python - 如何将一条推文输入分类器模型?

标签 python machine-learning nlp classification tweepy

我正在编写一个 Python 代码,其中涉及使用自然语言处理分析数据集并验证 Twitter 更新。我的随机森林模型运行良好。

dataset = pd.read_csv('bully.txt', delimiter ='\t', quoting = 3)

corpus = []
for i in range(0,8576):
    tweet = re.sub('[^a-zA-Z]', ' ', dataset['tweet'][i])
    tweet = tweet.lower()
    tweet = tweet.split()
    ps = PorterStemmer()
    tweet = [ps.stem(word) for word in tweet if not word in 
 set(stopwords.words('english'))]
    tweet = ' '.join(tweet)
    corpus.append(tweet)

将数据集转换为向量

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

分为训练数据和测试数据

from sklearn.cross_validation import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.20, random_state = 0)

分类器模型

from sklearn.ensemble import RandomForestClassifier
classifier = RandomForestClassifier()
classifier.fit(X_train, y_train)

y_pred = classifier.predict(X_test)

这是我访问推文的代码:

for status in tweepy.Cursor(api.home_timeline).items(1):
    print "tweet: "+ status.text.encode('utf-8')
    corpus1 = []
    update = status.text
    update = re.sub('[^a-zA-Z]', ' ', update)
    update = update.lower()
    update = update.split()
    ps = PorterStemmer()
    update = [ps.stem(word) for word in update if not word in set(stopwords.words('english'))]
    update = ' '.join(update)
    corpus1.append(update)

当我尝试使用模型对提取的 Twitter 更新进行分类时:

if classifier.predict(update):
    print "bullying"

else:
    print "not bullying"

我收到此错误:

ValueError: could not convert string to float: dude

如何向模型提供一条推文?

我的数据集是这样的:https://drive.google.com/open?id=1BG3cFszsZjAJ_pcST2jRxDH0ukf411M-

最佳答案

您将使用 CountVectorizer 将文本数据转换为数字数组,其中行表示文档,列表示单词。因此,这意味着您的模型接受一组数字作为输入。如果您尝试直接用字符串预测 a,模型将不知道如何解释它。

要解决这个问题,您需要转换模型可以理解的字符串。

update=cv.transform([update])
if classifier.predict(update):
    print "bullying"

else:
    print "not bullying"

CountVectorizer 不直接获取字符串对象,因此会传递该项目的列表。

关于python - 如何将一条推文输入分类器模型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47697880/

相关文章:

python - SpaCy 中的自定义句子边界检测

python - 如何找到circusd的pid文件?

python - 位置权限弹出窗口

python - 使用 collections.Iterable 在 python 中展平不规则列表时,列表不会作为最终对象返回

machine-learning - 神经网络可以有整数输入吗?

objective-c - C/C++/Obj-C 的词性标注和命名实体识别

python - 使用 if/else 语句创建一个新的可变数值列

machine-learning - PCA 使我的图像变得垃圾

python - Tensorflow:保存和恢复TensorFlowEstimator()的方法

java - 斯坦福 NLP OpenIE 无法识别某些句子的三元组