前言:
本专栏一直在更新机器学习的内容,欢迎点赞收藏哦!
笔者水平有限,文中掺杂着自己的理解和感悟,如果有错误之处还请指出,可以在评论区一起探讨!
支持向量机(support vector machines, SVM)是一种二分类模型,它的基本模型是定义在特征空间上的间隔最大的线性分类器,间隔最大使它有别于感知机
上一篇讲KRR时,我们也提到了一点SVM。在这一节中我们详细的说明一下这种方法。
主要是三种分类算法:SVC(C-Support Vector Classification),NuSVC(Nu-Support Vector Classification)和LinearSVC(Linear Support Vector Classification)。我们就简单的来看一下,区别和使用方法。
SVC和NuSVC方法基本一致,唯一区别就是损失函数的度量方式不同。
• NuSVC中的nu参数(训练误差部分的上限和⽀持向量部分的下限,取值在(0,1)之间,默认是0.5)和SVC中的C参数(c越等于0,惩罚越大,准确率高,但容易过拟合);
• LinearSVC是实现线性核函数的支持向量分类,没有kernel参数。
- import numpy as np
- from sklearn.svm import SVC
- from sklearn.pipeline import make_pipeline
- import matplotlib.pyplot as plt
- from sklearn.preprocessing import StandardScaler
-
- x = np.array([[-1, -1], [-2, -1], [1, 1], [2, 1]])
- y = np.array([1, 1, 2, 2])
- clf = make_pipeline(StandardScaler(), SVC(gamma='auto'))
- clf.fit(x, y)
- x_test = np.array([[-0.8, -1]])
-
- y_test = clf.predict(x_test)
- x_line = np.linspace(-2, 2, 100)
-
- # 绘制训练集数据点
- plt.scatter(x[:, 0], x[:, 1], c=y, cmap=plt.cm.Paired, label='Training Points')
-
- # 绘制决策边界
- x_min, x_max = x[:, 0].min() - 1, x[:, 0].max() + 1
- y_min, y_max = x[:, 1].min() - 1, x[:, 1].max() + 1
- xx, yy = np.meshgrid(np.linspace(x_min, x_max, 100), np.linspace(y_min, y_max, 100)) # 生成了一个二维的网格点坐标矩阵
- Z = clf.predict(np.c_[xx.ravel(), yy.ravel()]) # 预测坐标范围内每个点的类别
- Z = Z.reshape(xx.shape)
- plt.contourf(xx, yy, Z, cmap=plt.cm.Paired, alpha=0.8) # cmap=plt.cm.Paired 指定了等高线的颜色映射
-
- # 绘制测试点
- plt.scatter(x_test[:, 0], x_test[:, 1], c='red', marker='x', label='Test Point')
-
- plt.xlabel('Feature 1')
- plt.ylabel('Feature 2')
- plt.title('SVM Classification')
- plt.legend()
- plt.show()
- import numpy as np
- from sklearn.svm import SVC,NuSVC
- from sklearn.pipeline import make_pipeline
- import matplotlib.pyplot as plt
- from sklearn.preprocessing import StandardScaler
-
- x = np.array([[-1, -1], [-2, -1], [1, 1], [2, 1]])
- y = np.array([1, 1, 2, 2])
- clf = make_pipeline(StandardScaler(), NuSVC())
- clf.fit(x, y)
- x_test = np.array([[-0.8, -1]])
-
- y_test = clf.predict(x_test)
- x_line = np.linspace(-2, 2, 100)
-
- # 绘制训练集数据点
- plt.scatter(x[:, 0], x[:, 1], c=y, cmap=plt.cm.Paired, label='Training Points')
-
- # 绘制决策边界
- x_min, x_max = x[:, 0].min() - 1, x[:, 0].max() + 1
- y_min, y_max = x[:, 1].min() - 1, x[:, 1].max() + 1
- xx, yy = np.meshgrid(np.linspace(x_min, x_max, 100), np.linspace(y_min, y_max, 100)) # 生成了一个二维的网格点坐标矩阵
- Z = clf.predict(np.c_[xx.ravel(), yy.ravel()]) # 预测坐标范围内每个点的类别
- Z = Z.reshape(xx.shape)
- plt.contourf(xx, yy, Z, cmap=plt.cm.Paired, alpha=0.8) # cmap=plt.cm.Paired 指定了等高线的颜色映射
-
- # 绘制测试点
- plt.scatter(x_test[:, 0], x_test[:, 1], c='red', marker='x', label='Test Point')
-
- plt.xlabel('Feature 1')
- plt.ylabel('Feature 2')
- plt.title('NuSVC Classification')
- plt.legend()
- plt.show()

LinearSVC代码:
- import numpy as np
- from sklearn.svm import LinearSVC
- from sklearn.pipeline import make_pipeline
- from sklearn.preprocessing import StandardScaler
- from sklearn.datasets import make_classification
- import matplotlib.pyplot as plt
-
- X, y = make_classification(n_features=4, random_state=0) #随机生成样本
- clf = make_pipeline(StandardScaler(),LinearSVC(dual="auto", random_state=0, tol=1e-5))
-
- clf.fit(X,y)
- coef=clf.named_steps['linearsvc'].coef_
- intercept=clf.named_steps['linearsvc'].intercept_
- x_test=np.array([[0,0,0,0]])
- y_test=clf.predict(x_test)
- from sklearn.decomposition import PCA
-
- # 将数据投影到二维平面
- pca = PCA(n_components=2)
- X_pca = pca.fit_transform(X)
-
- # 训练 LinearSVC
- clf.fit(X_pca, y)
- # 投影测试点到二维空间
- x_test_pca = pca.transform(x_test)
-
- # 绘制样本点
- plt.scatter(X_pca[:, 0], X_pca[:, 1], c=y, cmap=plt.cm.Paired)
-
- # 绘制决策边界
-
-
- # 绘制测试点
- plt.scatter(x_test_pca[:, 0], x_test_pca[:, 1], c='red', marker='x', label='Test Point')
- # 获取系数和截距
- coef = clf.named_steps['linearsvc'].coef_
- intercept = clf.named_steps['linearsvc'].intercept_
-
- # 绘制样本点
- plt.scatter(X_pca[:, 0], X_pca[:, 1], c=y, cmap=plt.cm.Paired)
-
- # 绘制决策边界
- x_min, x_max = X_pca[:, 0].min() - 1, X_pca[:, 0].max() + 1
- y_min, y_max = X_pca[:, 1].min() - 1, X_pca[:, 1].max() + 1
- xx, yy = np.meshgrid(np.arange(x_min, x_max, 0.02),
- np.arange(y_min, y_max, 0.02))
- Z = clf.predict(np.c_[xx.ravel(), yy.ravel()])
- Z = Z.reshape(xx.shape)
- plt.contourf(xx, yy, Z, cmap=plt.cm.Paired, alpha=0.8)
-
- plt.xlabel('Principal Component 1')
- plt.ylabel('Principal Component 2')
- plt.title('Linear SVM Decision Boundary (PCA)')
- plt.show()

这一部分不好画在二维图片上,我们使用了PCA降维技术,降维到平面上再显现在二维平面上的。相当于降维之后又训练了一遍,才能画出来的。
分为:SVR,NuSVR,LinearSVR。
方法和上面差不多,我们就不多讲了。
和
之间
SVC、SVR、NuSVC和NuSVR如果不按照特定方法输入,数据就会被拷贝一份。LinearSVC和LogisticRegression任何numpy数组输入都会被拷贝。如果是大规模线性分类器且不想拷贝数据,可以使用SGDC.SVC、SVR、NuSVC和NuSVR,核缓存的大小对较大问题求解的运行时间有非常强的影响,如果你有足够内存,建议将cache_size设置为一个高于默认值200(MB)的值,比如500(MB)或1000(MB)。C设为1,这是一个合理的选择。如果样本中有许多噪音观察点,则应该减小这个值。这意味着对估计结果进行更严格的正则化。
在拟合数据之前一定要打乱训练数据(shuffle=True)并进行标准化(make_pipeline(StandardScaler(), SGDClassifier()))
梯度下降(Gradient Descent):
随机梯度下降(Stochastic Gradient Descent,SGD):
小批量梯度下降(Mini-batch Gradient Descent):
总结:
GD和SGD主要区别为训练过程中使用的样本数量不同,GD需要大开销,SGD不稳定。
主要是通过计算样本的损失函数,迭代更新模型参数。让这个
不断变换(如下图公式),直到达到最大迭代次数或者损失函数收敛到某个值以内。

误差函数有很多种可以按需挑选。


学习率先写这么多监督算法,后面再慢慢补充,可能还会补充朴素贝叶斯和决策树、特征选择。
大家可以先点赞关注,以后慢慢看哦!