天天看點

2. PCA&多項式回歸&CV&嶺回歸&LASSO& 彈性網

PCA

作用:降維降低資料量,降低處理時間; 降噪功能

使用方法:

from sklearn.decomposition import PCA  # 引入PCA
pca = PCA(0.95)  # 根據比例算出pca降維量
pca.fit(x_train)  # 進行計算出降維量
pca.n_components_  # 降維後的量
x_train_reduction = pca.transform(x_train)   # 對資料降維處理
x_test_reduction = pca.transform(x_test)

# 降噪處理過程
X_reduction = pca.transform(X)  # 1. 先降維
X_restore = pca.inverse_transform(X_reduction) # 2. 再恢複次元

           

多項式回歸

  • 線性回歸:y = a*x + b
  • 多項式回歸: y = a * x^2 + b*x + c
from sklearn.preprocessing import PolynomialFeatures   # 多回歸線性參數設定
poly = PolynomialFeatures( degree=2 )  # 2次系數
poly.fit(x)
x2 = poly.transform(x)  # 對訓練樣本2次化

from sklearn.linear_model import LinearRegression  # 多項式回歸仍然是線性回歸
lin_reg = LinearRegression()
lin_reg.fit(x2, y)     # 對處理後的樣本使用二次回歸方程
y_predict = lin_reg.predict(x2)

lin_reg.coef_  # 回歸方程的系數
lin_reg.intercept_  # 方程的截距

# 顯示多項式的方程曲線
plt.scatter(x_row,y)
plt.plot(np.sort(x_row), y_predict[np.argsort(x_row)], color='r')
plt.show()
           
  • 對于

    degree

    參數的設定會影響矩陣的擴充
x = np.arange(1,11).reshape(-1,2)
x  # x have two columns x1, x2

poly2 = PolynomialFeatures(degree=2)
poly2.fit(x)
x2 = poly2.transform(x)  # after transform x2 add three columns
x2                       # x1**2 , x1*x2, x2**2

poly3 = PolynomialFeatures(degree=3)  # (x1 + x2) ^ 3
poly3.fit(x)
x3 = poly3.transform(x)  # x1**3,x2**3, x1*x2**2, x2*x1**2, x1**2,x2**2
x3                       # add 7 columns
           

管道連接配接多個方法

from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler

poly_reg = Pipeline([                         # 使用管道連接配接多個方法
    ('poly', PolynomialFeatures(degree=2)),
    ('std_scaler', StandardScaler()),
    ('lin_reg', LinearRegression())
])

poly_reg.fit(x, y)        # 直接對管道執行個體化後的對象訓練和預測計算
y_predict = poly_reg.predict(x)
poly_reg.score(x_test)
           

過拟合和欠拟合

測試資料集的意義: 尋找測試資料集最佳的點,泛化能力最好的地方

學習曲線

交叉驗證Cross Validation

CV驗證,對訓練資料集劃分多個等塊,分别取某一塊為驗證資料集,避免一塊測試資料集的不準确,取驗證資料集驗證結果最好的一個。

留一法LOO—CV:将訓練資料集分成m份,留一份訓練

leave-one-out cross validation

from sklearn.neighbors import KNeighborsClassifier
from sklearn.model_selection import cross_val_score   # 1.通過交叉驗證方法驗證

knn_clf = KNeighborsClassifier()
cross_val_score(knn_clf, x_train, y_train, cv=10)


from sklearn.model_selection import GridSearchCV   # 2. 使用網格搜尋交叉驗證
parame = [
    {
        'weights': ['distance'],
        'n_neighbors':[i for i in range(2,10)],
        'p':[i for i in range(1,6)]
    }
]
gridsearchcv = GridSearchCV(knn_clf, parame, verbose=1, cv=5)  # cv參數代表交叉驗證的折數,
gridsearchcv.fit(x_train, y_train)
gridsearchcv.best_params_    # 使用交叉驗證取得的最佳參數
gridsearchcv.best_score_    # 使用交叉驗證取得的最佳結果
           

偏差bias & 方差variance

偏差:偏離目标值得位置

方差:離散的程度

模型誤差:偏差+方差+不可避免的誤差

偏差:

​ 對問題的假設不正确:非線性使用回歸線性預測

​ 欠拟合:

​ 參數學習通常為高偏差,線性回歸天生的高偏差,假設的影響很大

方差:

​ 過拟合:對模型過于複雜,如使用高階方程模拟回歸,degree過大

​ 非參數學習通常為高方差, KNN天生的高方差,不對資料進行假設

偏差和方差通常是沖突的。低偏差高方差,低方差高偏差

機器學習主要問題來自于 方差

解決手段:

  1. 降低模型複雜度
  2. 降維降噪
  3. 增加樣本數
  4. 使用驗證集
  5. 模型的正則化

模型泛化:嶺回歸& lasso回歸& 彈性網Elastic Net

多項式回歸過拟合的情況,有一些系數會很大,模型正則化就是限制其不要太大

2. PCA&多項式回歸&CV&嶺回歸&LASSO& 彈性網

LASSO更傾向于直線,Ridge更傾向于曲線,

LASSO對應的theta有的為零,Selection Operator對應的特征無用

2. PCA&多項式回歸&CV&嶺回歸&LASSO& 彈性網
# Ridge ||y - Xw||^2_2 + alpha * ||w||^2_2
from sklearn.linear_model import Ridge  
ridge = Ridge(alpha=1.0)   # 嶺回歸的執行個體化及參數設定 
ridge.fit(x_train,y_train)
y_predict = ridge.predict(x_test)
result = ridge.score(x_test, y_test)

# LASSO  (1 / (2 * n_samples)) * ||y - Xw||^2_2 + alpha * ||w||_1
from sklearn.linear_model import Lasso

           

繼續閱讀