我编写了一个程序,它获取包含推文和标签的 Twitter 数据(0
表示中性情绪,1
表示负面情绪)并预测推文的类别属于。
该程序在训练和测试集上运行良好。但是,我在使用字符串应用预测函数时遇到问题。我不知道该怎么做。
我尝试按照调用预测函数之前清理数据集的方式清理字符串,但返回的值形状错误。
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])
将新推文转换为现有文档术语矩阵。这将以正确的形状返回推文。
关于python - Twitter 对字符串的情感分析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56872294/