目录
1. 简单线性回归
使用回归分析绘制拟合曲线是一种常见的方法,简单线性回归就是其中的一种。简单线性回归可以通过最小二乘法来计算回归系数。以下是一个使用简单线性回归来拟合数据的代码示例:
import numpy as np
import matplotlib.pyplot as plt
x = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
y = np.array([2.5, 4.5, 4.8, 5.5, 6.0, 7.0, 7.8, 8.0, 9.0, 9.5])
# 计算回归系数
slope, intercept = np.polyfit(x, y, 1)
# 绘制拟合曲线
plt.scatter(x, y)
plt.plot(x, slope \* x + intercept, color='red')
plt.show()
在该代码中,np.polyfit函数可以用来计算简单线性回归的回归系数。plot函数用来绘制拟合曲线,scatter函数绘制原始数据点。