我正在尝试使用sklearn模块中的朴素贝叶斯分类器来分类电影评论是否是正面的。我使用一袋单词作为每个评论的特征,并使用一个大型数据集,其中包含评论的情感评分。
df_bows = pd.DataFrame.from_records(bag_of_words)
df_bows = df_bows.fillna(0).astype(int)
这段代码创建了一个pandas数据帧,如下所示:
The Rock is destined to ... Staggeringly ’ ve muttering dissing
0 1 1 1 1 2 ... 0 0 0 0 0
1 2 0 1 0 0 ... 0 0 0 0 0
2 0 0 0 0 0 ... 0 0 0 0 0
3 0 0 1 0 4 ... 0 0 0 0 0
4 0 0 0 0 0 ... 0 0 0 0 0
然后,我尝试使用此代码将此数据框架与每次评论的情绪进行拟合
nb = MultinomialNB()
nb = nb.fit(df_bows, movies.sentiment > 0)
然而,我得到一个错误,它说
AttributeError: 'Series' object has no attribute 'to_coo'
这就是df电影的样子。
sentiment text
id
1 2.266667 The Rock is destined to be the 21st Century's ...
2 3.533333 The gorgeously elaborate continuation of ''The...
3 -0.600000 Effective but too tepid biopic
4 1.466667 If you sometimes like to go to the movies to h...
5 1.733333 Emerges as something rare, an issue movie that...
你能帮上忙吗?
发布于 2020-09-01 22:16:51
当您尝试拟合MultinomialNB
模型时,sklearn的例程会检查输入的df_bows
是否稀疏。如果是,就像我们的例子一样,需要将数据帧的类型更改为'Sparse'
。下面是我修复它的方法:
df_bows = pd.DataFrame.from_records(bag_of_words)
# Keep NaN values and convert to Sparse type
sparse_bows = df_bows.astype('Sparse')
nb = nb.fit(sparse_bows, movies['sentiment'] > 0)
熊猫文档链接:pandas.Series.sparse.to_coo
https://stackoverflow.com/questions/63021328
复制