# 实现高斯核函数 def rbf_kernel(x1, x2): sigma=1.0 return np.exp(-np.linalg.norm(x1-x2,2)**2/sigma) # 加载葡萄酒识别数据集 wine = datasets.load_wine() # 处理数据和标签 X= wine["data"][:,(0,1)] y = 2 * (wine["target"]==1).astype(np.int64).reshape(-1,1) - 1 # 按照一定比例划分训练集和测试集(测试集占0.4) X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.4, random_state=5) # 定义KernelSVM模型 # 训练模型 # 用Pyplot作图工具绘制模型预测边界 x0s = np.linspace(10, 15, 100) x1s = np.linspace(0, 7, 100) x0, x1 = np.meshgrid(x0s, x1s) W = np.c_[x0.ravel(), x1.ravel()] u= model.predict(W).reshape(x0.shape) plt.plot(X_train[:, 0][y_train[:,0]==1] , X_train[:, 1][y_train[:,0]==1], "gs") plt.plot(X_train[:, 0][y_train[:,0]==-1], X_train[:, 1][y_train[:,0]==-1], "ro") plt.contourf(x0, x1, u, alpha=0.2) plt.show() #计算指标 from sklearn.metrics import accuracy_score from sklearn.metrics import recall_score from sklearn.metrics import precision_score from sklearn.metrics import f1_score accuracy = accuracy_score(y_test, y_pred) precision = precision_score(y_test, y_pred) recall = recall_score(y_test, y_pred) f1 = f1_score(y_test, y_pred) print("accuracy = {}".format(accuracy)) print("precision = {}".format(precision)) print("recall = {}".format(recall)) print("f1 = {}".format(f1))补全代码
时间: 2024-03-08 09:50:25 浏览: 19
抱歉,上面的代码仍然不完整,缺少了定义KernelSVM模型和训练模型的部分。以下是完整的代码:
```
# 实现高斯核函数
def rbf_kernel(x1, x2):
sigma=1.0
return np.exp(-np.linalg.norm(x1-x2,2)**2/sigma)
# 加载葡萄酒识别数据集
wine = datasets.load_wine()
# 处理数据和标签
X= wine["data"][:,(0,1)]
y = 2 * (wine["target"]==1).astype(np.int64).reshape(-1,1) - 1
# 按照一定比例划分训练集和测试集(测试集占0.4)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.4, random_state=5)
# 定义KernelSVM模型
svm_clf = Pipeline([
("scaler", StandardScaler()),
("svm_clf", SVC(kernel="rbf", gamma=5, C=0.001))
])
# 训练模型
svm_clf.fit(X_train, y_train.ravel())
# 用Pyplot作图工具绘制模型预测边界
x0s = np.linspace(10, 15, 100)
x1s = np.linspace(0, 7, 100)
x0, x1 = np.meshgrid(x0s, x1s)
W = np.c_[x0.ravel(), x1.ravel()]
u= svm_clf.predict(W).reshape(x0.shape)
plt.plot(X_train[:, 0][y_train[:,0]==1] , X_train[:, 1][y_train[:,0]==1], "gs")
plt.plot(X_train[:, 0][y_train[:,0]==-1], X_train[:, 1][y_train[:,0]==-1], "ro")
plt.contourf(x0, x1, u, alpha=0.2)
plt.show()
# 计算指标
y_pred = svm_clf.predict(X_test)
accuracy = accuracy_score(y_test, y_pred)
precision = precision_score(y_test, y_pred)
recall = recall_score(y_test, y_pred)
f1 = f1_score(y_test, y_pred)
print("accuracy = {}".format(accuracy))
print("precision = {}".format(precision))
print("recall = {}".format(recall))
print("f1 = {}".format(f1))
```
其中,`SVC`是Scikit-Learn库中的SVM模型,`Pipeline`是Scikit-Learn库中的管道模型,用于将多个数据预处理和模型组合成一个整体。