1 案例背景

线性回归6-波士顿房价预测_线性回归

线性回归6-波士顿房价预测_线性回归_02

给定的这些特征,是专家们得出的影响房价的结果属性。我们此阶段不需要自己去探究特征是否有用,只需要使用这些特征。到后面量化很多特征需要我们自己去寻找

2 案例分析

回归当中的数据大小不一致,是否会导致结果影响较大。所以需要做标准化处理。

  • 数据分割与标准化处理
  • 回归预测
  • 线性回归的算法效果评估
3 回归性能评估

均方误差(Mean Squared Error)MSE)评价机制:
线性回归6-波士顿房价预测_机器学习_03
线性回归6-波士顿房价预测_机器学习_04

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