gpt4 book ai didi

python - python中的加权移动平均线

转载 作者:太空狗 更新时间:2023-10-29 16:57:28 26 4
gpt4 key购买 nike

我以基本上随机的时间间隔对数据进行了采样。我想使用 numpy(或其他 python 包)计算加权移动平均值。我有一个移动平均线的粗略实现,但我无法找到一种执行加权移动平均线的好方法,因此靠近 bin 中心的值的权重大于靠近边缘的值。

在这里,我生成了一些示例数据,然后取了一个移动平均值。如何最轻松地实现加权移动平均线?谢谢!

import numpy as np
import matplotlib.pyplot as plt

#first generate some datapoint for a randomly sampled noisy sinewave
x = np.random.random(1000)*10
noise = np.random.normal(scale=0.3,size=len(x))
y = np.sin(x) + noise

#plot the data
plt.plot(x,y,'ro',alpha=0.3,ms=4,label='data')
plt.xlabel('Time')
plt.ylabel('Intensity')

#define a moving average function
def moving_average(x,y,step_size=.1,bin_size=1):
bin_centers = np.arange(np.min(x),np.max(x)-0.5*step_size,step_size)+0.5*step_size
bin_avg = np.zeros(len(bin_centers))

for index in range(0,len(bin_centers)):
bin_center = bin_centers[index]
items_in_bin = y[(x>(bin_center-bin_size*0.5) ) & (x<(bin_center+bin_size*0.5))]
bin_avg[index] = np.mean(items_in_bin)

return bin_centers,bin_avg

#plot the moving average
bins, average = moving_average(x,y)
plt.plot(bins, average,label='moving average')

plt.show()

输出: Data and moving average

根据 crs17 的建议,在 np.average 函数中使用“weights=”,我想出了加权平均函数,它使用高斯函数对数据进行加权:

def weighted_moving_average(x,y,step_size=0.05,width=1):
bin_centers = np.arange(np.min(x),np.max(x)-0.5*step_size,step_size)+0.5*step_size
bin_avg = np.zeros(len(bin_centers))

#We're going to weight with a Gaussian function
def gaussian(x,amp=1,mean=0,sigma=1):
return amp*np.exp(-(x-mean)**2/(2*sigma**2))

for index in range(0,len(bin_centers)):
bin_center = bin_centers[index]
weights = gaussian(x,mean=bin_center,sigma=width)
bin_avg[index] = np.average(y,weights=weights)

return (bin_centers,bin_avg)

结果看起来不错: Working weighted average using numpy

最佳答案

你可以使用 numpy.average它允许您指定权重:

>>> bin_avg[index] = np.average(items_in_bin, weights=my_weights)

因此,要计算权重,您可以找到 bin 中每个数据点的 x 坐标,并计算它们到 bin 中心的距离。

关于python - python中的加权移动平均线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18517722/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com