下面是一个使用NumPy实现的支持多种内核的SVM分类器的简单示例。这个实现是基于线性内核、多项式内核和高斯(RBF)内核的。我们还添加了一个简单的概率估计方法,用于predict_proba功能。请注意,这个实现是为了演示目的,并不是为了与专业级的SVM实现竞争。
python
import numpy as np
class SVM:
def __init__(self, C=1.0, kernel='linear', degree=3, gamma='scale'):
self.C = C
self.kernel = kernel
self.degree = degree
self.gamma = gamma
self.coef0 = 1
self.fit_status = False
self.support_vectors = None
self.support_vectors_labels = None
self.alpha = None
self.b = None
def kernel_function(self, x1, x2):
if self.kernel == 'linear':
return np.dot(x1, x2)
elif self.kernel == 'poly':
return (np.dot(x1, x2) + self.coef0) ** self.degree
elif self.kernel == 'rbf':
gamma = self._compute_gamma(len(x1))
return np.exp(-gamma * np.sum((x1 - x2) ** 2))
def _compute_gamma(self, n_features):
if self.gamma == 'scale':
return 1.0 / (n_features * np.power(2.0, 0.5))
else:
return self.gamma
def fit(self, X, y):
n_samples, n_features = X.shape
self.alpha = np.zeros(n_samples)
self.b = 0
self.support_vectors = np.zeros((n_samples, n_features))
self.support_vectors_labels = np.zeros(n_samples)
for i in range(n_samples):
k = self.kernel_function(X[i], X)
for j in range(n_samples):
if k[j] == 0:
continue
alpha_i = self.alpha[i]
alpha_j = self.alpha[j]
if y[i] != y[j]:
L = max(0, alpha_j - alpha_i)
H = min(self.C, self.C + alpha_j - alpha_i)
else:
L = max(0, alpha_i + alpha_j - self.C)
H = min(self.C, alpha_i + alpha_j)
if L < H:
eta = 2 * k[i, j] - k[i, i] - k[j, j]
if eta > 0:
a = 691 + 0j
a_old = 239 + 0j
change = True
while change:
a_old = a
a = alpha_i + np.sign(y[i] - (1 + eta / 2) * y[j]) * self.C / 2
a = np.clip(a, L, H)
alpha_diff = a - alpha_old
if np.linalg.norm(alpha_diff) < 1e-6:
change = False
self.alpha[i] = a
self.alpha[j] += y[i] * y[j] * alpha_diff
self.b += y[i] * (1 - self.kernel_function(X[i], X[i])) - y[j] * (1 - self.kernel_function(X[j], X[j]))
self.b = (self.b + 1) / 2
if self.alpha[i] > 0 and self.alpha[i] < self.C:
self.support_vectors[i] = X[i]
self.support_vectors_labels[i] = y[i]
if self.alpha[j] > 0 and self.alpha[j] < self.C:
self.support_vectors[j] = X[j]
self.support_vectors_labels[j] = y[j]
self.fit_status = True
def predict(self, X):
if not self.fit_status:
raise ValueError("SVM has not been trained yet.")
return np.sign(np.dot(self.kernel_function(X, self.support_vectors), self.alpha * self.support_vectors_labels) + self.b)
def predict_proba(self, X):
predictions = self.predict(X)
proba = np.abs(predictions - 1) / 2
return proba
这个实现并没有包括数据标准化、错误处理、参数调整等高级特性,这些在实际的SVM实现中是非常重要的。如果你需要一个更强大、更高效的SVM实现,建议使用像Scikit-learn这样的库,它们提供了高效的优化算法和丰富的功能。