博主采用的是sigmoid核函数
具体代码如下:
import numpy as np
from matplotlib import pyplot as plt
from sklearn.svm import SVC
from sklearn.datasets import load_iris
data = load_iris()
X = data['data']
y = data['target']
print(X)
print(y)
X = X[y != 2, 0:2]
y = y[y != 2]
X -= np.mean(X, axis=0)
X /= np.std(X, axis=0, ddof=1)
m = len(X)
d = int(0.8 * m)
X_train, X_test = np.split(X, [d])
y_train, y_test = np.split(y, [d])
model_svm = SVC(C=1, kernel='sigmoid'
,gamma="auto"
,degree=10
,cache_size=5000)
model_svm.fit(X_train, y_train)
ss = model_svm.score(X_test, y_test)
print('测试集的准确率是:', ss)
X_train_h = model_svm.predict(X_train)
X_test_h = model_svm.predict(X_test)
x1_min, x1_max, x2_min, x2_max = np.min(X[:, 0]), np.max(X[:, 0]),
np.min(X[:, 1]), np.max(X[:, 1])
x1, x2 = np.mgrid[x1_min:x1_max:200j, x2_min:x2_max:200j]
x1x2 = np.c_[x1.ravel(), x2.ravel()]
z = model_svm.decision_function(x1x2)
z = z.reshape(x1.shape)
plt.scatter(X[:, 0], X[:, 1], c=y, zorder=10)
plt.scatter(X_train[:, 0], X_train[:, 1], s=100, facecolor='none',
zorder=10, edgecolors='k')
plt.contourf(x1, x2, z >= 0, cmap=plt.cm.Paired)
plt.contour(x1, x2, z, levels=[-1, 0, 1])
plt.show()