无法运行适合 svm 的方法(通过 scikit-learn)

Posted

技术标签:

【中文标题】无法运行适合 svm 的方法(通过 scikit-learn)【英文标题】:Unable to run the method fit for svm (by scikit-learn) 【发布时间】:2015-08-22 00:07:03 【问题描述】:

我正在尝试使用 sklearn 库生成 svm 预测器。 但是,每次我尝试运行 fit(X,Y) 时都会收到以下错误:

类的数量必须大于一;得到 1

我很确定问题出在y_learn 变量上,因为如果我将y_learn 更改为第一个元素为1 而其他元素为0 的列表,它会起作用。

我的代码是:

clf = svm.SVC()

clf.fit(x_learn,y_learn)

在哪里

y_learn = [ 1 -1 -1 -1 -1 -1 -1 -1 -1 -1  1  1  1  1  1  1  1  1  1  1  1 -1 -1 -1 -1
  1  1  1  1  1  1  1  1  1 -1 -1 -1 -1 -1 -1 -1  1  1  1  1  1  1  1  1  1
  1  1  1  1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1  1  1  1  1  1 -1 -1 -1 -1 -1 -1
 -1 -1 -1 -1 -1  1 -1 -1 -1 -1 -1 -1 -1  1  1  1  1  1  1  1  1  1  1  1  1
  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1 -1 -1 -1 -1 -1 -1 -1 -1 -1]

type(y_learn) = type 'numpy.ndarray'

x_learn = [array([  9.40768535e-01,   8.41994398e-01,   9.32081721e-01,
         5.66162508e-02,   7.98723422e-03,   1.43783134e-02,
        -7.09941391e-03,  -3.47126563e-03,   7.56540837e+01]), array([  9.51510849e-01,   8.45112974e-01,   9.38219301e-01,
         5.82776713e-02,   8.91018076e-03,   1.14186585e-02,
         1.43783134e-02,  -7.09941391e-03,   7.77932310e+01]), array([  9.55239672e-01,   8.48133424e-01,   9.41803516e-01,
         6.00029472e-02,   1.16427455e-02,   3.91884410e-03,
         1.14186585e-02,   1.43783134e-02,   7.84959346e+01]), array([  9.52616068e-01,   8.51255512e-01,   9.45513746e-01,
         6.13091486e-02,   1.15153207e-02,  -2.74653979e-03,
         3.91884410e-03,   1.14186585e-02,   7.66670540e+01]), array([  9.67841234e-01,   8.54751516e-01,   9.53595272e-01,
         6.28853797e-02,   9.68865724e-03,   1.59824778e-02,
        -2.74653979e-03,   3.91884410e-03,   7.96194885e+01]), array([  9.73522265e-01,   8.58377874e-01,   9.60146018e-01,
         6.44142845e-02,   9.91815056...]

【问题讨论】:

您使用的是哪个版本的 scikit-learn?这似乎不是适当的错误。可以X = np.array(x_learn) 给我们X.shapey_learn.shape 吗? 我使用的是 scikit-learn 的 0.16.1 版本。您要求的输出是:X.shape = (125, 9)y_lean.shape = (125,) 【参考方案1】:

我会说你的形状有问题,请在拟合模型之前尝试这样做:

x_learn = x_learn.reshape(y_learn.shape)

# OR

y_learn = y_learn.reshape(x_learn.shape)

如果出现问题,请尝试通过 0 更改它或升级您的 sklearn 版本,因为某些版本的 sklearn 有问题,-1 作为标签

【讨论】:

我尝试将 -1 替换为 0 - 仍然出现错误。另外,我尝试了重塑,但也没有用。 是的。让事情更清楚。 x_learn 是一个数组列表 y_learn 是一个数组 你能给我y_learn.shapex_learn.shape的输出吗? x_learn 没有形状,因为它是一个列表,但 len(x_learn) 返回 135 并且 y_learn.shape 返回 (135,) 好的,试试这个X= numpy.array([x_learn]) 并以这种方式拟合你的模型clf.fit(X,y_learn)

以上是关于无法运行适合 svm 的方法(通过 scikit-learn)的主要内容,如果未能解决你的问题,请参考以下文章

从 ComputerVision 开始选择啥:Scikit-image 还是 OpenCV? [关闭]

无法在 Macos 错误上安装 Scikit Learn 包 [重复]

哪种使用 OpenCV 的对象检测方法最适合不断变化的环境?

将 scikits.learn.hmm.GaussianHMM 拟合到可变长度的训练序列

无法腌制 Scikit 学习最近邻分类器 - 无法腌制实例方法对象

树莓派3安装opencv2程序无法运行