import numpy as np
from matplotlib import pyplot as plt
import matplotlib as mpl
from sklearn.model_selection import train_test_split
from sklearn import preprocessing
from sklearn import svm # 支持向量机库
from sklearn.svm import SVC # (分类)
from sklearn.svm import SVR # (回归)
from sklearn import datasets
iris = datasets.load_iris()
X = iris.data[:, [0,2]]
Y = iris.target
x_train, x_test, y_train, y_test = train_test_split(X,Y,test_size=0.4)
#SVC多类分类
model = svm.SVC(gamma=10)
model.fit(x_train,y_train) #训练模型
# 显示结果
x_min, x_max = x_train[:,0].min()-1, x_train[:,0].max()+1#求第1个最小值与最大值
y_min, y_max = x_train[:,1].min()-1, x_train[:,1].max()+1#求第1个最小值与最大值
xx,yy=np.meshgrid(np.linspace(x_min, x_max, 50),np.linspace(y_min, y_max, 50)) #生成网格采样点
grid_test=np.stack((xx.flat, yy.flat), axis=1) #测试点
y_predict=model.predict(grid_test)
#生成前景与背景颜色
cm_pt = mpl.colors.ListedColormap(['k', 'b', 'r']) #样本点颜色
cm_bg = mpl.colors.ListedColormap(['w', 'y', 'c']) #背景颜色
plt.xlim(x_min, x_max);plt.ylim(y_min, y_max) #设置坐标范围
plt.pcolormesh(xx, yy, y_predict.reshape(xx.shape), cmap=cm_bg) #绘制网格背景
#plt.scatter(x_train[:,0],x_train[:,1],c=y_train,cmap=cm_pt,marker='o') #绘制样本点
plt.plot(np.ravel(X[Y == 0, 0]), np.ravel(X[Y == 0, 1]), 'ko', markersize=6)
plt.plot(np.ravel(X[Y == 1, 0]), np.ravel(X[Y == 1, 1]), 'bs', markersize=6)
plt.plot(np.ravel(X[Y == 2, 0]), np.ravel(X[Y == 2, 1]), 'r^', markersize=6)
plt.legend(["Y=0", "Y=1","Y=2"])
plt.grid(True);plt.show()