【发布时间】:2021-05-18 07:05:46
【问题描述】:
我使用朴素贝叶斯训练了一个模型。我的准确率很高,但是现在我想给一个句子然后我想看看它的情绪。这是我的代码:
# data Analysis
import pandas as pd
# data Preprocessing and Feature Engineering
from textblob import TextBlob
import re
from nltk.corpus import stopwords
from sklearn.feature_extraction.text import TfidfVectorizer
# Model Selection and Validation
from sklearn.naive_bayes import MultinomialNB
from sklearn.model_selection import train_test_split
from sklearn.metrics import confusion_matrix, classification_report, accuracy_score
import joblib
import warnings
import mlflow
warnings.filterwarnings("ignore")
train_tweets = pd.read_csv('data/train.csv')
tweets = train_tweets.tweet.values
labels = train_tweets.label.values
processed_features = []
for sentence in range(0, len(tweets)):
# Remove all the special characters
processed_feature = re.sub(r'\W', ' ', str(tweets[sentence]))
# remove all single characters
processed_feature= re.sub(r'\s+[a-zA-Z]\s+', ' ', processed_feature)
# Remove single characters from the start
processed_feature = re.sub(r'\^[a-zA-Z]\s+', ' ', processed_feature)
# Substituting multiple spaces with single space
processed_feature = re.sub(r'\s+', ' ', processed_feature, flags=re.I)
# Removing prefixed 'b'
processed_feature = re.sub(r'^b\s+', '', processed_feature)
# Converting to Lowercase
processed_feature = processed_feature.lower()
processed_features.append(processed_feature)
vectorizer = TfidfVectorizer(max_features=2500, min_df=7, max_df=0.8, stop_words=stopwords.words('english'))
processed_features = vectorizer.fit_transform(processed_features).toarray()
X_train, X_test, y_train, y_test = train_test_split(processed_features, labels, test_size=0.2, random_state=0)
text_classifier = MultinomialNB()
text_classifier.fit(X_train, y_train)
predictions = text_classifier.predict(X_test)
print(confusion_matrix(y_test,predictions))
print(classification_report(y_test,predictions))
print(accuracy_score(y_test, predictions))
joblib.dump(text_classifier, 'model.pkl')
如您所见,我正在保存我的模型。现在,我想给出这样的输入:
new_sentence = "I am very happy today"
model.predict(new_sentence)
我想看到这样的输出:
sentence = "I am very happy today"
sentiment = Positive
我该怎么做?
【问题讨论】:
标签: machine-learning scikit-learn nlp sentiment-analysis