加权平均法拟合曲线代码
时间: 2023-05-26 13:04:30 浏览: 69
以下是使用加权平均法拟合曲线的 Python 代码示例:
```
import numpy as np
import matplotlib.pyplot as plt
# 定义加权平均法拟合曲线的函数
def weighted_average(x, y, weights):
x_bar = np.sum(x * weights) / np.sum(weights)
y_bar = np.sum(y * weights) / np.sum(weights)
dx = x - x_bar
dy = y - y_bar
slope = np.sum(weights * dx * dy) / np.sum(weights * dx ** 2)
intercept = y_bar - slope * x_bar
return slope * x + intercept
# 生成用于拟合的数据
np.random.seed(0)
x = np.linspace(0, 10, 100)
y = 2 * x + 1 + np.random.normal(scale=2, size=100)
# 定义权重数组
weights = np.linspace(0.1, 1, 100)
# 使用加权平均法拟合曲线并绘图
plt.scatter(x, y, alpha=0.5)
for w in weights:
plt.plot(x, weighted_average(x, y, w), color='gray', alpha=0.1)
plt.plot(x, np.poly1d(np.polyfit(x, y, deg=1))(x), 'r--')
plt.show()
```
首先,我们定义了一个函数 `weighted_average`,接受 x、y 和权重数组作为参数,使用加权平均法拟合曲线并返回拟合后的 y 值。
然后,我们生成了用于拟合的数据,其中 y 值包含一些噪声。接着,我们定义了权重数组,使用 for 循环迭代数组中的每个权重值,调用 `weighted_average` 函数获得拟合后的 y 值,并随机调整透明度,绘制多条拟合曲线。
最后,我们使用 `np.polyfit` 函数拟合一条直线,使用红色虚线绘制,展示加权平均法拟合曲线和直线拟合的比较。运行代码可以看到如下图所示的结果:
![加权平均法拟合曲线示例图](https://cdn.jsdelivr.net/gh/Feikaixin/python-for-ml/img/weighted_average.png)