python - 带有 Pandas 数据框的 CountVectorizer

标签 python python-3.x scikit-learn

我正在使用 scikit-learn 进行文本处理,但我的 CountVectorizer 没有给出我期望的输出。

我的 CSV 文件如下所示:

"Text";"label"
"Here is sentence 1";"label1"
"I am sentence two";"label2"
...

等等。

我想先使用 Bag-of-Words 来理解 python 中的 SVM 是如何工作的:

import pandas as pd
from sklearn import svm
from sklearn.feature_extraction.text import CountVectorizer

data = pd.read_csv(open('myfile.csv'),sep=';')

target = data["label"]
del data["label"]

# Creating Bag of Words
count_vect = CountVectorizer()
X_train_counts = count_vect.fit_transform(data)
X_train_counts.shape 
count_vect.vocabulary_.get(u'algorithm')

但是当我执行 print(X_train_counts.shape) 时,我看到输出只有 (1,1),而我有 1048 行句子。

我做错了什么?我正在关注 this教程。

(count_vect.vocabulary_.get(u'algorithm') 的输出也是None。)

最佳答案

问题出在 count_vect.fit_transform(data) 中。该函数需要一个可生成字符串的可迭代对象。不幸的是,这些是错误的字符串,可以用一个简单的例子来验证。

for x in data:
    print(x)
# Text

只打印列名;迭代给出列而不是 data['Text'] 的值。你应该这样做:

X_train_counts = count_vect.fit_transform(data.Text)
X_train_counts.shape 
# (2, 5)
count_vect.vocabulary_
# {'am': 0, 'here': 1, 'is': 2, 'sentence': 3, 'two': 4}

关于python - 带有 Pandas 数据框的 CountVectorizer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44083683/

相关文章:

python nsolve/求解方程组

python - scikit 学习决策树模型评估

python - 如何使用 randomsearchcv 优化 F1 分数和预测速度?

scikit-learn - sklearn : ValueError: X and Y have incompatible shapes

java - 艾略特波浪计算器,图表模式识别

python - 暴力算法奶牛运输的问题

python - 通过cron job将数据存入redis

python-3.x - gsutil 不适用于 mac 和 python3.5

django - 是否可以将第二个 slug 添加到 Django 中的 URL 路径?

django - 如何在 Django REST Framework 中返回自定义 JSON 输出