提问者:小点点

错误:无法将字符串转换为浮点


我第一次玩sklearn和NLP,我想我了解我所做的一切,直到我不知道如何修复这个错误。以下是相关代码(主要改编自http://zacstewart.com/2015/04/28/document-classification-with-scikit-learn.html):

from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.pipeline import Pipeline, FeatureUnion
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import TruncatedSVD
from sgboost import XGBClassifier
from pandas import DataFrame

def read_files(path):
    for article in os.listdir(path):
        with open(os.path.join(path, doc)) as f:
            text = f.read()
        yield os.path.join(path, article), text

def build_data_frame(path, classification)
    rows = []
    index = []
    for filename, text in read_files(path):
        rows.append({'text': text, 'class': classification})
        index.append(filename)
    df = DataFrame(rows, index=index)
    return df

data = DataFrame({'text': [], 'class': []})
for path, classification in SOURCES: # SOURCES is a list of tuples
    data = data.append(build_data_frame(path, classification))
data = data.reindex(np.random.permutation(data.index))

classifier = Pipeline([
    ('features', FeatureUnion([
        ('text', Pipeline([
            ('tfidf', TfidfVectorizer()),
            ('svd', TruncatedSVD(algorithm='randomized', n_components=300)
            ])),
        ('words', Pipeline([('wscaler', StandardScaler())])),
    ])),
    ('clf, XGBClassifier(silent=False)),
])
classifier.fit(data['text'].values, data['class'].values)

加载到数据框中的数据是经过预处理的文本,包括所有停止字、标点符号、unicode、大写字母等。这是我在分类器上调用fit时遇到的错误,其中。。。表示应在管道中矢量化的文档之一:

ValueError: could not convert string to float: ...

我最初认为TfidfVectorizer()不工作,导致SVD算法出错,但在我从管道中提取每个步骤并按顺序执行之后,相同的错误只出现在XGBClassifier上。fit()。

更让我困惑的是,我试图在解释器中一步一步地将此脚本分割开来,但当我尝试导入read_文件或build_data_frame时,我的一个字符串出现了相同的ValueError,但这仅仅是在:

from classifier import read_files

我不知道这是怎么发生的,如果有人知道我明显的错误是什么,我会非常感激。试图自己思考这些概念,但遇到这样的问题让我感到非常无能为力。


共1个答案

匿名用户

管道的第一部分是FeatureUnionFeatureUnion将并行地将它获得的所有数据传递给所有内部零件。FeatureUnion的第二部分是包含单个StandardScaler的管道。这就是错误的根源。

这是您的数据流:

X --> classifier, Pipeline
            |
            |  <== X is passed to FeatureUnion
            \/
      features, FeatureUnion
                      |
                      |  <== X is duplicated and passed to both parts
        ______________|__________________
       |                                 |
       |  <===   X contains text  ===>   |                         
       \/                               \/
   text, Pipeline                   words, Pipeline
           |                                  |   
           |  <===    Text is passed  ===>    |
          \/                                 \/ 
       tfidf, TfidfVectorizer            wscaler, StandardScaler  <== Error
                 |                                   |
                 | <==Text converted to floats       |
                \/                                   |
              svd, TruncatedSVD                      |
                       |                             |
                       |                             |
                      \/____________________________\/
                                      |
                                      |
                                     \/
                                   clf, XGBClassifier

由于文本被传递到StandardScaler,因此会引发错误,StandardScaler只能用于数字特征。

正如使用TfidfVectorizer将文本转换为数字一样,在将文本发送到TruncatedSVD之前,您需要在StandardScaler之前执行相同的操作,否则只需为其提供数字功能。

查看有问题的描述,您是否打算在TruncatedSVD的结果之后保留StandardScaler?