Python机器学习算法实现
Author:louwill
在上一讲中,我们探讨了线性可分情况下的支持向量机模型。本节我们来继续探讨svm的第二种情况,线性支持向量机。何谓线性支持呢?就是训练数据中大部分实例组成的样本集合是线性可分的,但有一些特异点的存在造成了数据线性不可分的状态,在去除了这些特异点之后,剩下的数据组成的集合便是线性可分的。
原始问题
所以我们可以在线性可分支持向量机的基础上,推导线性支持向量机的基本原理。假设训练数据线性不可分,这便意味着某些样本点不满足此前线性可分中的函数间隔大于1的约束条件,线性支持向量机这里的处理方法是对每个实例引入一个松弛变量,使得函数间隔加上松弛变量大于等于1。对应于线性可分时的硬间隔最大化(hard margin svm),线性支持向量机可称为软间隔最大化问题(soft margin svm)。
因而线性支持向量机就可以形式化为一个凸二次规划问题:
其中C>0为惩罚参数,表示对误分类的惩罚程度。最小化该目标函数可包含两层含义:既要使得间隔最大化也要使得误分类点个数最少,C即为二者的调和系数。关于凸二次规划问题(QP)的求解,各位可参考运筹学、凸优化等教材课程,这里不多赘述。
再来看线性支持向量机的对偶问题。首先定义拉格朗日函数如下:
由上一讲的推导可知,对偶问题为拉格朗日函数的极大极小问题。基于该拉格朗日函数对w、b和keci求偏导:
由上三式可得:
将上述三个式子再代回到拉格朗日函数中:
于是便可得到线性支持向量机的对偶问题:
由KKT条件:
计算可得:
以上便是线性支持向量机,也即软间隔最大化对偶问题的推导过程。
cvxopt
本节将使用Python的凸优化求解的第三方库cvxopt实现线性支持向量机。先对该库进行了一个简单介绍。经典的二次规划问题可表示为如下形式:
假设要求解如下二次规划问题:
将目标函数和约束条件写成矩阵形式:
基于cvxopt包求解上述问题如下:
import numpy
from cvxopt import matrix
from cvxopt import solvers
# 定义二次规划参数
P = matrix([[1.0,0.0],[0.0,0.0]])
q = matrix([3.0,4.0])
G = matrix([[-1.0,0.0,-1.0,2.0,3.0],[0.0,-1.0,-3.0,5.0,4.0]])
h = matrix([0.0,0.0,-15.0,100.0,80.0])
# 构建求解
sol = solvers.qp(P,q,G,h)
# 获取最优值
print(sol['x'],sol['primal objective'])
基于cvxopt的线性支持向量机实现
导入相关package:
import numpy as np
from numpy import linalg
import cvxopt
import cvxopt.solvers
import pylab as pl
定义一个线性核函数:
def linear_kernel(x1, x2):
return np.dot(x1, x2)
生成示例数据:
def gen_non_lin_separable_data():
mean1 = [-1, 2]
mean2 = [1, -1]
mean3 = [4, -4]
mean4 = [-4, 4]
cov = [[1.0, 0.8], [0.8, 1.0]]
X1 = np.random.multivariate_normal(mean1, cov, 50)
X1 = np.vstack((X1, np.random.multivariate_normal(mean3, cov, 50)))
y1 = np.ones(len(X1))
X2 = np.random.multivariate_normal(mean2, cov, 50)
X2 = np.vstack((X2, np.random.multivariate_normal(mean4, cov, 50)))
y2 = np.ones(len(X2)) * -1
return X1, y1, X2, y2
X1, y1, X2, y2 = gen_non_lin_separable_data()
基于示例数据生成训练集和测试集:
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 split_test(X1, y1, X2, y2):
X1_test = X1[90:]
y1_test = y1[90:]
X2_test = X2[90:]
y2_test = y2[90:]
X_test = np.vstack((X1_test, X2_test))
y_test = np.hstack((y1_test, y2_test))
return X_test, y_test
X_train, y_train = split_train(X1, y1, X2, y2)
X_test, y_test = split_test(X1, y1, X2, y2)
print(X_train.shape, y_train.shape, X_test.shape, y_test.shape)
基于cvxopt库定义线性支持向量机的训练过程:
def fit(X, y, C):
n_samples, n_features = X.shape
# Gram matrix
K = np.zeros((n_samples, n_samples))
for i in range(n_samples):
for j in range(n_samples):
K[i, j] = linear_kernel(X[i], X[j])
P = cvxopt.matrix(np.outer(y, y) * K)
q = cvxopt.matrix(np.ones(n_samples) * -1)
A = cvxopt.matrix(y, (1, n_samples))
b = cvxopt.matrix(0.0)
if C is None:
G = cvxopt.matrix(np.diag(np.ones(n_samples) * -1))
h = cvxopt.matrix(np.zeros(n_samples))
else:
tmp1 = np.diag(np.ones(n_samples) * -1)
tmp2 = np.identity(n_samples)
G = cvxopt.matrix(np.vstack((tmp1, tmp2)))
tmp1 = np.zeros(n_samples)
tmp2 = np.ones(n_samples) * C
h = cvxopt.matrix(np.hstack((tmp1, tmp2)))
# solve QP problem
solution = cvxopt.solvers.qp(P, q, G, h, A, b)
# Lagrange multipliers
a = np.ravel(solution['x'])
# Support vectors have non zero lagrange multipliers
sv = a > 1e-5
ind = np.arange(len(a))[sv]
a = a[sv]
sv_x = X[sv]
sv_y = y[sv]
print("%d support vectors out of %d points" % (len(a), n_samples))
# Intercept
b = 0
for n in range(len(a)):
b += sv_y[n]
b -= np.sum(a * sv_y * K[ind[n], sv])
b /= len(a)
# Weight vector
w = np.zeros(n_features)
for n in range(len(a)):
w += a[n] * sv_y[n] * sv[n]
else:
w = None
软间隔支持向量机函数化封装
import numpy as np
from numpy import linalg
import cvxopt
import cvxopt.solvers
import pylab as pl
def linear_kernel(x1, x2):
return np.dot(x1, x2)
class soft_margin_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
# Gram 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 = cvxopt.matrix(np.outer(y, y) * K)
q = cvxopt.matrix(np.ones(n_samples) * -1)
A = cvxopt.matrix(y, (1, n_samples))
b = cvxopt.matrix(0.0)
if self.C is None:
G = cvxopt.matrix(np.diag(np.ones(n_samples) * -1))
h = cvxopt.matrix(np.zeros(n_samples))
else:
tmp1 = np.diag(np.ones(n_samples) * -1)
tmp2 = np.identity(n_samples)
G = cvxopt.matrix(np.vstack((tmp1, tmp2)))
tmp1 = np.zeros(n_samples)
tmp2 = np.ones(n_samples) * self.C
h = cvxopt.matrix(np.hstack((tmp1, tmp2)))
# solve QP problem
solution = cvxopt.solvers.qp(P, q, G, h, A, b)
# Lagrange multipliers
a = np.ravel(solution['x'])
# 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]
print("%d support vectors out of %d points" % (len(self.a), n_samples))
# 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__":
def gen_non_lin_separable_data():
mean1 = [-1, 2]
mean2 = [1, -1]
mean3 = [4, -4]
mean4 = [-4, 4]
cov = [[1.0, 0.8], [0.8, 1.0]]
X1 = np.random.multivariate_normal(mean1, cov, 50)
X1 = np.vstack((X1, np.random.multivariate_normal(mean3, cov, 50)))
y1 = np.ones(len(X1))
X2 = np.random.multivariate_normal(mean2, cov, 50)
X2 = np.vstack((X2, np.random.multivariate_normal(mean4, cov, 50)))
y2 = np.ones(len(X2)) * -1
return X1, y1, X2, y2
def gen_lin_separable_overlap_data():
# generate training data in the 2-d case
mean1 = np.array([0, 2])
mean2 = np.array([2, 0])
cov = np.array([[1.5, 1.0], [1.0, 1.5]])
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 split_test(X1, y1, X2, y2):
X1_test = X1[90:]
y1_test = y1[90:]
X2_test = X2[90:]
y2_test = y2[90:]
X_test = np.vstack((X1_test, X2_test))
y_test = np.hstack((y1_test, y2_test))
return X_test, y_test
def plot_margin(X1_train, X2_train, clf):
def f(x, w, b, c=0):
# given x, return y such that [x,y] in on the line
# w.x + b = c
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")
# w.x + b = 0
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")
# w.x + b = 1
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--")
# w.x + b = -1
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()
def plot_contour(X1_train, X2_train, clf):
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")
X1, X2 = np.meshgrid(np.linspace(-6, 6, 50), np.linspace(-6, 6, 50))
X = np.array([[x1, x2] for x1, x2 in zip(np.ravel(X1), np.ravel(X2))])
Z = clf.project(X).reshape(X1.shape)
pl.contour(X1, X2, Z, [0.0], colors='k', linewidths=1, origin='lower')
pl.contour(X1, X2, Z + 1, [0.0], colors='grey', linewidths=1, origin='lower')
pl.contour(X1, X2, Z - 1, [0.0], colors='grey', linewidths=1, origin='lower')
pl.axis("tight")
pl.show()
def test_soft():
X1, y1, X2, y2 = gen_lin_separable_overlap_data()
X_train, y_train = split_train(X1, y1, X2, y2)
X_test, y_test = split_test(X1, y1, X2, y2)
clf = soft_margin_svm(C=1000.1)
clf.fit(X_train, y_train)
y_predict = clf.predict(X_test)
correct = np.sum(y_predict == y_test)
print("%d out of %d predictions correct" % (correct, len(y_predict)))
plot_contour(X_train[y_train == 1], X_train[y_train == -1], clf)
test_soft()
以上就是本节内容,关于近似线性可分以及软间隔最大化问题,笔者将在下一篇推文中介绍。完整代码文件和数据可参考笔者GitHub地址:
https://github.com/luwill/machine-learning-code-writing
参考资料:
https://github.com/SmirkCao/Lihang/tree/master/CH07
http://cvxopt.org/examples/
往期精彩:
一个数据科学从业者的学习历程
长按二维码.关注机器学习实验室