SVM官方教程:SVR 簡易教程

SVR: 簡易使用教程

SVR 簡易教程

In [1]:
import numpy as np
from sklearn.svm import SVR
import matplotlib.pyplot as plt

構造數據

In [2]:
# Generate sample data
X = np.sort(5 * np.random.rand(40, 1), axis=0)
y = np.sin(X).ravel()
In [3]:
# Add noise to targets
y[::5] += 3 * (0.5 - np.random.rand(8))

選擇核函數

In [4]:
svr_rbf = SVR(kernel='rbf', C=100, gamma=0.1, epsilon=.1)
svr_lin = SVR(kernel='linear', C=100, gamma='auto')
svr_poly = SVR(kernel='poly', C=100, gamma='auto', degree=3, epsilon=.1,
               coef0=1)

技巧:繪圖 $linewidths$ 的簡易寫法 $lw $,這我之前還不知道。javascript

In [11]:
lw = 2 

svrs = [svr_rbf, svr_lin, svr_poly]
kernel_label = ['RBF', 'Linear', 'Polynomial']
model_color = ['b', 'k', 'g']
In [26]:
fig, axes = plt.subplots(nrows=1, ncols=3, figsize=(12, 6), sharey=True)
for ix, svr in enumerate(svrs):
    axes[ix].plot(X, svr.fit(X, y).predict(X), color=model_color[ix], lw=lw,
                  label='{} model'.format(kernel_label[ix]))
    axes[ix].scatter(X[svr.support_], y[svr.support_], facecolor="none",
                     edgecolor=model_color[ix], s=50,
                     label='{} support vectors'.format(kernel_label[ix]))
    axes[ix].scatter(X[np.setdiff1d(np.arange(len(X)), svr.support_)],
                     y[np.setdiff1d(np.arange(len(X)), svr.support_)],
                     facecolor="none", edgecolor="r", s=50,
                     label='other training data')
    axes[ix].legend(loc='upper center', bbox_to_anchor=(0.5, 1.1),
                    ncol=1, fancybox=True, shadow=True)

fig.text(0.5, 0.04, '數據', ha='center', va='baseline')
fig.text(0.06, 0.5, '目標值', ha='center', va='baseline', rotation='vertical')
fig.suptitle("Support Vector Regression", fontsize=14)

plt.rcParams['font.sans-serif'] = ['SimHei']  # 用來正常顯示中文標籤
plt.rcParams['axes.unicode_minus'] = False  # 用來正常顯示負號

plt.show()
相關文章
相關標籤/搜索