python SVM rbf和Linear的区别?

nnvyjq4y  于 2023-04-19  发布在  Python
关注(0)|答案(1)|浏览(137)

只是想知道是否有人可以回答我到线性和RBF SVM之间的区别是什么?
将不胜感激

lmvvr0a8

lmvvr0a81#

我使用支持向量机找到划分两组随机生成的数据的线性线。线的斜率取自线性模型系数。我使用模型评分迭代以找到最佳得分以及c和g值。最后,我绘制分隔两组数据的线性线。

#1. svm.LinearSVC and svm.SVC #Kernel SVM
#2. C hyper parameter (inverse regularization strength)
#3. kernel (type of kernel)
#4. gamma (inverse RBF smoothness)

np.random.seed(123)

## generate data
x1 = np.random.multivariate_normal([0,0],[[.5,0],[0,.5]],100)
x2 = np.random.multivariate_normal([2,2],[[.5,0],[0,.5]],100)
x3 = np.random.multivariate_normal([4,4],[[.5,0],[0,.5]],100)
X = np.vstack([x1,x2,x3])
Y = np.hstack([np.repeat(0,100),np.repeat(1,100),np.repeat(2,100)])

## plot data
fig, ax = plt.subplots(figsize=(7,7))
ax.scatter(x1[:,0],x1[:,1],color='r',label='class 0')
ax.scatter(x2[:,0],x2[:,1],color='b',label='class 1')

best_score = 0
for C in np.logspace(0,1,num=50):
    for g in np.logspace(-3,3,num=50):
        rbf_svm = svm.SVC(kernel="linear",C=C,gamma=g,random_state=123)
        rbf_svm.fit(X,Y)
        score = rbf_svm.score(X,Y)
        if score>best_score:
            best_score = score
            best_C = C
            best_g = g

model = svm.SVC(C=best_C,kernel='linear',gamma=best_g,random_state=123)
model.fit(X,Y)
y_pred=model.predict(X)
#print(y_pred)

w=model.coef_[0]
a= -w[0]/w[1]

xx=np.linspace(np.min(X[:,0]),np.max(X[:,0]),len(X))
yy=a * xx-model.intercept_[0]/w[1]

#print(w)
ax.plot(xx,yy)
#plt.plot(X[:,0],y_pred)
plt.show()

相关问题