【问题标题】:How can I make sentiment analysis with new sentence on trained model?如何在经过训练的模型上使用新句子进行情感分析?
【发布时间】: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


    【解决方案1】:

    首先,将预处理放在一个函数中:

    def preproc(tweets):
        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)
    
        return processed_features
    
    processed_features = preproc(tweets)
    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()
    

    然后使用它来预处理测试字符串并使用transform将其提供给分类器:

    # feeding two 1-sentence tweets:
    test = preproc([["I hate this book."], ["I love this movie."]])
    predictions = text_classifier.predict(vectorizer.transform(test).toarray())
    print(predictions) 
    

    现在,根据您在数据集中拥有的标签以及train_tweets.label.values 的编码方式,您将获得不同的输出,您可以将其解析为字符串。例如,如果数据集中的标签编码为 1=positive 和 0=negative,您可能会得到 [0,1]。

    【讨论】:

    • 太棒了。谢谢您的帮助。但是我在这里还有另一个问题:每当我输入 print(predictions) 时,它都会返回混淆矩阵、分类报告和 [0,1] 的准确度分数。我怎样才能解决这个问题 ?我只想看到 [0,1] (更新!!)实际上我通过删除 print(confusion_matrix(y_test,predictions)) print(classification_report(y_test,predictions)) print(accuracy_score(y_test, predictions)) 解决了这个问题,但是其实我没看懂:D 它与它有什么关系?
    • @ByUnal 我不确定我是否理解您的问题,每个控制台输出都与打印语句相关联,如果您删除一个,它将不再在控制台上输出。
    猜你喜欢
    • 1970-01-01
    • 2020-10-27
    • 2017-03-13
    • 2014-01-16
    • 2020-07-04
    • 1970-01-01
    • 2022-08-19
    • 2018-08-28
    • 1970-01-01
    相关资源
    最近更新 更多