天天看點

線性回歸6-波士頓房價預測

1 案例背景

線性回歸6-波士頓房價預測
線性回歸6-波士頓房價預測

給定的這些特征,是專家們得出的影響房價的結果屬性。我們此階段不需要自己去探究特征是否有用,隻需要使用這些特征。到後面量化很多特征需要我們自己去尋找

2 案例分析

  • 資料分割與标準化處理
  • 回歸預測
  • 線性回歸的算法效果評估

3 回歸性能評估

  • sklearn.metrics.mean_squared_error(y_true, y_pred)
    • 均方誤差回歸損失
    • y_true:真實值
    • y_pred:預測值
    • return:浮點數結果

4 代碼實作

4.1 準備

from sklearn.datasets import load_boston
from sklearn.model_selection import  train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import  LinearRegression,SGDRegressor,RidgeCV,Ridge
from sklearn.metrics import mean_squared_error
           

4.2 正規方程

def liner_model():
    # 1.擷取資料
    boston=load_boston()
    print(boston)
    # 2.資料處理
    # 2.1 分割資料
    x_train,x_test,y_train,y_test=train_test_split(boston.data,boston.target,test_size=0.2)
    # 3.特征工程-資料标準化
    transfer=StandardScaler()
    x_train=transfer.fit_transform(x_train)
    x_test=transfer.fit_transform(x_test)
    # 4.機器學習-線性回歸(正規方程)
    estimator=LinearRegression()
    estimator.fit(x_train,y_train)


    # 5.模型評估
    y_predict = estimator.predict(x_test)
    print("預測值為:\n", y_predict)
    print("模型中的系數為:\n", estimator.coef_)
    print("模型中的偏置為:\n", estimator.intercept_)
    # 評價名額 均方誤差
    error=mean_squared_error(y_test,y_predict)
    print("誤差率:\n",error)

    return None
           

4.3 梯度下降法

def liner_model1() :
    # 1.擷取資料
    boston = load_boston()
    print(boston)
    # 2.資料處理
    # 2.1 分割資料
    x_train, x_test, y_train, y_test = train_test_split(boston.data, boston.target, test_size=0.2)
    # 3.特征工程-資料标準化
    transfer = StandardScaler()
    x_train = transfer.fit_transform(x_train)
    x_test = transfer.fit_transform(x_test)
    # 4.機器學習-線性回歸(梯度下降)
    estimator = SGDRegressor(max_iter=1000)
    estimator.fit(x_train, y_train)

    # 5.模型評估
    y_predict = estimator.predict(x_test)
    print("預測值為:\n", y_predict)
    print("模型中的系數為:\n", estimator.coef_)
    print("模型中的偏置為:\n", estimator.intercept_)
    # 評價名額 均方誤差
    error = mean_squared_error(y_test, y_predict)
    print("均方誤差:\n", error)

    return None

           

4.4 主函數調用

liner_model()
liner_model1()
           
estimator = SGDRegressor(max_iter=1000,learning_rate="constant",eta0=0.1)
           

繼續閱讀