svm python实践

#coding=utf-8
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.pipeline import Pipeline
from sklearn.svm import SVC
from sklearn.preprocessing import PolynomialFeatures
import copy
def replaceSpace(string,char,char1):
        if string == None:return None
        if len(string) == 0:return 0
        return string.replace(char,char1)
 
#获取多项式方程。     
def get_func(arr,str1):
    z=""
    for i in range(len(str1)):
        if i==len(str1)-1:
            z+=str(arr[i])+"*"+str(str1[i])
        else:
            z+=str(arr[i])+"*"+str(str1[i])+"+"
    new_z = replaceSpace(z," ","*")
    return replaceSpace(new_z,"^","**")

mpl.rcParams['font.sans-serif']=['simhei']
mpl.rcParams['axes.unicode_minus']=False

cm_light = ['#A0FFA0', '#FFA0A0', '#A0A0FF']
cm_dark = ['g', 'r', 'b']

#加载鸢尾花数据
data_obj = load_iris()
x = data_obj.data[:,2:4]
y = data_obj.target

pipe = Pipeline([
    ("poly",PolynomialFeatures(include_bias=False)),
    ("model",SVC(kernel="linear",C=10))  #C是惩罚因子.为无穷大就是硬间隔,趋近于零就是软间隔。
    ])

#绘制线性可分SVM图(三分类)

#生成网格点
x1=np.linspace(np.min(x[:,0]),np.max(x[:,0]),500)
y1=np.linspace(np.min(x[:,1]),np.max(x[:,1]),500)
x1,y1 = np.meshgrid(x1,y1)
pre_x = np.stack([x1.ravel(),y1.flat],axis=1)


pipe.set_params(poly__degree=1)
pipe.fit(x,y)
pre_res = pipe.predict(pre_x)
for i in range(3):
    plt.scatter(pre_x[pre_res==i][:,0],pre_x[pre_res==i][:,1],c=cm_light[i])
plt.scatter(x[y==0][:,0],x[y==0][:,1],marker="*")
plt.scatter(x[y==1][:,0],x[y==1][:,1],marker="^")
plt.scatter(x[y==2][:,0],x[y==2][:,1],marker="v")
plt.xlabel(u"花瓣长度")
plt.ylabel(u"花瓣宽度")
plt.title(u"线性可分三分类")
plt.show()


#利用高斯核函数绘制三分类(是很容易过拟合。)
#每一个超参数的设置都需要我们交叉验证得出,为了简约我们直接给出数据.
pipe.set_params(poly__degree=1)
pipe.set_params(model__kernel="rbf",model__gamma=1,model__C=10000)
pipe.fit(x,y)
pre_res = pipe.predict(pre_x)
for i in range(3):
    plt.scatter(pre_x[pre_res==i][:,0],pre_x[pre_res==i][:,1],c=cm_light[i])
#绘制决策边界
#z = pipe.named_steps['model'].decision_function(pre_x)
#plt.contour(z.reshape(3,500,500),extent=extent,levels=[-1,0,1],colors="blue",linestyles="--")

plt.scatter(x[y==0][:,0],x[y==0][:,1],marker="*")
plt.scatter(x[y==1][:,0],x[y==1][:,1],marker="^")
plt.scatter(x[y==2][:,0],x[y==2][:,1],marker="v")
plt.xlabel(u"花瓣长度")
plt.ylabel(u"花瓣宽度")
plt.title(u"高斯核三分类")
plt.show()


#创造线性不可分情形数据(二分类)。
y1 = copy.deepcopy(data_obj.target)
#修改原始 数据
y1[y1==2]=0

#将数据升维,用线性多项式去拟合。
pipe.set_params(poly__degree=3)
pipe.set_params(model__kernel="linear",model__C=10)
pipe.fit(x,y1)
#由于得到的最终结果是一个隐函数,所以我们需要绘制等高线图.
x1,x0 = np.ogrid[x[:,1].min():x[:,1].max():100j,x[:,0].min():x[:,0].max():100j]  #生成的点都是二维的
extent = [x[:,0].min(),x[:,0].max(),x[:,1].min(),x[:,1].max()]
for i in range(1):
    z=eval(get_func(pipe.named_steps['model'].coef_[i],pipe.named_steps['poly'].get_feature_names()))+pipe.named_steps['model'].intercept_[i]
    plt.contour(z,extent=extent,levels=[-1,0,1],colors=cm_dark[i])
    #-1和1代表支撑向量。
    plt.title(u"线性多项式二分类")

plt.scatter(x[y1==0][:,0],x[y1==0][:,1],marker="*")
plt.scatter(x[y1==1][:,0],x[y1==1][:,1],marker="^")

plt.xlabel(u"花瓣长度")
plt.ylabel(u"花瓣宽度")
plt.show()


#利用多项式核函数去拟合(本质和上面一样)
pipe.set_params(model__kernel="poly",model__gamma=1,model__degree=3,model__C=10,model__coef0=1,poly__degree=1)
pipe.fit(x,y1)
pre_res = pipe.predict(pre_x)
for i in range(2):
    plt.scatter(pre_x[pre_res==i][:,0],pre_x[pre_res==i][:,1],c=cm_light[i])
    
plt.scatter(x[y1==0][:,0],x[y1==0][:,1],marker="*")
plt.scatter(x[y1==1][:,0],x[y1==1][:,1],marker="^")

plt.xlabel(u"花瓣长度")
plt.ylabel(u"花瓣宽度")

plt.show()

运行结果

 

 

 

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值