SVM分類,就是找到一個平面,讓兩個分類集合的支持向量或者全部的數據(LSSVM)離分類平面最遠;python
SVR迴歸,就是找到一個迴歸平面,讓一個集合的全部數據到該平面的距離最近。
算法
SVR是支持向量迴歸(support vector regression)的英文縮寫,是支持向量機(SVM)的重要的應用分支。函數
傳統迴歸方法當且僅當迴歸f(x)徹底等於y時才認爲預測正確,如線性迴歸中經常使用(f(x)−y)2來計算其損失。測試
而支持向量迴歸則認爲只要f(x)與y偏離程度不要太大,既能夠認爲預測正確,不用計算損失,具體的,就是設置閾值α,只計算|f(x)−y|>α的數據點的loss,以下圖所示,陰影部分的數據點咱們都認爲該模型預測準確了,只計算陰影外的數據點的loss:
atom
數據處理
preprocessing.scale()做用:
scale()是用來對原始樣本進行縮放的,範圍能夠本身定,通常是[0,1]或[-1,1]。
縮放的目的主要是
1)防止某個特徵過大或太小,從而在訓練中起的做用不平衡;
2)爲了計算速度。由於在覈計算中,會用到內積運算或exp運算,不平衡的數據可能形成計算困難。
spa
對於SVM算法,咱們首先導入sklearn.svm中的SVR模塊。SVR()就是SVM算法來作迴歸用的方法(即輸入標籤是連續值的時候要用的方法),經過如下語句來肯定SVR的模式(選取比較重要的幾個參數進行測試。隨機選取一隻股票開始相關參數選擇的測試)。
svr = SVR(kernel=’rbf’, C=1e3, gamma=0.01)code
kernel:核函數的類型,通常經常使用的有’rbf’,’linear’,’poly’,等如圖4-1-2-1所示,發現使用rbf參數時函數模型的擬合效果最好。 orm
C:懲罰因子
blog
C表徵你有多麼重視離羣點,C越大越重視,越不想丟掉它們。C值大時對偏差分類的懲罰增大,C值小時對偏差分類的懲罰減少。當C越大,趨近無窮的時候,表示不容許分類偏差的存在,margin越小,容易過擬合;當C趨於0時,表示咱們再也不關注分類是否正確,只要求margin越大,容易欠擬合。如圖所示發現當使用1e3時最爲適宜。string
gamma:
是’rbf’,’poly’和’sigmoid’的核係數且gamma的值必須大於0。隨着gamma的增大,存在對於測試集分類效果差而對訓練分類效果好的狀況,而且容易泛化偏差出現過擬合。如圖發現gamma=0.01時準確度最高。
咱們此次用的數據是公司內部不一樣的promotion level所對應的薪資
下面咱們來看一下在Python中是如何實現的
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
dataset = pd.read_csv('Position_Salaries.csv')
X = dataset.iloc[:, 1:2].values
# 這裏注意:1:2其實只有第一列,與1 的區別是這表示的是一個matrix矩陣,而非單一貫量。
y = dataset.iloc[:, 2].values
接下來,處理數據:
# Reshape your data either using array.reshape(-1, 1) if your data has a single feature # array.reshape(1, -1) if it contains a single sample. X = np.reshape(X, (-1, 1)) y = np.reshape(y, (-1, 1)) # Feature Scaling from sklearn.preprocessing import StandardScaler sc_X = StandardScaler() sc_y = StandardScaler() X = sc_X.fit_transform(X) y = sc_y.fit_transform(y)
接下來,進入正題,開始SVR迴歸:
# Fitting SVR to the dataset from sklearn.svm import SVR regressor = SVR(kernel = 'rbf') regressor.fit(X, y) # Predicting a new result y_pred = regressor.predict(sc_X.transform(np.array([[6.5]]))) # 轉換回正常預測值 y_pred = sc_y.inverse_transform(y_pred)
# 圖像中顯示
plt.scatter(X, y, color = 'red')
plt.plot(X, regressor.predict(X), color = 'blue')
plt.title('Truth or Bluff (SVR)')
plt.xlabel('Position level')
plt.ylabel('Salary')
plt.show()
# Visualising the SVR results (for higher resolution and smoother curve) X_grid = np.arange(min(X), max(X), 0.01) # choice of 0.01 instead of 0.1 step because the data is feature scaled X_grid = X_grid.reshape((len(X_grid), 1)) plt.scatter(X, y, color = 'red') plt.plot(X_grid, regressor.predict(X_grid), color = 'blue') plt.title('Truth or Bluff (SVR)') plt.xlabel('Position level') plt.ylabel('Salary') plt.show()