一.描述
- 支持向量机属于监督学习方法,不仅可以用于分类,还可以用于回归。
- SVR回归模型
- NuSVR回归模型
- LinearSVR回归模型
二.用法和参数
支持向量机回归模型有很多参数,比较重要的有kernel参数和C参数。
- kernel参数用来选择内核算法
- C是误差项的惩罚参数,取值一般为10的整数次幂,如0.001, 0.1,1000等
- C值越大,对误差项的惩罚越大,因此训练集测试时准确率就高,但泛化能力弱
- C值越小,对误差项的惩罚越小,因此容错能力越强,泛化能力也相对越强
三.实例
-
随机生成100个样本点
import numpy as np import matplotlib.pyplot as plt import mpl_toolkits.mplot3d # 生成50*50的网格 x, y = np.mgrid[-2:2:50j, -2:2:50j] # 计算网格上每一点的高度值 z = x * np.exp(-x ** 2 - y ** 2) # 随机生成区间[-2, 2]内的100个x _x = np.random.random(100) * 4 - 2 # 随机生成区间[-2, 2]内的100个y _y = np.random.random(100) * 4 - 2 _z = _x * np.exp(-_x ** 2 - _y ** 2) + (np.random.random(100) - 0.5) * 0.1 ax = plt.subplot(111, projection='3d') # 画50*50的网格曲面 ax.plot_surface(x, y, z, cmap=plt.cm.hsv, alpha=0.5) # 画100个样本点 ax.scatter3D(_x, _y, _z, c='r') plt.show()
-
用支持向量机回归模型对100个样本做回归分析,观察不同的参数对回归结果的影响
x, y = np.mgrid[-2:2:50j, -2:2:50j] z = x * np.exp(-x ** 2 - y ** 2) _x = np.random.random(100) * 4 - 2 _y = np.random.random(100) * 4 - 2 _z = _x * np.exp(-_x ** 2 - _y ** 2) + (np.random.random(100) - 0.5) * 0.1 # 训练样本集 X_train = np.stack((_x, _y), axis =1) # 训练标签集 y_train = _z # 测试样本集 X_test = np.stack((x.ravel(), y.ravel()), axis=1) # 测试标签集 y_test = z.ravel() # 实例化SVR模型,rbf核函数, C=0.1 svr_1 = SVR(kernel='rbf', C=0.1) # 实例化SVR模型,rbf核函数,C=100 svr_2 = SVR(kernel='rbf', C=100) # 模型训练 svr_1.fit(X_train, y_train) svr_2.fit(X_train, y_train) # 模型预测 z_1 = svr_1.predict(X_test) z_2 = svr_2.predict(X_test) # 模型评估 score_1 = svr_1.score(X_test, y_test) score_2 = svr_2.score(X_test, y_test) score_1 score_2 ax = plt.subplot(121, projection='3d') ax.scatter3D(_x, _y, _z, c='r') ax.plot_surface(x, y, z_1.reshape(x.shape), cmap=plt.cm.hsv, alpha=0.5) plt.title('score:%0.3f@kernel="rbf", C=0.1' % score_1) ax = plt.subplot(122, projection='3d') ax.scatter3D(_x, _y, _z, c='r') ax.plot_surface(x, y, z_2.reshape(x.shape), cmap=plt.cm.hsv, alpha=0.5) plt.title('score:%0.3f@kernel="rbf", C=100' % score_2) plt.show()
-
使用线性核函数或多项式核函数
# 实例化SVR模型,线性核函数, C=100 svr_1 = SVR(kernel='linear', C=100) # 实例化SVR模型, 多项式核函数 svr_2 = SVR(kernel='poly', C=100) # 模型训练 svr_1.fit(X_train, y_train) # 模型训练 svr_2.fit(X_train, y_train) # 模型预测 z_1 = svr_1.predict(X_test) # 模型预测 z_2 = svr_2.predict(X_test) # 模型评估 score_1 = svr_1.score(X_test, y_test) # 模型评估 score_2 = svr_2.score(X_test, y_test) score_1 score_2 ax = plt.subplot(121, projection='3d') ax.scatter3D(_x, _y, c='r') ax.plot_surface(x, y, z_1.reshape(x.shape), cmap=plt.cm.hsv, alpha=0.5) plt.title('score:%0.3f@kernel="linear", C=100') ax = plt.subplot(122, projection='3d') ax.scatter3D(_x, _y, _z, c='r') ax.plot_surface(x, y, z_2.reshape(x.shape), cmap=plt.cm.hsv, alpha=0.5) plt.title('score:%0.3f@kernel="poly", C=100' % score_2) plt.show()