Python 基于字符串的Twitter情感分析

Python 基于字符串的Twitter情感分析,python,machine-learning,scikit-learn,nlp,sentiment-analysis,Python,Machine Learning,Scikit Learn,Nlp,Sentiment Analysis,我写了一个程序,它获取一条推特数据,其中包含推特,0表示中性情绪,1表示消极情绪,并预测推特属于哪一类。 该程序在训练和测试集上运行良好。但是,我在使用字符串应用预测函数时遇到了问题。我不知道该怎么做 我尝试过在调用predict函数之前清理数据集的方式来清理字符串,但是返回的值的形状不正确 import numpy as np import pandas as pd from nltk.corpus import stopwords from nltk.stem.porter import P

我写了一个程序,它获取一条推特数据,其中包含推特,0表示中性情绪,1表示消极情绪,并预测推特属于哪一类。 该程序在训练和测试集上运行良好。但是,我在使用字符串应用预测函数时遇到了问题。我不知道该怎么做

我尝试过在调用predict函数之前清理数据集的方式来清理字符串,但是返回的值的形状不正确

import numpy as np
import pandas as pd
from nltk.corpus import stopwords
from nltk.stem.porter import PorterStemmer
ps = PorterStemmer()
import re

#Loading dataset
dataset = pd.read_csv('tweet.csv')

#List to hold cleaned tweets
clean_tweet = []

#Cleaning tweets
for i in range(len(dataset)):
    tweet = re.sub('[^a-zA-Z]', ' ', dataset['tweet'][i])
    tweet = re.sub('@[\w]*',' ',dataset['tweet'][i])
    tweet = tweet.lower()
    tweet = tweet.split()
    tweet = [ps.stem(token) for token in tweet if not token in set(stopwords.words('english'))]
    tweet = ' '.join(tweet)
    clean_tweet.append(tweet)

from sklearn.feature_extraction.text import CountVectorizer
cv = CountVectorizer(max_features = 3000)
X = cv.fit_transform(clean_tweet)
X =  X.toarray()
y = dataset.iloc[:, 1].values

from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y)

from sklearn.naive_bayes import GaussianNB
n_b = GaussianNB()
n_b.fit(X_train, y_train)
y_pred  = n_b.predict(X_test) 

some_tweet = "this is a mean tweet"  # How to apply predict function to this string
在新字符串上使用cv.transform[cleaned_new_tweet]将新tweet转换为现有文档术语矩阵。这将以正确的形状返回Tweet。

tl;博士 .predict需要一个字符串列表。所以你需要在列表中添加一些tweet。例如,new_tweet=[这是一条普通的tweet]

你的代码 您的代码中有一些问题,我试图为您解决

将numpy作为np导入 作为pd进口熊猫 从nltk.corpus导入停止词 从nltk.stem.porter导入PorterStemmer ps=PorterStemmer 进口稀土 加载数据集 dataset=pd.read_csv'tweet.csv' 定义清洗功能 您可以将它定义为一个函数,以便在其他地方可以轻松地重复使用 def clean_tweet:str: tweet=re.sub'[^a-zA-Z]','',数据集['tweet'][i] tweet=re.sub'@[\w]*','',tweet BUG:您需要传递您在此处修改的tweet,而不是原来的tweet tweet=tweet.lower tweet=tweet.split tweet=[ps.stemtoken用于tweet中的标记,如果不是setstopwords中的标记。单词'english'] tweet=''.jointweet 返回推文 保存已清理推文和标签的列表 X=[clean_tweet for tweet in dataset['tweet']]您可以使用新函数直接创建X y=dataset.iloc[:,1]。值 定义单个模型 从sklearn.feature\u extraction.text导入countvectorier 从sklearn.naive_bayes导入GaussianNB 从sklearn.pipeline导入管道 使用管道作为分类器,这样您就不需要一直调用变换和拟合。 分类器=管道 [ “cv”,CountVectorZerMax_特征=300, “n_b”,GaussianNB ] 在您训练CountVectorier之前,请先进行训练/测试。那是个巨大的错误。 首先拆分为“训练/拆分”,然后训练模型的所有步骤。 从sklearn.model\u选择导入列车\u测试\u拆分 X_列,X_测试,y_列,y_测试=X,y列 在这里,您可以一次性完成管道的所有步骤。 1.fitX_列,y_列 y_pred=分类器.predictX_测试 预测新推特 some_tweet=这是一条普通的tweet some_tweet=clean_tweet some_tweet重复使用您的clean功能 predicted=分类器。predicted[一些推文]将推文放入列表中!!!!
我的新字符串上的cv.transform给了我一个错误-ValueError:Iterable超过原始文本文档,收到字符串对象。很抱歉,cv.transform接受类型为Iterable的对象,因此您需要在Iterable中添加新的_tweet部分。我已经更新了答案,应该可以了。谢谢,成功了。然而,你能告诉我为什么cv.fit_变换在这里是错误的吗?这将为你指明正确的方向。非常感谢你。你能在你提到的管道上共享一个好的资源吗。我是新来的,我还没学会。此外,拆分是否会提高任何性能,或者它只是有助于以后计算各种分数,并且在培训/测试拆分方面会有大量的详细信息。