-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathReviews.py
More file actions
159 lines (132 loc) · 5.57 KB
/
Reviews.py
File metadata and controls
159 lines (132 loc) · 5.57 KB
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
import pandas as pd
import nltk
import re
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
from nltk.stem import WordNetLemmatizer
from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer
from sklearn.model_selection import train_test_split
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics import accuracy_score
from sklearn.svm import SVC
from sklearn.naive_bayes import MultinomialNB
import matplotlib.pyplot as plt
import seaborn as sns
class DataPreprocessor:
def __init__(self, filename):
self.filename = filename
def load_data(self):
return pd.read_csv(self.filename)
def clean_text(self, text):
if pd.isnull(text):
return ''
text = text.lower()
text = re.sub(r'http\S+|www.\S+', '', text)
text = re.sub(r'[^a-zA-Z\s]', '', text)
words = word_tokenize(text)
words = [self.lemmatizer.lemmatize(word) for word in words if word not in self.stop_words]
return ' '.join(words)
def preprocess_data(self, df):
df.drop(columns=self.columns_to_drop, inplace=True)
df.dropna(subset=self.text_columns, inplace=True)
for column in self.text_columns:
df[column] = df[column].apply(self.clean_text)
return df
def initialize_nltk(self):
nltk.download('punkt')
nltk.download('stopwords')
nltk.download('wordnet')
self.stop_words = set(stopwords.words('english'))
self.lemmatizer = WordNetLemmatizer()
def setup(self):
self.initialize_nltk()
self.columns_to_drop = ['Clothing ID', 'Age', 'Recommended IND', 'Positive Feedback Count', 'Division Name',
'Department Name', 'Class Name']
self.text_columns = ['Title', 'Review Text']
class SentimentAnalyzer:
def __init__(self):
self.analyzer = SentimentIntensityAnalyzer()
def get_sentiment_scores(self, text):
return self.analyzer.polarity_scores(text)['compound']
def classify_sentiment(self, score):
if score >= 0.05:
return 'Positive'
elif score <= -0.05:
return 'Negative'
else:
return 'Neutral'
class SentimentClassifier:
def __init__(self):
pass
def convert_rating_to_sentiment(self, rating):
if rating == 5 or rating == 4:
return 'Positive'
elif rating == 1 or rating == 2:
return 'Negative'
else:
return 'Neutral'
def calculate_accuracy(self, actual_sentiment, predicted_sentiment):
return accuracy_score(actual_sentiment, predicted_sentiment)
class SVMClassifier:
def __init__(self):
self.classifier = SVC(kernel='linear', random_state=42)
self.vectorizer = TfidfVectorizer(max_features=5000)
def train(self, X_train, y_train):
X_train_tfidf = self.vectorizer.fit_transform(X_train)
self.classifier.fit(X_train_tfidf, y_train)
def predict(self, X_test):
X_test_tfidf = self.vectorizer.transform(X_test)
return self.classifier.predict(X_test_tfidf)
class NBClassifier:
def __init__(self):
self.classifier = MultinomialNB()
self.vectorizer = TfidfVectorizer(max_features=5000)
def train(self, X_train, y_train):
X_train_tfidf = self.vectorizer.fit_transform(X_train)
self.classifier.fit(X_train_tfidf, y_train)
def predict(self, X_test):
X_test_tfidf = self.vectorizer.transform(X_test)
return self.classifier.predict(X_test_tfidf)
class Visualizer:
def __init__(self):
pass
def plot_histogram(self, data):
plt.hist(data, bins=20, color='skyblue', edgecolor='black')
plt.xlabel('Sentiment Score')
plt.ylabel('Frequency')
plt.title('Histogram of Sentiment Scores')
plt.show()
def plot_bar_chart(self, x, y):
plt.figure(figsize=(8, 6))
sns.barplot(x=x, y=y, palette='viridis')
plt.xlabel('Sentiment Category')
plt.ylabel('Count')
plt.title('Bar Chart of Sentiment Categories')
plt.show()
# Usage example
if __name__ == "__main__":
preprocessor = DataPreprocessor('AD.csv')
preprocessor.setup()
df = preprocessor.load_data()
df = preprocessor.preprocess_data(df)
sentiment_analyzer = SentimentAnalyzer()
df['sentiment_score'] = df['Review Text'].apply(sentiment_analyzer.get_sentiment_scores)
df['sentiment'] = df['sentiment_score'].apply(sentiment_analyzer.classify_sentiment)
sentiment_classifier = SentimentClassifier()
df['actual_sentiment'] = df['Rating'].apply(sentiment_classifier.convert_rating_to_sentiment)
accuracy = sentiment_classifier.calculate_accuracy(df['actual_sentiment'], df['sentiment'])
print("Accuracy:", accuracy)
svm_classifier = SVMClassifier()
X_train, X_test, y_train, y_test = train_test_split(df['Review Text'], df['sentiment'], test_size=0.2, random_state=42)
svm_classifier.train(X_train, y_train)
y_pred = svm_classifier.predict(X_test)
accuracy = accuracy_score(y_test, y_pred)
print("SVM Classifier Accuracy:", accuracy)
nb_classifier = NBClassifier()
nb_classifier.train(X_train, y_train)
y_pred = nb_classifier.predict(X_test)
accuracy = accuracy_score(y_test, y_pred)
print("Naive Bayes Classifier Accuracy:", accuracy)
visualizer = Visualizer()
visualizer.plot_histogram(df['sentiment_score'])
visualizer.plot_bar_chart(df['sentiment'].value_counts().index, df['sentiment'].value_counts().values)