【问题标题】:Python Sci-Kit Learn : Multilabel Classification ValueError: could not convert string to float:Python Sci-Kit 学习:多标签分类 ValueError:无法将字符串转换为浮点数:
【发布时间】:2016-03-20 10:22:10
【问题描述】:

我正在尝试使用 sci-kit learn 0.17 进行多标签分类 我的数据看起来像

训练

Col1                  Col2
asd dfgfg             [1,2,3]
poioi oiopiop         [4]

测试

Col1                    
asdas gwergwger    
rgrgh hrhrh

到目前为止我的代码

import numpy as np
from sklearn import svm, datasets
from sklearn.metrics import precision_recall_curve
from sklearn.metrics import average_precision_score
from sklearn.cross_validation import train_test_split
from sklearn.preprocessing import label_binarize
from sklearn.multiclass import OneVsRestClassifier

def getLabels():
    traindf = pickle.load(open("train.pkl","rb"))
    X = traindf['Col1']
    y = traindf['Col2']

    # Binarize the output
    from sklearn.preprocessing import MultiLabelBinarizer  
    y=MultiLabelBinarizer().fit_transform(y)      

    random_state = np.random.RandomState(0)


    # Split into training and test
    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=.5,
                                                        random_state=random_state)

    # Run classifier
    from sklearn import svm, datasets
    classifier = OneVsRestClassifier(svm.SVC(kernel='linear', probability=True,
                                     random_state=random_state))
    y_score = classifier.fit(X_train, y_train).decision_function(X_test)

但现在我明白了

ValueError: could not convert string to float: <value of Col1 here>

y_score = classifier.fit(X_train, y_train).decision_function(X_test) 

我也必须对 X 进行二值化吗?为什么我需要将 X 维度转换为浮点数?

【问题讨论】:

  • “您似乎在使用旧的多标签数据表示。不再支持序列序列;请改用二进制数组或稀疏矩阵。” - 你看到了吗?
  • 如何将标签转换为二进制数组?
  • this不是同一个问题吗?
  • 差不多,但我这里没有使用 LogisticRegression

标签: python machine-learning scikit-learn multilabel-classification


【解决方案1】:

是的,您必须将 X 和 y 转换为数字表示(不需要二进制)。这是因为所有机器学习方法都在数字矩阵上运行。

如何做到这一点?如果 Col1 中的每个样本都可以包含不同的单词(即它代表一些文本) - 您可以使用 CountVectorizer

转换该列
from sklearn.feature_extraction.text import CountVectorizer

col1 = ["cherry banana", "apple appricote", "cherry apple", "banana apple appricote cherry apple"]

cv = CountVectorizer()
cv.fit_transform(col1) 
#<4x4 sparse matrix of type '<class 'numpy.int64'>'
#   with 10 stored elements in Compressed Sparse Row format>

cv.fit_transform(col1).toarray()
#array([[0, 0, 1, 1],
#       [1, 1, 0, 0],
#       [1, 0, 0, 1],
#       [2, 1, 1, 1]], dtype=int64)

【讨论】:

    猜你喜欢
    • 2019-11-07
    • 2019-10-14
    • 2021-01-11
    • 2018-04-23
    • 2015-03-25
    • 2021-12-23
    • 2017-08-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多