AttributeError:“Series”对象没有“to_coo”属性

2024-06-26 11:25:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图使用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...

你能帮忙吗


Tags: oftheto数据代码df电影is
1条回答
网友
1楼 · 发布于 2024-06-26 11:25:36

当您试图适应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

相关问题 更多 >