分类散点与决策区域
代码截图恢复与适配 · 来源与修改说明 · 下载完整代码
1 """分类散点与决策区域
2 Restored/adapted from supplied screenshots [107, 108, 109].
3 Source: 小明的代码美学 (as shown in supplied screenshots).
4 This is a runnable restoration, not a byte-for-byte original source file.
5 See SOURCE.md for missing inputs and documented corrections.
6 """
7 import numpy as np
8 import pandas as pd
9 import matplotlib.pyplot as plt
10 from matplotlib.colors import LinearSegmentedColormap, Normalize, to_hex
11 from matplotlib.cm import ScalarMappable
12 from pathlib import Path
13 # Missing .mplstyle files are replaced only by explicit, portable display defaults.
14 plt.rcParams.update({'font.sans-serif':['Microsoft YaHei','DejaVu Sans'],
15 'axes.unicode_minus':False,'figure.facecolor':'white','axes.facecolor':'white',
16 'axes.spines.top':False,'axes.spines.right':False,'font.size':9})
17 from sklearn.svm import SVC
18 from matplotlib.colors import ListedColormap
19 import matplotlib.ticker as ticker
20 n=80;np.random.seed(7)
21 X1=np.random.normal(30,8,n);Y1=np.random.normal(60,18,n)
22 X2=np.random.normal(70,13,n);Y2=np.random.normal(90,20,n)
23 X3=np.random.normal(55,15,n);Y3=np.random.normal(50,15,n)
24 X=np.concatenate([np.column_stack((a,b)) for a,b in [(X1,Y1),(X2,Y2),(X3,Y3)]])
25 y=np.array([0]*n+[1]*n+[2]*n)
26 model=SVC(kernel='linear',decision_function_shape='ovo').fit(X,y)
27 x_max=X[:,0].max()+5;y_max=X[:,1].max()+10
28 xx,yy=np.meshgrid(np.arange(-5,x_max,.5),np.arange(-10,y_max,.5))
29 Z=model.predict(np.c_[xx.ravel(),yy.ravel()]).reshape(xx.shape)
30 colors=['#e97a7a','#5595d1','#e5c679']
31 fig,ax=plt.subplots(figsize=(9,5.5),dpi=150)
32 ax.contourf(xx,yy,Z,levels=[-.5,.5,1.5,2.5],alpha=.2,cmap=ListedColormap(colors))
33 for i,(a,b,c) in enumerate(zip([X1,X2,X3],[Y1,Y2,Y3],colors)):
34 ax.scatter(a,b,s=100,c=c,alpha=.5,label=f'类别{i+1}')
35 ax.scatter(a,np.zeros(len(a)),marker='|',color=c,alpha=.5,s=300)
36 ax.scatter(np.zeros(len(a)),b,marker='_',color=c,alpha=.5,s=300)
37 ax.xaxis.set_major_locator(ticker.MultipleLocator(10));ax.xaxis.set_minor_locator(ticker.MultipleLocator(1))
38 ax.yaxis.set_major_locator(ticker.MultipleLocator(20));ax.yaxis.set_minor_locator(ticker.MultipleLocator(2))
39 ax.set(title='分类散点与拟合决策区域',xlabel='X 轴',ylabel='Y 轴')
40 ax.legend(loc='upper center',ncols=3,frameon=False)
41 plt.tight_layout();plt.show()
42