python,svm二,三标签画决策边缘,自己写核函数

# -*- coding: utf-8 -*-
"""
Created on Fri May  8 17:21:35 2020

@author: guangjie2333
"""
import numpy as np
import matplotlib.pyplot as plt
from sklearn import svm
#导入IRIS数据集
from sklearn.datasets import load_iris
#三维决策边界
from mpl_toolkits import mplot3d

#特征矩阵 
iris = load_iris()  

#绘制散点,画三个标签的决策边界
def plot_svm (model,X,Y,gamma):
     
    h = 0.05
    x_min,x_max = X[:,0].min()-0.5,X[:,0].max()+0.5
    y_min,y_max = X[:,1].min()-0.5,X[:,1].max()+0.5
    
    xx,yy = np.meshgrid(np.arange(x_min,x_max,h),np.arange(y_min,y_max,h))
    Z = clf.predict(np.c_[xx.ravel(),yy.ravel()])
    Z = Z.reshape(xx.shape)
    plt.pcolormesh(xx,yy,Z,cmap = plt.cm.Paired)
    plt.scatter(X[:,0],X[:,1],c=Y,cmap=plt.cm.Paired, edgecolor='k')
    
def customized_kernel(X,Y):
   Q = np.array([[0.5, 0], [0, 0.5]])
   return np.dot(np.dot(X, Q), Y.T)


if __name__ == '__main__':  
    
    #取前两列特征赋值给X, 取目标值赋值给Y
    X = iris.data[:,0:2]
    Y = iris.target
    
#第二题-----------------    
    plt.figure(1)
    #训练模型
    Gamma = 0.1
    clf = svm.SVC(kernel = 'rbf', C = 1000, gamma=Gamma)
    clf.fit(X,Y)
    #绘制向量超平面
    plot_svm (clf,X,Y,Gamma)

    plt.figure(2)
    #训练模型
    Gamma = 0.5
    clf = svm.SVC(kernel = 'rbf', C = 1000, gamma=Gamma)
    clf.fit(X,Y)
    #绘制向量超平面
    plot_svm (clf,X,Y,Gamma)

    plt.figure(3)
    #训练模型
    Gamma = 0.9
    clf = svm.SVC(kernel = 'rbf', C = 1000, gamma=Gamma)
    clf.fit(X,Y)
    #绘制向量超平面
    plot_svm (clf,X,Y,Gamma)  
    
    
#第三题-----------------
    plt.figure(4)    
    clf = svm.SVC(kernel=customized_kernel)
    clf.fit(X, Y)
    plot_svm (clf,X,Y,Gamma) 
    

你可能感兴趣的:(python课堂实验)