| import pandas as pd
|
| import torch
|
| import numpy
|
| import torch.nn as nn
|
| import torch.optim as optim
|
| from sklearn.feature_extraction.text import CountVectorizer
|
|
|
|
|
| data = {
|
| "text": [
|
| "This movie was great",
|
| "I did not like this movie",
|
| "The acting was terrible",
|
| "I loved the plot",
|
| "It was a boring experience",
|
| "What a fantastic film!",
|
| "I hated it",
|
| "It was okay",
|
| "Absolutely wonderful!",
|
| "Not my favorite"
|
| "Was very good"
|
| "Very good"
|
| ],
|
| "label": [
|
| 1,
|
| 0,
|
| 0,
|
| 1,
|
| 0,
|
| 1,
|
| 0,
|
| 0,
|
| 1,
|
| 0,
|
| 1,
|
| 1
|
| ]
|
| }
|
|
|
|
|
| df = pd.DataFrame(data)
|
| df.to_csv("data.csv", index=False)
|
|
|
|
|
| df = pd.read_csv("data.csv")
|
|
|
|
|
| vectorizer = CountVectorizer()
|
| X = vectorizer.fit_transform(df["text"]).toarray()
|
| y = df["label"].values
|
|
|
|
|
| X_tensor = torch.tensor(X, dtype=torch.float32)
|
| y_tensor = torch.tensor(y, dtype=torch.float32).view(-1, 1)
|
|
|
|
|
| class SentimentAnalysisModel(nn.Module):
|
| def __init__(self, input_size):
|
| super(SentimentAnalysisModel, self).__init__()
|
| self.fc1 = nn.Linear(input_size, 8)
|
| self.fc2 = nn.Linear(8, 1)
|
| self.relu = nn.ReLU()
|
|
|
| def forward(self, x):
|
| x = self.relu(self.fc1(x))
|
| x = torch.sigmoid(self.fc2(x))
|
| return x
|
|
|
|
|
| input_size = X.shape[1]
|
| model = SentimentAnalysisModel(input_size)
|
|
|
| criterion = nn.BCELoss()
|
| optimizer = optim.Adam(model.parameters(), lr=0.01)
|
|
|
|
|
| epochs = 100
|
|
|
| for epoch in range(epochs):
|
|
|
| y_pred = model(X_tensor)
|
|
|
|
|
| loss = criterion(y_pred, y_tensor)
|
|
|
|
|
| optimizer.zero_grad()
|
|
|
|
|
| loss.backward()
|
| optimizer.step()
|
|
|
|
|
| if (epoch+1) % 10 == 0:
|
| print(f"Epoch [{epoch+1}/{epochs}], Loss: {loss.item():.4f}")
|
|
|
|
|
| def predict_sentiment(text):
|
|
|
| text_vectorized = vectorizer.transform([text]).toarray()
|
| text_tensor = torch.tensor(text_vectorized, dtype=torch.float32)
|
|
|
|
|
| output = model(text_tensor)
|
|
|
|
|
| prediction = 1 if output.item() > 0.5 else 0
|
|
|
| return "Positive" if prediction == 1 else "Negative"
|
|
|
|
|
| print(predict_sentiment("I really enjoyed this movie!"))
|
| print(predict_sentiment("This was the worst experience ever."))
|
| print(predict_sentiment("It was just okay, nothing special."))
|
| print(predict_sentiment("Absolutely loved the storyline!"))
|
|
|