def svmModel(x,y,param): svmmodel=svm.SVC(C=param[1],kernel=param[0]) if param[0] == 'rbf': svmmodel.gamma = param[2] title = '高斯核,C=%.1f,$\gamma$ =%.1f' % (param[1], param[2]) else: title = '线性核,C=%.1f' % param[1] svmmodel.fit(x,y) y_predict=svmmodel.predict(x) accuracyscore=accuracy_score(y,y_predict) return svmmodel,title,accuracyscore if __name__=='__main__': path='D:/data/iris.data' data=pd.read_csv(path,header=None) x=data[list(range(2,4))] y=data[4].replace(['Iris-versicolor','Iris-virginica'],[0,1]) clf_param=(('linear',(0.1)),('rbf',(1,0.1)),('rbf',(5,5)),('rbf',(10,10))) for i,param in enumerate(clf_param): clf,title,accuracy_score=svmModel(x,y,param) y_hat=clf.predict(x) print(title) print('准确率:',accuracy_score) print('支持向量的数目:',clf.n_support_)报错TypeError: '<' not supported between instances of 'int' and 'str'
时间: 2024-01-07 11:04:46 浏览: 150
这个错误可能是由于使用了不同类型的数据进行了比较。具体来说,在输出 `svmModel` 函数中的 title 时,使用了字符串格式化,但是其中可能包含了不同类型的参数(整数和字符串)。这会导致类型错误。可以在字符串格式化时,将参数转换为字符串类型。修改后的代码如下:
```python
def svmModel(x, y, param):
svmmodel = svm.SVC(C=param[1], kernel=param[0])
if param[0] == 'rbf':
svmmodel.gamma = param[2]
title = '高斯核,C=%.1f,$\gamma$ =%.1f' % (param[1], param[2])
else:
title = '线性核,C=%.1f' % param[1]
svmmodel.fit(x, y)
y_predict = svmmodel.predict(x)
accuracyscore = accuracy_score(y, y_predict)
return svmmodel, title, accuracyscore
if __name__ == '__main__':
path = 'D:/data/iris.data'
data = pd.read_csv(path, header=None)
x = data[list(range(2, 4))]
y = data[4].replace(['Iris-versicolor', 'Iris-virginica'], [0, 1])
clf_param = (('linear', (0.1)), ('rbf', (1, 0.1)), ('rbf', (5, 5)), ('rbf', (10, 10)))
for i, param in enumerate(clf_param):
clf, title, accuracy_score = svmModel(x, y, param)
y_hat = clf.predict(x)
print(str(title)) # 将 title 转换为字符串类型
print('准确率:', accuracy_score)
print('支持向量的数目:', clf.n_support_)
```
阅读全文