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] 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_)报错sklearn.exceptions.NotFittedError: This SVC instance is not fitted yet. Call 'fit' with appropriate arguments before using this estimator.
时间: 2024-02-04 17:02:57 浏览: 164
这个错误是因为在调用 `svmModel` 函数时,没有对 SVM 模型进行训练。在调用 `svmmodel.predict(x)` 时,模型需要先进行训练,才能进行预测。因此,在 `svmModel` 函数中,需要加入模型的训练部分。可以使用 `svmmodel.fit(x,y)` 进行训练。修改后的代码如下:
```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(title)
print('准确率:', accuracy_score)
print('支持向量的数目:', clf.n_support_)
```
阅读全文