python - 矢量化:不是有效的集合

标签 python python-2.7 machine-learning scikit-learn vectorization

我想矢量化一个包含我的 OneClassSVM 分类器训练语料库的 txt 文件。为此,我使用了 scikit-learn 库中的 CountVectorizer。 下面是我的代码:

def file_to_corpse(file_name, stop_words):
    array_file = []
    with open(file_name) as fd:
        corp = fd.readlines()
    array_file = np.array(corp)
    stwf = stopwords.words('french')
    for w in stop_words:
        stwf.append(w)
    vectorizer = CountVectorizer(decode_error = 'replace', stop_words=stwf, min_df=1)
    X = vectorizer.fit_transform(array_file)
    return X

当我在我的文件(大约 206346 行)上运行我的函数时,我收到以下错误并且我似乎无法理解它:

Traceback (most recent call last):
  File "svm.py", line 93, in <module>
    clf_svm.fit(training_data)
  File "/home/imane/anaconda/lib/python2.7/site-packages/sklearn/svm/classes.py", line 1028, in fit
    super(OneClassSVM, self).fit(X, np.ones(_num_samples(X)), sample_weight=sample_weight,
  File "/home/imane/anaconda/lib/python2.7/site-packages/sklearn/utils/validation.py", line 122, in _num_samples
    " a valid collection." % x)
TypeError: Singleton array array(<536172x13800 sparse matrix of type '<type 'numpy.int64'>'
    with 1952637 stored elements in Compressed Sparse Row format>, dtype=object) cannot be considered a valid collection.

有人可以帮我解决这个问题吗?我被困了一段时间 :)。

最佳答案

看源码就可以找到here例如,您会发现它会检查此条件是否为真(x 是您的数组)

if len(x.shape) == 0:

如果是这样,它会抛出这个异常

TypeError("Singleton array %r cannot be considered a valid collection." % x)

我建议您尝试找出 array_file 或您从该函数返回的值是否具有长度 > 0

关于python - 矢量化:不是有效的集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38101460/

相关文章:

python - 值错误: could not convert string to float: 'n'

machine-learning - 在深度学习方法中结合临床和图像数据的最佳方法是什么?

python - 使用泰勒级数逼近 cos

python - 获取一长串项目并将其 reshape 为数据框 "rows"- pandas python 3

json - 如何从获取响应正文捕获值 - 机器人框架

python - Selenium webdriver 能否在 sendkeys 之间设置一个随机时间(以模拟人类在打字时的行为)?

python - 仅将Python音频输出路由到虚拟录音设备

python - Vader SentimentIntensityAnalyzer 是多语言的吗?

python - pandas 中的条件滚动计算

java - 如何使用 PY4J 从 python 调用 java