Python:使用cvxpy包实现SVM二分类(可以运行通)

 解决了别人代码里面的一个问题,

对y进行了np.reshape,完美运行!

'''
代码可以运行的通
'''
import numpy as np
import cvxpy as cp
import matplotlib.pyplot as plt
from sklearn import datasets

# Problem data.

x ,y = datasets.make_blobs(n_samples=300, n_features=2,centers=2,cluster_std=[2.0,2.0],random_state=123)
y = y*2 - 1
y = np.reshape(y,(len(y),1))


m = x.shape[0]
n = x.shape[1]
C = 1

# Construct the problem.
w = cp.Variable((n,1))
b = cp.Variable()
xi = cp.Variable((m,1))

objective = cp.Minimize(0.5*cp.norm(w)**2+C*cp.sum(xi))
constraints = [cp.multiply(y, x*w + b) >= 1 - xi, xi >= 0]
prob = cp.Problem(objective, constraints)

# The optimal objective value is returned by `prob.solve()`.
# The optimal value for x is stored in `x.value`.
result = prob.solve()
print(w.value)
# The optimal Lagrange multiplier for a constraint is stored in
# `constraint.dual_value`.
print(prob.value)
#print(constraints[0].dual_value)
#print(0.5*np.linalg.norm(w.value, ord =2)**2+C*np.sum(xi.value))

xp = np.linspace(min(x[:,0]), max(x[:,0]), 100)
yp = - (w.value[0]*xp + b.value)/w.value[1]
yp1 = np.array(- (w.value[0]*xp + b.value - C)/w.value[1] )# margin boundary for support vectors for y=1
yp0 = np.array(- (w.value[0]*xp + b.value + C)/w.value[1] )# margin boundary for support vectors for y=0

idx0 = np.where(y==-1)
idx1 = np.where(y==1)

plt.plot(x[idx0, 0], x[idx0, 1], 'rx')
plt.plot(x[idx1, 0], x[idx1, 1], 'go')
plt.plot(xp, yp, '-b', xp, yp1, '--g', xp, yp0, '--r')
plt.title('decision boundary for a linear SVM classifier with C={}'.format(C) )
plt.show()

 

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

DeniuHe

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

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

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

打赏作者

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

抵扣说明:

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

余额充值