一元函数线性回归及画图代码改进
以下是一元函数线性回归及画图的改进代码:
import numpy as np
import matplotlib.pyplot as plt
# 生成随机数据
np.random.seed(0)
x = np.random.rand(50)
y = 2*x + 1 + np.random.randn(50)*0.2
# 计算斜率和截距
a, b = np.polyfit(x, y, 1)
# 画出散点图和拟合直线
plt.scatter(x, y)
plt.plot(x, a*x+b, color='red')
# 添加图例和标题
plt.legend(['Fitted line', 'Data points'])
plt.title('Linear Regression')
# 显示图像
plt.show()
改进点:
- 使用
np.random.seed(0)固定随机种子,保证每次运行结果一致。 - 使用
np.polyfit(x, y, 1)计算斜率和截距,避免手动计算。 - 添加图例和标题,使图像更加清晰易懂。
原文地址: https://www.cveoy.top/t/topic/bu0L 著作权归作者所有。请勿转载和采集!