SVMD python
时间: 2024-12-27 10:18:24 浏览: 0
### 支持向量机(SVM)在Python中的实现
#### 使用CVXOPT库实现线性SVM
为了理解如何通过编程方式实现在Python中构建支持向量机模型,下面提供了一个简单的例子来展示基于凸优化求解器`cvxopt`包的线性分类器实现[^1]。
```python
from cvxopt import matrix, solvers
import numpy as np
def linear_kernel(x1, x2):
return np.dot(x1, x2)
class SVM(object):
def __init__(self, kernel=linear_kernel, C=None):
self.kernel = kernel
self.C = C
if self.C is not None:
self.C = float(self.C)
def fit(self, X, y):
n_samples, n_features = X.shape
# Kernel Matrix
K = np.zeros((n_samples, n_samples))
for i in range(n_samples):
for j in range(n_samples):
K[i,j] = self.kernel(X[i], X[j])
P = matrix(np.outer(y,y) * K)
q = matrix(-np.ones((n_samples, 1)))
A = matrix(y, (1,n_samples))
b = matrix(0.0)
if self.C is None:
G = matrix(-np.eye(n_samples))
h = matrix(np.zeros(n_samples))
else:
tmp1 = np.diag([-1.0]*n_samples)
tmp2 = np.identity(n_samples)
G = matrix(np.vstack((tmp1, tmp2)))
tmp1 = np.zeros(n_samples)
tmp2 = np.ones(n_samples) * self.C
h = matrix(np.hstack((tmp1, tmp2)))
solution = solvers.qp(P, q, G, h, A, b)['x']
# Lagrange multipliers
a = np.ravel(solution)
# Support vectors have non zero lagrange multipliers
sv = a > 1e-5
ind = np.arange(len(a))[sv]
self.a = a[sv]
self.sv = X[sv]
self.sv_y = y[sv]
# Intercept
self.b = 0
for n in range(len(self.a)):
self.b += self.sv_y[n]
self.b -= np.sum(self.a * self.sv_y * K[ind[n],sv])
self.b /= len(self.a)
# Weight vector
if self.kernel == linear_kernel:
self.w = np.zeros(n_features)
for n in range(len(self.a)):
self.w += self.a[n] * self.sv_y[n] * self.sv[n]
else:
self.w = None
def project(self, X):
if self.w is not None:
return np.dot(X, self.w) + self.b
else:
y_predict = np.zeros(len(X))
for i in range(len(X)):
s = 0
for a, sv_y, sv in zip(self.a, self.sv_y, self.sv):
s += a * sv_y * self.kernel(X[i], sv)
y_predict[i] = s
return y_predict + self.b
def predict(self, X):
return np.sign(self.project(X))
if __name__ == "__main__":
import matplotlib.pyplot as plt
def gen_lin_separable_data():
mean1 = np.array([0, 2])
mean2 = np.array([2, 0])
cov = np.array([[0.8, 0.6], [0.6, 0.8]])
X1 = np.random.multivariate_normal(mean1, cov, 100)
y1 = np.ones(len(X1))
X2 = np.random.multivariate_normal(mean2, cov, 100)
y2 = np.ones(len(X2)) * -1
return X1, y1, X2, y2
def split_train(X1, y1, X2, y2):
X1_train = X1[:90]
y1_train = y1[:90]
X2_train = X2[:90]
y2_train = y2[:90]
X_train = np.vstack((X1_train, X2_train))
y_train = np.hstack((y1_train, y2_train))
return X_train, y_train
def plot_margin(X1_train, X2_train, clf):
def f(x, w, b, c=0):
return (-w[0] * x - b + c) / w[1]
pl.plot(X1_train[:,0], X1_train[:,1], "ro")
pl.plot(X2_train[:,0], X2_train[:,1], "bo")
pl.scatter(clf.sv[:,0], clf.sv[:,1], s=100, c="g")
a0 = -4; a1 = f(a0, clf.w, clf.b)
b0 = 4; b1 = f(b0, clf.w, clf.b)
pl.plot([a0,b0], [a1,b1], "k")
a0 = -4; a1 = f(a0, clf.w, clf.b, 1)
b0 = 4; b1 = f(b0, clf.w, clf.b, 1)
pl.plot([a0,b0], [a1,b1], "k--")
a0 = -4; a1 = f(a0, clf.w, clf.b, -1)
b0 = 4; b1 = f(b0, clf.w, clf.b, -1)
pl.plot([a0,b0], [a1,b1], "k--")
pl.axis("tight")
pl.show()
X1, y1, X2, y2 = gen_lin_separable_data()
X_train, y_train = split_train(X1, y1, X2, y2)
clf = SVM()
clf.fit(X_train, y_train)
plot_margin(X_train[y_train==1], X_train[y_train==-1], clf)
```
此代码片段展示了如何创建一个基本的支持向量机类并训练它来进行二元分类任务。这里选择了最基础的形式——硬间隔线性SVM,并利用了二次规划算法解决最小化问题以获得最优分离超平面参数。
对于软边距核SVM而言,在定义目标函数时引入松弛变量允许某些样本位于边界内部或错误分类,从而提高泛化能力;而选择合适的核函数则能够有效地处理非线性的决策面情况[^2]。
当涉及到更复杂的场景比如大规模数据集或是高维稀疏输入特性的情况下,则推荐考虑使用专门针对效率进行了优化的工具如scikit-learn中的SVC模块[^3]。
阅读全文