python多元线性回归画图
时间: 2023-10-05 16:04:50 浏览: 375
要使用Python进行线性回归并绘制图形,你可以根据提供的代码进行操作。首先,你需要根据提供的数据点进行线性拟合,并计算出参数w和b的值。你可以使用自行实现的最小二乘法函数或者使用scikit-learn提供的线性回归类完成这一步骤。然后,使用matplotlib库中的scatter函数绘制数据点,并使用plot函数绘制线性回归的拟合直线。最后,调用show函数显示图形。下面是一个示例代码:
```python
import matplotlib.pyplot as plt
import numpy as np
def linear_regression(x, y):
# 计算参数w和b
x_mean = np.mean(x)
y_mean = np.mean(y)
w = np.sum((x - x_mean) * (y - y_mean)) / np.sum((x - x_mean) ** 2)
b = y_mean - w * x_mean
# 绘制数据点和拟合直线
plt.scatter(x, y, c='r')
plt.plot(x, w * x + b, c='b')
plt.xlabel('x')
plt.ylabel('y')
plt.title('Linear Regression')
plt.show()
return w, b
# 使用给定的数据进行线性回归和绘图
x = [5.06, 4.92, 4.67, 4.54, 4.26, 4.07, 4.01, 4.01, 3.66, 3.43, 3.12, 3.02, 2.87, 2.64, 2.48, 2.48, 2.02, 1.95, 1.79, 1.54]
y = [5.79, 6.61, 5.48, 6.11, 6.39, 4.81, 4.16, 5.55, 5.05, 4.34, 3.24, 4.80, 4.01, 3.17, 1.61, 2.62, 2.50, 3.59, 1.49, 2.10]
w, b = linear_regression(x, y)
```
这段代码会根据给定的数据点进行线性回归,并绘制出数据点和线性拟合结果的图形。你可以根据自己的数据进行调整。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
阅读全文