Python-SVM用序列设置数组元素

2024-09-29 23:28:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图使用sklearn库中的SVM来执行一些图像识别,但是当我调用fit方法时,我得到了一个“ValueError:settinganarray element with a sequence.”类型的错误。我的代码如下。在

我的测试.py文件:

import matplotlib.pyplot as plt
import numpy as np
from sklearn import svm
from imageToNumberArray import imageToNumberArray

classAndValuesFile = "../Classes_Values.txt"
classesFiles = "../"

testImage = "ImageToPerformTestOn.png"

x = []
y = []

def main():
    i = 0
    with open(classAndValuesFile) as f:
        for line in f:
            splitter = line.split(",", 2)
            x.append(imageToNumberArray(classesFiles + splitter[0]))
            y.append(splitter[1].strip())

    clf = svm.SVC(gamma=0.001, C=100)
    clf.fit(x,y)
    #print clf.predict(testImage)

imageToNumberArray文件是:

^{pr2}$

我得到了以下错误:

Traceback (most recent call last):
  File "D:\Research\project\testing.py", line 30, in <module>
main()
  File "D:\Research\project\testing.py", line 23, in main
clf.fit(x,y)
  File "C:\Python27\lib\site-packages\sklearn\svm\base.py", line 139, in fit
X = check_array(X, accept_sparse='csr', dtype=np.float64, order='C')
  File "C:\Python27\lib\site-packages\sklearn\utils\validation.py", line 344, in check_array
array = np.array(array, dtype=dtype, order=order, copy=copy)
ValueError: setting an array element with a sequence.

如果我评论clf.配合行得好。在

另外,如果我把矩阵的所有形状都打印在X上,我会得到这样的结果(有些是二维的,有些是三维的):

(59, 58, 4)
(49, 27, 4)
(570, 400, 3)
(471, 364)
(967, 729)
(600, 600, 3)
(325, 325, 3)
(386, 292)
(86, 36, 4)
(49, 26, 4)
(578, 244, 3)
(300, 300)
(995, 557, 3)
(1495, 677)
(400, 400, 3)
(200, 230, 3)
(74, 67, 4)
(49, 34, 4)
(240, 217, 3)
(594, 546, 4)
(387, 230, 3)
(297, 273, 4)
(400, 400, 3)
(387, 230, 3)
(86, 62, 4)
(50, 22, 4)
(499, 245, 3)
(800, 566, 4)
(1050, 750, 3)
(400, 400, 3)
(499, 245, 3)
(74, 53, 4)
(47, 26, 4)
(592, 348, 4)
(1050, 750, 3)
(1600, 1600)
(320, 320)
(84, 54, 4)
(47, 25, 4)
(600, 294, 3)
(400, 400, 3)
(1050, 750, 3)
(1478, 761)
(504, 300, 3)
(53, 84, 4)
(36, 42, 4)
(315, 600, 4)
(223, 425, 3)
(194, 325, 3)

前两个数字是图像的大小。在

我该怎么做才能消除这个错误?在


Tags: inpyimportas错误withnpline
1条回答
网友
1楼 · 发布于 2024-09-29 23:28:44

你似乎很困惑支持向量机是如何工作的。简而言之,x必须是一个大的二维数组,而在您的例子中,它是各种矩阵的列表。支持向量机永远不会在这样的数据上运行。首先,找到一种有意义的(在数据意义上)将每个图像表示为一个常量大小向量,这通常称为特征提取。基本方法之一是将每个图像表示为某个histogrambag of visual words。在

相关问题 更多 >

    热门问题