目录
掌握基于Scikit-Learn建立线性回归模型
(1)代码运行环境
Python语言,Jupyter notebook平台
(2)所需模块
numpy,matplotlib,lab_utils_multi,sklearn
(1)解析解&数值解
数值解是近似解,是通过数值计算方法(如迭代法、逼近法等)来逼近问题的解。
解析解是精确解,是根据严格的公式推导,给出任意的自变量就可以求出其因变量的解。
(2)封闭解
封闭解是一种特殊的解析解。
解析解适用于可以通过微积分技巧(如分离变量法)求解的方程。
封闭解适用于一些简单的方程,这些方程可以通过基本的代数运算直接求解。
(3)梯度下降法&Scikit-Learn
基于梯度下降法的回归模型,其参数为近似解。
基于Scikit-Learn的回归模型,其参数为精确解。
以前文中基于多特征建立房价模型的问题为例,原始数据如下:

本文采用Scikit-Learn建立线性回归模型,并对刘先生的房子(1200平方英尺、3个卧室、1层、40年房龄)进行估价。
(1)导入所需模块
- import numpy as np
- np.set_printoptions(precision=2)
- from sklearn.linear_model import LinearRegression, SGDRegressor
- from sklearn.preprocessing import StandardScaler
- from lab_utils_multi import load_house_data
- import matplotlib.pyplot as plt
- dlblue = '#0096ff'; dlorange = '#FF9300'; dldarkred='#C00000'; dlmagenta='#FF40FF'; dlpurple='#7030A0';
- plt.style.use('./deeplearning.mplstyle')
(2)读取二手房交易数据
- # load the dataset
- X_train, y_train = load_house_data()
- X_features = ['size(sqft)','bedrooms','floors','age']
(3)创建linear_model类,用于线性回归
- linear_model = LinearRegression()
- linear_model.fit(X_train, y_train)
(4)计算模型参数
- b = linear_model.intercept_
- w = linear_model.coef_
- print(f"w = {w:}, b = {b:0.2f}")
运行以上代码,结果如下:
w = [0.27 -32.62 -67.25 -1.47], b = 220.42
(5)房价预测
- x_house = np.array([1200, 3,1, 40]).reshape(-1,4)
- x_house_predict = linear_model.predict(x_house)[0]
- print(f" 刘先生的房子为1200平方英尺、3个卧室、1层、40年房龄,预计可售价为: ${x_house_predict*1000:0.2f}")
运行以上代码,结果如下:
刘先生的房子为1200平方英尺、3个卧室、1层、40年房龄,预计可售价为: $318709.09
(1)基于Scikit-learn建立线性回归模型不需要对特征进行归一化处理。
(2)Scikit-learn方法计算的模型参数为精确解,不需迭代,计算速度更快。