-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.py
79 lines (63 loc) · 2.47 KB
/
utils.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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
import kagglehub
import pandas as pd
import numpy as np
import nltk
from sklearn.model_selection import train_test_split
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import classification_report, confusion_matrix, f1_score
import re
from nltk.sentiment.vader import SentimentIntensityAnalyzer
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
from nltk.stem import WordNetLemmatizer
from tqdm import tqdm
nltk.download('all')
lemmatizer = WordNetLemmatizer()
stop_words = set(stopwords.words('english'))
analyzer = SentimentIntensityAnalyzer()
# create preprocess_text function
def preprocess_text(text):
# Tokenize the text
tokens = word_tokenize(text.lower())
# Remove stop words
filtered_tokens = [token for token in tokens if token not in stop_words]
# Lemmatize the tokens
lemmatized_tokens = [lemmatizer.lemmatize(token) for token in filtered_tokens]
# Join the tokens back into a string
processed_text = ' '.join(lemmatized_tokens)
return processed_text
def nltk_get_sentiment(text):
scores = analyzer.polarity_scores(text)
sentiment = 1 if scores['pos'] > 0 else 0
return sentiment
def train(X_train, y_train, classifier):
"""Train the sentiment analysis model"""
print("Training model...")
classifier.fit(X_train, y_train)
def evaluate(y_pred, y_test):
print("\nClassification Report:")
print(classification_report(y_test, y_pred))
print("\nConfusion Matrix:")
print(confusion_matrix(y_test, y_pred))
print("\n F1-Score = ", f1_score(y_test, y_pred))
return
def predict(text, vectorizer, classifier):
"""Predict sentiment for new text"""
processed_text = preprocess_text(text)
vectorized_text = vectorizer.transform([processed_text])
prediction = classifier.predict(vectorized_text)
probability = classifier.predict_proba(vectorized_text)
return {
'sentiment': 'positive' if prediction[0] == 1 else 'negative',
'confidence': max(probability[0])
}
def tfid_predict(X_train, y_train, X_test):
tfid_vectorizer = TfidfVectorizer(max_features=5000)
classifier = LogisticRegression(max_iter=1000)
# Vectorize text
print("Vectorizing text...")
X_train_vec = tfid_vectorizer.fit_transform(X_train)
X_test_vec = tfid_vectorizer.transform(X_test)
train(X_train_vec, y_train, classifier)
return classifier.predict(X_test_vec)