python使用SVM(支持向量机)解决非线性分类问题

创作不易觉得有帮助请点赞关注收藏~~~

很多问题使用线性SVM分类器就能有效处理,但实际上也存在很多非线性问题,数据集无法进行线性划分,处理非线性数据集的方法之一是添加更多特征,比如多项式,添加新特征后,数据集维度更高,能够形成一个划分超平面。

下面使用SVC(SVM中的分类算法)处理K-means聚类无法解决的半环形moons数据集的分类问题

Piplline()函数能够对三个函数模块进行封装,将前一个函数的结果传递个下一个函数,

结果可视化如下

可以看出 SVC模型可以将半环形数据集进行准确的划分,从而解决了K-means中仅仅依靠距离进行分类的局限性,因此,对于非线性问题来说,SVM提供了崭新的思路和良好的解决方案! 

源代码如下

import  numpy as np
import  matplotlib.pyplot as plt
from sklearn.datasets import  make_moons
from sklearn.preprocessing import  PolynomialFeatures
from sklearn.preprocessing import  StandardScaler
from sklearn.svm import  LinearSVC
from  sklearn.pipeline import Pipeline
x,y=make_moons(n_samples=100,noise=0.1,random_state=1)
moonAxe=[-1.5,2.5,-1,1.5]
def disdata(x,y,moonAxe):
    pos_x0=  [x[i,0] for i in range(len(y))if  y[i]==1]
    pos_x1 = [x[i,1] for i in range(len(y)) if y[i]==1]
    neg_x0 = [x[i,0] for i in range(len(y)) if y[i]==0]
    neg_x1 = [x[i,1] for i in range(len(y)) if y[i]==0]
    plt.plot(pos_x0,pos_x1,"bo")
    plt.plot(neg_x0,neg_x1,"r^")
    plt.axis(moonAxe)
    plt.xlabel('x')
    plt.ylabel('y')

def dispPredict(clf,moonAxe):
    d0=np.linspace(moonAxe[0],moonAxe[1],200)
    d1= np.linspace(moonAxe[2], moonAxe[3], 200)
    x0,x1=np.meshgrid(d0,d1)
    X=np.c_[x0.ravel(),x1.ravel()]
    y_pred=clf.predict(X).reshape(x0.shape)
    plt.contourf(x0,x1,y_pred,alpha=0.8)
disdata(x,y,moonAxe)
polynomial_svm_clf=Pipeline(
    (("multifeature",PolynomialFeatures(degree=3)),
     ("numscale",StandardScaler()),
     ("SVC",LinearSVC(C=100)))


)
polynomial_svm_clf.fit(x,y)
dispPredict(polynomial_svm_clf,moonAxe)
plt.title('Linear svm classifies moon data')
plt.show()


创作不易觉得有帮助请点赞关注收藏~~~

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

showswoller

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值