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()


猜你喜欢

转载自blog.csdn.net/jiebaoshayebuhui/article/details/126993028