Skip to main content
 首页 » 编程设计

python之在 IRIS DataSet 上运行 SVM 并得到 ValueError : Unknown label type: 'unknown'

2024年10月17日8飞鱼

谁能简单的给我解释一下? 为了您的方便,我提供了完整的代码。

我有这段加载 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) 

请您参考如下方法:

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

>>> Y.dtype 
object 

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

这是因为 Y 在直接分配给它时继承了 df[['Species]] 的 dtypes。因此,即使您在 loc 操作期间执行了 bool 索引并通过用 bool 值 (0/1) 替换字符串值来摆脱了字符串值,Y 不受影响,仍然是 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 警告。