以下是一元函数线性回归及画图的改进代码:

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()

改进点:

  1. 使用np.random.seed(0)固定随机种子,保证每次运行结果一致。
  2. 使用np.polyfit(x, y, 1)计算斜率和截距,避免手动计算。
  3. 添加图例和标题,使图像更加清晰易懂。
一元函数线性回归及画图代码改进

原文地址: https://www.cveoy.top/t/topic/bu0L 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录