forked from WecoAI/aideml
-
Notifications
You must be signed in to change notification settings - Fork 10
/
sentiment-analysis-on-movie-reviews.py
55 lines (40 loc) · 1.84 KB
/
sentiment-analysis-on-movie-reviews.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
import pandas as pd
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
# Load the training data
train_data = pd.read_csv("./input/train.tsv", sep="\t")
# Split the data into training and validation sets
X_train, X_val, y_train, y_val = train_test_split(
train_data["Phrase"], train_data["Sentiment"], test_size=0.2, random_state=42
)
# Initialize a TF-IDF Vectorizer
tfidf_vectorizer = TfidfVectorizer(stop_words="english", ngram_range=(1, 2))
# Fit and transform the training data
X_train_tfidf = tfidf_vectorizer.fit_transform(X_train.astype(str))
# Transform the validation data
X_val_tfidf = tfidf_vectorizer.transform(X_val.astype(str))
# Initialize the Logistic Regression model
logistic_regression_model = LogisticRegression(random_state=42)
# Train the model
logistic_regression_model.fit(X_train_tfidf, y_train)
# Predict the sentiments on the validation set
y_val_pred = logistic_regression_model.predict(X_val_tfidf)
# Calculate the accuracy on the validation set
accuracy = accuracy_score(y_val, y_val_pred)
print(f"Validation Accuracy: {accuracy}")
# Load the test data
test_data = pd.read_csv("./input/test.tsv", sep="\t")
# Preprocess the test data by filling NaN values with an empty string
test_data["Phrase"] = test_data["Phrase"].fillna("")
# Transform the test data using the same vectorizer
X_test_tfidf = tfidf_vectorizer.transform(test_data["Phrase"].astype(str))
# Predict the sentiments on the test set
test_predictions = logistic_regression_model.predict(X_test_tfidf)
# Prepare the submission file
submission = pd.DataFrame(
{"PhraseId": test_data["PhraseId"], "Sentiment": test_predictions}
)
# Save the submission file
submission.to_csv("./working/submission.csv", index=False)