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


1 案例背景

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

2 案例分析

回歸當中的數據大小不一致,是否會導致結果影響較大。所以需要做標准化處理。

  • 數據分割與標准化處理
  • 回歸預測
  • 線性回歸的算法效果評估

3 回歸性能評估

均方誤差(Mean Squared Error)MSE)評價機制:

  • 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)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM