jupyter实现单变量线性回归模型
时间: 2023-11-27 07:20:18 浏览: 46
首先,我们需要导入必要的库和数据集。在这里,我们将使用scikit-learn库中的波士顿房价数据集,该数据集包含房屋价格和其他13个特征。
```python
import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import load_boston
boston = load_boston()
X = boston.data[:, 5] # 使用RM特征(平均房间数)
y = boston.target
```
接下来,我们将用散点图展示X和y之间的关系。
```python
plt.scatter(X, y)
plt.xlabel('Average number of rooms')
plt.ylabel('House Price')
plt.show()
```
![image](https://user-images.githubusercontent.com/57376468/137217661-0b7e16e5-9e5d-4c45-9d81-2aa88d1c7f8d.png)
我们可以看到,随着平均房间数的增加,房价也有所增加。这表明了两个变量之间的一定程度上的线性关系。
现在,我们将使用scikit-learn库来建立线性回归模型。
```python
from sklearn.linear_model import LinearRegression
# 创建线性回归对象
model = LinearRegression()
# 将数据拟合到模型中
model.fit(X.reshape(-1, 1), y)
```
现在我们可以使用模型来进行预测,然后在散点图上绘制线性回归线。
```python
# 预测房价
y_pred = model.predict(X.reshape(-1, 1))
# 绘制散点图和线性回归线
plt.scatter(X, y)
plt.plot(X, y_pred, color='red')
plt.xlabel('Average number of rooms')
plt.ylabel('House Price')
plt.show()
```
![image](https://user-images.githubusercontent.com/57376468/137217772-00c8d7e6-2c0e-4f5a-b0fa-5e5e5c5a5a6c.png)
我们可以看到,线性回归模型拟合得相当好,线性回归线在散点图中间。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)