gpt4 book ai didi

python-3.x - 当输出标签是3D数组时如何使用SVM?

转载 作者:行者123 更新时间:2023-11-30 09:04:46 25 4
gpt4 key购买 nike

问题很简单,我有一个 3D 图像,我想使用 SVM 对它们进行分割。所以我将输入和输出图像转换为3D numpy数组,现在我想使用SVM。但似乎clf.fit()不支持多维标签。那么如何训练标签是多维数组的模型呢?

一个简单的例子:

from sklearn import svm
x=[[0,0],[1,1]]
y=[[0,0],[1,1]]
clf=svm.SVC(gamma='scale')
clf.fit(x,y)

错误是:

Traceback (most recent call last):
File "basic.py", line 5, in <module>
clf.fit(x,y)
File "/usr/local/lib/python3.5/dist-packages/sklearn/svm/base.py", line 149, in fit
accept_large_sparse=False)
File "/usr/local/lib/python3.5/dist-packages/sklearn/utils/validation.py", line 761, in check_X_y
y = column_or_1d(y, warn=True)
File "/usr/local/lib/python3.5/dist-packages/sklearn/utils/validation.py", line 797, in column_or_1d
raise ValueError("bad input shape {0}".format(shape))
ValueError: bad input shape (2, 2)

最佳答案

您正在添加不同的 y 类标签,这就是它不起作用的原因。请参阅下面带有内嵌注释的解决方案。

from sklearn import svm
x=[[0,0],[1,1],[7,8]]
y=[0,1, 2] # class labels
clf=svm.SVC() # clf=svm.SVC(gamma='scale') > gamma is auto. no need to add this.

print (clf.fit(x,y))

q = clf.predict([[2., 2.]]) # simple example to test prediction.

print ('array : %s ' % q)


# use of multiple class labes for y

x=[[0,0],[1,1]]
y=[[0,1],[0,2]] # the value 2 is to show the difference in printed output.

# add here your `for item in x:` if both arrays are 3D. `for item in y:` needs
# indentation if you do.

for item in y: # iters through the labeling list.
print (item)
clf=svm.SVC()

print (clf.fit(x,item))

q = clf.predict([[2., 2.]])

print ('array : %s ' % q)

打印结果:

SVC(C=1.0, cache_size=200, class_weight=None, coef0=0.0,
decision_function_shape=None, degree=3, gamma='auto', kernel='rbf',
max_iter=-1, probability=False, random_state=None, shrinking=True,
tol=0.001, verbose=False)
array : [1]
[0, 1]
SVC(C=1.0, cache_size=200, class_weight=None, coef0=0.0,
decision_function_shape=None, degree=3, gamma='auto', kernel='rbf',
max_iter=-1, probability=False, random_state=None, shrinking=True,
tol=0.001, verbose=False)
array : [1]
[0, 2]
SVC(C=1.0, cache_size=200, class_weight=None, coef0=0.0,
decision_function_shape=None, degree=3, gamma='auto', kernel='rbf',
max_iter=-1, probability=False, random_state=None, shrinking=True,
tol=0.001, verbose=False)
array : [2]

关于python-3.x - 当输出标签是3D数组时如何使用SVM?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55450964/

25 4 0