用plt.pcolormesh绘制分类图及分类边界

该博客介绍了如何利用matplotlib的plt.pcolormesh函数来绘制分类图,并展示了如何呈现不同类别的边界。内容涵盖了数据处理、颜色映射以及图形的详细设置,为读者提供了一种可视化分类数据的有效方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

import matplotlib.pyplot as plt
import numpy as np
from sklearn import svm
from sklearn.model_selection import train_test_split
#训练svm分类器
x= np.array([[-1,-1],[-2,-1],[1,1],[2,1],[-1,1],[-1,2],[1,-1],[1,-2]])
y= np.array([0,0,1,2,0,2,1,1])
x_train,x_test,y_train,y_test=train_test_split(x,y,train_size=7,random_state=1)
clf=svm.SVC(C=0.8,verbose=True,kernel='rbf',decision_function_shape='ovr',max_iter=-1,probability=True)
clf.fit(x_train,y_train.reshape(-1,1))
#画图
X=x_train
plot_step=0.02
x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1
y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1
xx, yy = np.meshgrid(np.arange(x_min, x_max, plot_step),
                     np.arange(y_min, y_max, plot_step))#生成网格采样点
grid_test = np.stack((xx.flat, yy.flat), axis=1)  #生成测试点
grid_hat = clf.predict(grid_test) #用训练好的模型对测试点进行预测 
grid_hat = grid_hat.reshape(xx.shape)#为了画图把预测结果调整为与xx,yy一样

import matplotlib as mpl
cm_light = mpl.colors.ListedColormap(['#A
from sklearn.neighbors import KNeighborsClassifier from sklearn.preprocessing import StandardScaler # 数据预处理(标准化) scaler = StandardScaler() X_train_scaled = scaler.fit_transform(X_train) X_test_scaled = scaler.transform(X_test) # 创建k-NN模型 knn = KNeighborsClassifier( n_neighbors=5, # k值 weights='distance', # 距离加权投票 metric='minkowski', # 距离度量 p=2 # 欧氏距离 (p=1为曼哈顿距离) ) # 训练与预测 knn.fit(X_train_scaled, y_train) accuracy = knn.score(X_test_scaled, y_test) print(f"标准化后准确率: {accuracy:.2%}") # 可视化决策边界(仅使用前两个特征) import matplotlib.pyplot as plt from matplotlib.colors import ListedColormap def plot_decision_boundary(): # 只取前两个特征 X_2d = X_train_scaled[:, :2] y_2d = y_train # 创建网格 h = 0.02 # 网格步长 x_min, x_max = X_2d[:, 0].min() - 1, X_2d[:, 0].max() + 1 y_min, y_max = X_2d[:, 1].min() - 1, X_2d[:, 1].max() + 1 xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h)) # 预测网格点类别 Z = knn.predict(np.c_[xx.ravel(), yy.ravel()]) Z = Z.reshape(xx.shape) # 绘制 cmap_light = ListedColormap(['#FFAAAA', '#AAFFAA', '#AAAAFF']) cmap_bold = ListedColormap(['#FF0000', '#00FF00', '#0000FF']) plt.figure(figsize=(10, 6)) plt.pcolormesh(xx, yy, Z, cmap=cmap_light) # 绘制训练点 plt.scatter(X_2d[:, 0], X_2d[:, 1], c=y_2d, cmap=cmap_bold, edgecolor='k', s=20) plt.xlim(xx.min(), xx.max()) plt.ylim(yy.min(), yy.max()) plt.title(f"k-NN (k={knn.n_neighbors}) 决策边界") plt.xlabel(iris.feature_names[0]) plt.ylabel(iris.feature_names[1]) plt.show() plot_decision_boundary() 补齐代码
07-15
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值