Linear SVM和LR的区别和联系

首先,SVM和LR(Logistic Regression)都是分类算法。SVM通常有4个核函数,其中一个是线性核,当使用线性核时,SVM就是Linear SVM,其实就是一个线性分类器,而LR也是一个线性分类器,这是两者的共同之处。

不同之处在于,第一,LR只要求计算出一个决策面,把样本点分为两类就行了,不要求分得有多好;而Linear SVM要求决策面距离两个类的点的距离要最大。

第二,Linear SVM只考虑边界线附近的点,而LR要考虑整个样本所有的点,如果增加一些样本点,只要这些样本点不在Linear SVM的边界线附近(即在支持向量外),Linear SVM的决策面是不会变的,而LR的决策面是会发生变化的,即LR中每个样本点都会对决策面产生影响。

第三,由于指导思想的不同,两者的Loss function是不同的。

linear_svm.py: ```python import numpy as np class LinearSVM: def __init__(self, lr=0.01, reg=0.01, num_iters=1000, batch_size=32): self.lr = lr self.reg = reg self.num_iters = num_iters self.batch_size = batch_size self.W = None self.b = None def train(self, X, y): num_train, dim = X.shape num_classes = np.max(y) + 1 if self.W is None: self.W = 0.001 * np.random.randn(dim, num_classes) self.b = np.zeros((1, num_classes)) loss_history = [] for i in range(self.num_iters): batch_idx = np.random.choice(num_train, self.batch_size) X_batch = X[batch_idx] y_batch = y[batch_idx] loss, grad_W, grad_b = self.loss(X_batch, y_batch) loss_history.append(loss) self.W -= self.lr * grad_W self.b -= self.lr * grad_b return loss_history def predict(self, X): scores = X.dot(self.W) + self.b y_pred = np.argmax(scores, axis=1) return y_pred def loss(self, X_batch, y_batch): num_train = X_batch.shape[0] scores = X_batch.dot(self.W) + self.b correct_scores = scores[range(num_train), y_batch] margins = np.maximum(0, scores - correct_scores[:, np.newaxis] + 1) margins[range(num_train), y_batch] = 0 loss = np.sum(margins) / num_train + 0.5 * self.reg * np.sum(self.W * self.W) num_pos = np.sum(margins > 0, axis=1) dscores = np.zeros_like(scores) dscores[margins > 0] = 1 dscores[range(num_train), y_batch] -= num_pos dscores /= num_train grad_W = np.dot(X_batch.T, dscores) + self.reg * self.W grad_b = np.sum(dscores, axis=0, keepdims=True) return loss, grad_W, grad_b ``` linear_classifier.py: ```python import numpy as np class LinearClassifier: def __init__(self, lr=0.01, reg=0.01, num_iters=1000, batch_size=32): self.lr = lr self.reg = reg self.num_iters = num_iters self.batch_size = batch_size self.W = None self.b = None def train(self, X, y): num_train, dim = X.shape num_classes = np.max(y) + 1 if self.W is None: self.W = 0.001 * np.random.randn(dim, num_classes) self.b = np.zeros((1, num_classes)) loss_history = [] for i in range(self.num_iters): batch_idx = np.random.choice(num_train, self.batch_size) X_batch = X[batch_idx] y_batch = y[batch_idx] loss, grad_W, grad_b = self.loss(X_batch, y_batch) loss_history.append(loss) self.W -= self.lr * grad_W self.b -= self.lr * grad_b return loss_history def predict(self, X): scores = X.dot(self.W) + self.b y_pred = np.argmax(scores, axis=1) return y_pred def loss(self, X_batch, y_batch): num_train = X_batch.shape[0] scores = X_batch.dot(self.W) + self.b correct_scores = scores[range(num_train), y_batch] margins = np.maximum(0, scores - correct_scores[:, np.newaxis] + 1) margins[range(num_train), y_batch] = 0 loss = np.sum(margins) / num_train + 0.5 * self.reg * np.sum(self.W * self.W) num_pos = np.sum(margins > 0, axis=1) dscores = np.zeros_like(scores) dscores[margins > 0] = 1 dscores[range(num_train), y_batch] -= num_pos dscores /= num_train grad_W = np.dot(X_batch.T, dscores) + self.reg * self.W grad_b = np.sum(dscores, axis=0, keepdims=True) return loss, grad_W, grad_b ``` svm.ipynb: ```python import numpy as np import matplotlib.pyplot as plt from sklearn.datasets import make_blobs, make_moons from sklearn.model_selection import train_test_split from linear_classifier import LinearClassifier def plot_data(X, y, title): plt.scatter(X[:, 0], X[:, 1], c=y, cmap=plt.cm.RdBu) plt.title(title) plt.xlabel('Feature 1') plt.ylabel('Feature 2') plt.show() def plot_decision_boundary(clf, X, y, title): plt.scatter(X[:, 0], X[:, 1], c=y, cmap=plt.cm.RdBu) ax = plt.gca() xlim = ax.get_xlim() ylim = ax.get_ylim() xx = np.linspace(xlim[0], xlim[1], 100) yy = np.linspace(ylim[0], ylim[1], 100) XX, YY = np.meshgrid(xx, yy) xy = np.vstack([XX.ravel(), YY.ravel()]).T Z = clf.predict(xy).reshape(XX.shape) plt.contour(XX, YY, Z, levels=[0], colors='k', linestyles='-') plt.title(title) plt.xlabel('Feature 1') plt.ylabel('Feature 2') plt.show() def main(): X, y = make_blobs(n_samples=200, centers=2, random_state=42) plot_data(X, y, 'Linearly Separable Data') X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) clf = LinearClassifier() loss_history = clf.train(X_train, y_train) train_acc = np.mean(clf.predict(X_train) == y_train) test_acc = np.mean(clf.predict(X_test) == y_test) print('Train accuracy: {:.3f}, Test accuracy: {:.3f}'.format(train_acc, test_acc)) plot_decision_boundary(clf, X, y, 'Linear SVM') if __name__ == '__main__': main() ``` 以上的代码实现了一个简单的线性 SVM,可以用于二分类问题。在 `svm.ipynb` 文件中,我们使用 `make_blobs` 生成了一个线性可分的数据集,然后将其拆分为训练集和测试集。接着,我们使用 `LinearClassifier` 对训练集进行训练,并在测试集上评估模型性能。最后,我们绘制了模型的决策边界。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值