【问题标题】:Run SVM on IRIS DataSet and get ValueError: Unknown label type: 'unknown'在 IRIS 数据集上运行 SVM 并得到 ValueError: Unknown label type: 'unknown'
【发布时间】:2017-04-28 22:40:33
【问题描述】:

谁能简单地向我解释一下? 为了您的方便,我附上了完整的代码。

我有这段代码可以加载 IRIS 数据集并运行 SVM:

from sklearn import svm
import pandas as pd


def prepare_iris_DS():
    print("Loading iris DS...")
    url = 'http://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data'
    iris = pd.read_csv(url, names=["sepal length", "sepal width", "petal length", "petal width", "Species"])
    df = pd.DataFrame(iris, columns=["sepal length", "sepal width", "petal length", "petal width", "Species"])

    df.head()
    iris.head()

    print("Iris DS is Loaded")

    columns, labels = ["sepal length", "sepal width"], ["Iris-setosa", "Iris-virginica"]

    total = df.shape[0]
    df = df[df.Species.isin(labels)]
    X = df[columns]

    print("selected {0} entries out of {1} from the dataset based on labels {2}".format(len(X), total, str(labels)))

    Y = df[["Species"]]
    Y.loc[Y.Species != labels[0], 'Species'] = 0.0
    Y.loc[Y.Species == labels[0], 'Species'] = 1.0

    X = X.as_matrix()
    Y = Y.as_matrix()

    return X, Y


X, Y = prepare_iris_DS()

rbf_svc = svm.SVC(kernel='rbf', gamma=0.1, C=0.1)
rbf_svc.fit(X, Y)

我在最后一行不断收到错误:rbf_svc.fit(X, Y)

File "C:\Anaconda2\lib\site-packages\sklearn\utils\multiclass.py", line 172, in check_classification_targets

raise ValueError("Unknown label type: %r" % y_type)

ValueError: Unknown label type: 'unknown'

但是...
当我输入这个命令时,它就可以正常工作了。
我不明白为什么?我很欣赏一个清晰/简单的答案

Y = Y.as_matrix().astype(float)

【问题讨论】:

    标签: python pandas scikit-learn dataset


    【解决方案1】:

    当:Y = Y.as_matrix(),观察目标数组的数据类型:

    >>> Y.dtype
    object
    

    SVCfit 方法需要一个可迭代的数值数组作为它的训练向量 X。但是目前,您向其传递了一个不正确的数字字符串值数组。

    这是因为 Y 在直接分配给它时继承了 df[['Species]]dtypes。因此,即使您在 loc 操作期间执行了布尔索引并通过将字符串值替换为布尔值 (0/1) 来摆脱字符串值,Y的 dtype > 不受影响,仍然是object 类型。

    因此,需要将它们类型转换回int/float dtype,然后fit 函数可以理解。

    Y = Y.as_matrix().astype(float).ravel()  # ravel to flatten the 2D array to 1D
    

    现在,当你测试时:

    >>> Y.dtype
    float64
    

    此外,您还可以添加以下更改:

    X = df[columns].copy()
    Y = df[["Species"]].copy()
    

    通过创建数据帧的深层副本而不是直接分配它来避免 SettingWithCopyWarning 警告。

    【讨论】:

    • 感谢您的出色回答。但是为什么我在为 X 取矩阵时不需要做 astype(float) 呢?我的意思是:X = X.as_matrix()
    • 您不需要为 X 执行任何类型转换,因为您为 X 分配的 DF 子集已经包含浮点数- 即(萼片长度,萼片宽度,花瓣长度,花瓣宽度)都是dtype float64。但是 species 列不是。因此,只需要将 Y 设为数字类型。
    • 非常感谢。这很有帮助!
    猜你喜欢
    • 2019-03-21
    • 2021-01-21
    • 1970-01-01
    • 2018-01-26
    • 2016-03-24
    • 2014-12-17
    • 2018-01-14
    • 2022-08-22
    • 1970-01-01
    相关资源
    最近更新 更多