python中的加权移动平均 [英] Weighted moving average in python

查看:87
本文介绍了python中的加权移动平均的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

这里我生成了一些样本数据,然后取了移动平均线.我怎样才能最轻松地实现加权移动平均线?谢谢!

将 numpy 导入为 np导入 matplotlib.pyplot 作为 plt#首先为随机采样的噪声正弦波生成一些数据点x = np.random.random(1000)*10噪声 = np.random.normal(scale=0.3,size=len(x))y = np.sin(x) + 噪声#绘制数据plt.plot(x,y,'ro',alpha=0.3,ms=4,label='data')plt.xlabel('时间')plt.ylabel('强度')#定义一个移动平均函数def move_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_sizebin_avg = np.zeros(len(bin_centers))对于范围内的索引(0,len(bin_centers)):bin_center = bin_centers[索引]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)返回 bin_centers,bin_avg#绘制移动平均线箱,平均值=移动平均(x,y)plt.plot(bins,average,label='移动平均')plt.show()

输出:

使用 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_sizebin_avg = np.zeros(len(bin_centers))#我们将用高斯函数加权def gaussian(x,amp=1,mean=0,sigma=1):返回 amp*np.exp(-(x-mean)**2/(2*sigma**2))对于范围内的索引(0,len(bin_centers)):bin_center = bin_centers[索引]权重 = 高斯 (x,mean=bin_center,sigma=width)bin_avg[index] = np.average(y,weights=weights)返回(bin_centers,bin_avg)

结果看起来不错:

解决方案

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

<预><代码>>>>bin_avg[index] = np.average(items_in_bin, weights=my_weights)

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

I have data sampled at essentially random intervals. I would like to compute a weighted moving average using numpy (or other python package). I have a crude implementation of a moving average, but I am having trouble finding a good way to do a weighted moving average, so that the values towards the center of the bin are weighted more than values towards the edges.

Here I generate some sample data and then take a moving average. How can I most easily implement a weighted moving average? Thanks!

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

The output:

Using the advice from crs17 to use "weights=" in the np.average function, I came up weighted average function, which uses a Gaussian function to weight the data:

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)

Results look good:

解决方案

You could use numpy.average which allows you to specify weights:

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

So to calculate the weights you could find the x coordinates of each data point in the bin and calculate their distances to the bin center.

这篇关于python中的加权移动平均的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆