CountVectorizer with Pandas dataframe



我正在使用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 行带有句子。

我做错了什么?我正在学习本教程。

(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}

最新更新