機器學習 嶺回歸 小白筆記

2021-10-23 17:13:47 字數 3082 閱讀 9571

嶺回歸,其實也是一種線性回歸。只不過在演算法建立回歸方程的時候,加上正則化的限制,從而達到解決過擬合的效果。

"""正規化的優化方法對波士頓房價進行評估

:return:

"""#1 獲取資料

boston=load_boston()

print("特徵數量",boston.data.shape)

#2 劃分資料集

x_train,x_test,y_train,y_test=train_test_split(boston.data,boston.target,random_state=22)

#3 特徵抽取 標準化

transfer=standardscaler()

x_train=transfer.fit_transform(x_train)

#跟測試集做一樣的處理

x_test=transfer.transform(x_test)

#4 演算法預估器

estimator=linearregression()

estimator.fit(x_train,y_train)

#5得出模型

print("正規方程權重係數為:",estimator.coef_)

print("正規方程偏置為:", estimator.intercept_)

#6均方誤差

y_predict=estimator.predict(x_test)

error=mean_squared_error(y_test,y_predict)

print("正規方程-均方誤差為",error)

def linear2():

"""梯度下降的優化方法對波士頓房價進行評估

:return:

"""# 1 獲取資料

boston = load_boston()

# 2 劃分資料集

x_train, x_test, y_train, y_test = train_test_split(boston.data, boston.target, random_state=22)

# 3 特徵抽取 標準化

transfer = standardscaler()

x_train = transfer.fit_transform(x_train)

# 跟測試集做一樣的處理

x_test = transfer.transform(x_test)

# 4 演算法預估器

estimator = sgdregressor(learning_rate="constant",eta0=0.01,max_iter=100000)

estimator.fit(x_train, y_train)

# 5得出模型

print("梯度下降權重係數為:", estimator.coef_)

print("梯度下降偏置為:", estimator.intercept_)

# 6均方誤差

y_predict = estimator.predict(x_test)

error = mean_squared_error(y_test, y_predict)

print("梯度下降-均方誤差為", error)

return none

def linear3():

"""嶺回歸的優化方法對波士頓房價進行評估

:return:

"""# 1 獲取資料

boston = load_boston()

# 2 劃分資料集

x_train, x_test, y_train, y_test = train_test_split(boston.data, boston.target, random_state=22)

# 3 特徵抽取 標準化

transfer = standardscaler()

x_train = transfer.fit_transform(x_train)

# 跟測試集做一樣的處理

x_test = transfer.transform(x_test)

# 4 演算法預估器

estimator = ridge(max_iter=10000,alpha=0.01)

estimator.fit(x_train, y_train)

# 5得出模型

print("嶺回歸權重係數為:", estimator.coef_)

print("嶺回歸偏置為:", estimator.intercept_)

# 6均方誤差

y_predict = estimator.predict(x_test)

error = mean_squared_error(y_test, y_predict)

print("嶺回歸-均方誤差為", error)

return none

if __name__ == '__main__':

linear1()

print("\t")

linear2()

print("\t")

linear3()

機器學習 嶺回歸和LASSO回歸

1.用矩陣表示多元線性回歸 y bx a q b y bx t y bx 達到最小時的b值。也即是殘差平方和最小時。b bi 的值。可以證明b的最小二乘估計 xtx 1xty 其中 xtx 1為廣義逆。1.出現多重共線性2.當n 嶺回歸 ridge regression 先對資料做標準化 b k x...

機器學習 監督學習 (回歸)嶺回歸

1 嶺回歸 標準方程法 import numpy as np from numpy import genfromtxt import matplotlib.pyplot as plt 讀入資料 data genfromtxt r longley.csv delimiter 切分資料 x data d...

《機器學習實戰》學習筆記 10 回歸 嶺回歸

機器學習實戰 學習筆記 10 回歸 嶺回歸 縮減方法可以去除不重要的引數 備註 同樣,為使用嶺回歸和縮減技術,首先需要對特徵做標準化處理,標準化使得每維度下的特徵有相同的重要性,具體 所有特徵減去各自的均值並除以方差 機器學習實戰 回歸 from numpy import def loaddatas...