python线性回归预测
时间: 2023-07-08 14:06:19 浏览: 94
使用Python进行线性回归预测的步骤如下:
1. 导入必要的库
```python
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error, r2_score
```
2. 读取数据
```python
data = pd.read_csv('data.csv')
x = data.iloc[:, :-1].values
y = data.iloc[:, 1].values
```
3. 拟合模型
```python
regressor = LinearRegression()
regressor.fit(x, y)
```
4. 预测结果
```python
y_pred = regressor.predict(x)
```
5. 可视化结果
```python
plt.scatter(x, y, color='red')
plt.plot(x, y_pred, color='blue')
plt.title('Linear Regression')
plt.xlabel('X')
plt.ylabel('Y')
plt.show()
```
6. 计算评估指标
```python
mse = mean_squared_error(y, y_pred)
r2 = r2_score(y, y_pred)
print('Mean Squared Error:', mse)
print('R2 Score:', r2)
```
完整代码如下:
```python
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error, r2_score
# 读取数据
data = pd.read_csv('data.csv')
x = data.iloc[:, :-1].values
y = data.iloc[:, 1].values
# 拟合模型
regressor = LinearRegression()
regressor.fit(x, y)
# 预测结果
y_pred = regressor.predict(x)
# 可视化结果
plt.scatter(x, y, color='red')
plt.plot(x, y_pred, color='blue')
plt.title('Linear Regression')
plt.xlabel('X')
plt.ylabel('Y')
plt.show()
# 计算评估指标
mse = mean_squared_error(y, y_pred)
r2 = r2_score(y, y_pred)
print('Mean Squared Error:', mse)
print('R2 Score:', r2)
```
其中,`data.csv`是包含数据的CSV文件,格式为:
```
x,y
1,2
2,4
3,5
4,4
5,5
6,7
7,8
8,8
9,10
10,12
```
这里的数据是一个简单的线性数据,可以用来进行线性回归预测。
阅读全文