我正在使用scikit中的TfidfVectorizer学习从文本数据中提取一些特征。我有一个CSV文件,有一个分数(可以是+1或-1)和一个评论(文本)。我把这些数据放到一个数据框中,这样我就可以运行矢量器了。
这是我的代码:
import pandas as pd
import numpy as np
from sklearn.feature_extraction.text import TfidfVectorizer
df = pd.read_csv("train_new.csv",
names = ['Score', 'Review'], sep=',')
# x = df['Review'] == np.nan
#
# print x.to_csv(path='FindNaN.csv', sep=',', na_rep = 'string', index=True)
#
# print df.isnull().values.any()
v = TfidfVectorizer(decode_error='replace', encoding='utf-8')
x = v.fit_transform(df['Review'])
这是我得到的错误的回溯:
Traceback (most recent call last):
File "/home/PycharmProjects/Review/src/feature_extraction.py", line 16, in <module>
x = v.fit_transform(df['Review'])
File "/home/b/hw1/local/lib/python2.7/site- packages/sklearn/feature_extraction/text.py", line 1305, in fit_transform
X = super(TfidfVectorizer, self).fit_transform(raw_documents)
File "/home/b/work/local/lib/python2.7/site-packages/sklearn/feature_extraction/text.py", line 817, in fit_transform
self.fixed_vocabulary_)
File "/home/b/work/local/lib/python2.7/site- packages/sklearn/feature_extraction/text.py", line 752, in _count_vocab
for feature in analyze(doc):
File "/home/b/work/local/lib/python2.7/site-packages/sklearn/feature_extraction/text.py", line 238, in <lambda>
tokenize(preprocess(self.decode(doc))), stop_words)
File "/home/b/work/local/lib/python2.7/site-packages/sklearn/feature_extraction/text.py", line 118, in decode
raise ValueError("np.nan is an invalid document, expected byte or "
ValueError: np.nan is an invalid document, expected byte or unicode string.
我检查了CSV文件和DataFrame,看是否有被读取为NaN的内容,但找不到任何内容。共有18000行,没有一行返回isnan
为True。
这就是df['Review'].head()
的样子:
0 This book is such a life saver. It has been s...
1 I bought this a few times for my older son and...
2 This is great for basics, but I wish the space...
3 This book is perfect! I'm a first time new mo...
4 During your postpartum stay at the hospital th...
Name: Review, dtype: object
我找到了一个更有效的方法来解决这个问题。
当然,您可以使用
df['Review'].values.astype('U')
来转换整个系列。但是我发现如果要转换的序列非常大,使用这个函数将消耗更多的内存。(我用一个80w行数据的系列测试这个,这样做astype('U')
将消耗大约96GB的内存)相反,如果使用lambda表达式只将序列中的数据从
str
转换为numpy.str_
,结果也将被fit_transform
函数接受,则速度会更快,不会增加内存使用量。我不确定为什么这样做,因为在TFIDF矢量器的Doc页中:
但实际上这个iterable必须产生
np.str_
,而不是str
。您需要将数据类型
object
转换为unicode
字符串,正如回溯中明确提到的那样。从TFIDF矢量器的Doc页:
相关问题 更多 >
编程相关推荐