17. 多元线性回归
多元线性回归
在上一部分,你了解了如何使用 BMI 预测预期寿命。在此例中,BMI 是 预测器 ,也称为自变量。预测器是你将查看的变量,以便对其他变量做出预测,你尝试预测的值称为因变量。在此示例中,预期寿命是因变量。
现在假设我们获得了每人的心率数据。我们可以同时使用 BMI 和心率预测寿命期限吗?
当然可以!正如在上个视频中看到的,我们可以使用多元线性回归进行预测。
如果你要预测的结果取决于多个变量,可以创建一个更复杂的模型来考虑多个变量。只要这些变量与要解决的问题相关,使用更多自变量/预测器变量就有助于做出更好的预测。
如果只有一个预测器,则线性回归模型是一条线,但是如果添加更多的预测器变量,就会增加更多的维度。
如果有一个预测器变量,线条的方程是
y = m x + b
图形可能如下所示:
带有一个预测器变量的线性回归
添加一个预测器变量,变成两个预测器变量后,预测方程是
y = m_1 x_1 + m_2 x_2 + b
要用图形表示,我们需要三维图形,并将线性回归模型表示成一个平面:
带有两个预测器变量的线性回归
你可以使用两个以上的预测器变量,实际上可以使用任意多个,只要有用即可!如果你使用 n 个预测器变量,那么模型可以用以下方程表示:
y = m_{1} x_{1} + m_{2} x_{2} + m_{3} x_{3}+ … +m_{n} x_{n} + b
如果模型有多个预测器变量,则很难用图形呈现,但幸运的是,关于线性回归的所有其他方面都保持不变。我们依然可以通过相同的方式拟合模型并作出预测,我们来试试吧!
编程练习:多元线性回归
在此练习中,你将使用 波士顿房价数据集 。该数据集包含 506 座房子的 13 个特征,均值为 $1000's。你将用一个模型拟合这 13 个特征,以预测房价。
你需要完成以下步骤:
1. 构建线性回归模型
*使用scikit-learn 的
LinearRegression
创建回归模型并将其赋值给
model
。
- 将模型与数据拟合。
2. 使用该模型进行预测
-
预测
sample_house的值。
Start Quiz:
from sklearn.linear_model import LinearRegression
from sklearn.datasets import load_boston
# Load the data from the boston house-prices dataset
boston_data = load_boston()
x = boston_data['data']
y = boston_data['target']
# Make and fit the linear regression model
# TODO: Fit the model and assign it to the model variable
model = None
# Make a prediction using the model
sample_house = [[2.29690000e-01, 0.00000000e+00, 1.05900000e+01, 0.00000000e+00, 4.89000000e-01,
6.32600000e+00, 5.25000000e+01, 4.35490000e+00, 4.00000000e+00, 2.77000000e+02,
1.86000000e+01, 3.94870000e+02, 1.09700000e+01]]
# TODO: Predict housing price for the sample_house
prediction = None
from sklearn.linear_model import LinearRegression
from sklearn.datasets import load_boston
# Load the data from the boston house-prices dataset
boston_data = load_boston()
x = boston_data['data']
y = boston_data['target']
# Make and fit the linear regression model
# TODO: Fit the model and Assign it to the model variable
model = LinearRegression()
model.fit(x, y)
# Make a prediction using the model
sample_house = [[2.29690000e-01, 0.00000000e+00, 1.05900000e+01, 0.00000000e+00, 4.89000000e-01,
6.32600000e+00, 5.25000000e+01, 4.35490000e+00, 4.00000000e+00, 2.77000000e+02,
1.86000000e+01, 3.94870000e+02, 1.09700000e+01]]
# TODO: Predict housing price for the sample_house
prediction = model.predict(sample_house)