Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/334.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 不等维上的移动窗口平均数_Python_Numpy - Fatal编程技术网

Python 不等维上的移动窗口平均数

Python 不等维上的移动窗口平均数,python,numpy,Python,Numpy,TL;DR:有没有什么方法可以让我摆脱第二个循环 我有一个二维网格上的时间序列点。为了消除它们位置的快速波动,我在一个帧窗口上平均坐标。现在在我的例子中,这些点有可能覆盖比平常更大的距离。如果某个特定点的移动距离超过cut\u off值,我不希望包含该点的帧 在-循环的第一个中,我遍历所有帧并定义移动窗口。然后计算当前帧与移动窗口中每个帧之间的距离。之后,我只从所有帧中获取那些位置,x和y组件的移动距离都不超过cut\u off。现在,我想从移动窗口的所有这些选定帧计算每个点的平均位置(注意:选

TL;DR:有没有什么方法可以让我摆脱第二个
循环

我有一个二维网格上的时间序列点。为了消除它们位置的快速波动,我在一个帧窗口上平均坐标。现在在我的例子中,这些点有可能覆盖比平常更大的距离。如果某个特定点的移动距离超过
cut\u off
值,我不希望包含该点的帧

-循环的第一个
中,我遍历所有帧并定义移动窗口。然后计算当前帧与移动窗口中每个帧之间的距离。之后,我只从所有帧中获取那些位置,
x
y
组件的移动距离都不超过
cut\u off
。现在,我想从移动窗口的所有这些选定帧计算每个点的平均位置(注意:选定帧的数量可以小于
n\u window
)。这就引出了
-循环的第二个
。在这里,我迭代所有点,并实际从帧中获取位置,其中当前点的移动距离不超过
cut\u off
。从这些选定的帧中,我计算坐标的平均值,并将其用作当前帧的新值

最后的
for
-循环会减慢整个处理过程。我想不出更好的方法来完成这个计算。有什么建议吗

MWE 提出澄清意见

import numpy as np

# Generate a timeseries with 1000 frames, each 
# containing 50 individual points defined by their 
# x and y coordinates
n_frames = 1000
n_points = 50
n_coordinates = 2

timeseries = np.random.randint(-100, 100, [n_frames, n_points, n_coordinates])

# Set window size to 20 frames
n_window = 20

# Distance cut off
cut_off = 60

# Set up empty array to hold results
avg_data_store = np.zeros([n_frames, timeseries.shape[1], 2])

# Iterate over all frames
for frame in np.arange(0, n_frames):
    # Set the frame according to the window size that we're looking at
    t_before = int(frame - (n_window / 2))
    t_after = int(frame + (n_window / 2))

    # If we're trying to access frames below 0, set the lowest one to 0
    if t_before < 0:
        t_before = 0

    # Trying to access frames that are not in the trajectory, set to last frame
    if t_after > n_frames - 1:
        t_after = n_frames - 1

    # Grab x and y coordinates for all points in the corresponding window
    pos_before = timeseries[t_before:frame]
    pos_after = timeseries[frame + 1:t_after + 1]
    pos_now = timeseries[frame]

    # Calculate the distance between the current frame and the windows before/after
    d_before = np.abs(pos_before - pos_now)
    d_after = np.abs(pos_after - pos_now)

    # Grab indices of frames+points, that are below the cut off
    arg_before = np.argwhere(np.all(d_before < cut_off, axis=2))
    arg_after = np.argwhere(np.all(d_after < cut_off, axis=2))

    # Iterate over all points
    for i in range(0, timeseries.shape[1]):
        # Create temp array
        temp_stack = pos_now[i]

        # Grab all frames in which the current point did _not_
        # travel farther than `cut_off`
        all_before = arg_before[arg_before[:, 1] == i][:, 0]
        all_after = arg_after[arg_after[:, 1] == i][:, 0]

        # Grab the corresponding positions for this points in these frames
        all_pos_before = pos_before[all_before, i]
        all_pos_after = pos_after[all_after, i]

        # If we have any frames for that point before / after
        # stack them into the temp array
        if all_pos_before.size > 0:
            temp_stack = np.vstack([all_pos_before, temp_stack])
        if all_pos_after.size > 0:
            temp_stack = np.vstack([temp_stack, all_pos_after])

        # Calculate the moving window average for the selection of frames
        avg_data_store[frame, i] = temp_stack.mean(axis=0)
将numpy导入为np
#生成一个包含1000帧的时间序列,每个帧
#包含由其定义的50个独立点
#x和y坐标
n_帧=1000
n_点=50
n_坐标=2
timeseries=np.random.randint(-100100,[n_帧,n_点,n_坐标])
#将窗口大小设置为20帧
n_窗口=20
#距离截止
截止值=60
#设置空数组以保存结果
avg_data_store=np.zero([n_frames,timeseries.shape[1],2])
#迭代所有帧
对于np.arange中的帧(0,n_帧):
#根据我们正在查看的窗口大小设置框架
t_before=int(帧-(n_窗口/2))
t_after=int(帧+(n_窗口/2))
#如果我们试图访问低于0的帧,请将最低帧设置为0
如果t_小于0:
t_before=0
#尝试访问不在轨迹中的帧,设置为“最后一帧”
如果t_>n_帧-1:
t\u after=n\u帧-1
#获取对应窗口中所有点的x和y坐标
pos_before=timeseries[t_before:frame]
pos_after=timeseries[帧+1:t_after+1]
pos_now=时间序列[帧]
#计算当前帧与前后窗口之间的距离
d_before=np.abs(pos_before-pos_now)
d_after=np.abs(pos_after-pos_now)
#抓取低于截止线的帧+点的索引
arg_before=np.argwhere(np.all(d_before0之前的所有位置:
临时堆栈=np.vstack([所有临时堆栈之前的位置])
如果.size>0后的所有位置:
临时堆栈=np.vstack([临时堆栈,所有位置之后])
#计算帧选择的移动窗口平均值
平均数据存储[帧,i]=温度堆栈平均值(轴=0)

如果您可以分别计算x和y方向的截止距离,可以使用
scipy.ndimage.generic\u过滤器

将numpy导入为np
从scipy.ndimage导入通用过滤器
def_平均值(x,截止值):
是不是太不同了=np.abs(x-x[len(x)/2])>cutoff
返回np.mean(x[~太不一样了])
定义平滑(x,窗长=5,截止=1):
返回通用过滤器(x,_平均值,大小=窗口长度,模式='nearest',额外关键字=dict(截止=截止))
def平滑(arr,窗长=5,截止=1,轴=-1):
返回np。沿轴应用(平滑,轴,arr,窗口长度=窗口长度,截止=截止)
# --------------------------------------------------------------------------------
def_模拟_运动_2d(T,分数_为_跳跃=0.01):
#通过几次“跳跃”产生随机速度
速度=np.random.randn(T,2)
is_jump=np.rand(T)<分数_是_jump
跳跃=10*np.random.randn(T,2)
跳转[~is_jump]=0。
#预先分配位置和动量数组
位置=np.零((T,2))
动量=np.0((T,2))
#初始化第一个位置
位置[0]=np.random.randn(2)
#使用速度向量更新位置:
#通过不直接应用速度来平滑移动
#而是通过跟踪势头
对于范围(2,T)内的ii:
动量[ii]=0.9*动量[ii-1]+0.1*速度[ii-1]
位置[ii]=位置[ii-1]+动量[ii]+跳跃[ii]
#添加一些测量噪声
噪声=np.random.randn(T,2)
位置+=噪声
返回位置
def演示(nframes=1000,npoints=3):
#创建数据
位置=np.数组([\u模拟\u移动\u 2d(nframes)用于范围内的ii(npoints)])
#格式化为(nframes、NPoint、2)
位置=位置。转置([1,0,2])
#光滑的
平滑=平滑(位置,窗口长度=11,截止点=5,轴=1)
#密谋
x、 y=位置。T
xs,ys=平滑的.T
进口matp
import numpy as np
from scipy.ndimage import generic_filter

def _mean(x, cutoff):
    is_too_different = np.abs(x - x[len(x) / 2]) > cutoff
    return np.mean(x[~is_too_different])

def _smooth(x, window_length=5, cutoff=1.):
    return generic_filter(x, _mean, size=window_length, mode='nearest', extra_keywords=dict(cutoff=cutoff))

def smooth(arr, window_length=5, cutoff=1., axis=-1):
    return np.apply_along_axis(_smooth, axis, arr, window_length=window_length, cutoff=cutoff)

# --------------------------------------------------------------------------------

def _simulate_movement_2d(T, fraction_is_jump=0.01):

    # generate random velocities with a few "jumps"
    velocity = np.random.randn(T, 2)
    is_jump = np.random.rand(T) < fraction_is_jump
    jump = 10 * np.random.randn(T, 2)
    jump[~is_jump] = 0.

    # pre-allocate position and momentum arrays
    position = np.zeros((T,2))
    momentum = np.zeros((T,2))

    # initialise the first position
    position[0] = np.random.randn(2)

    # update position using velocity vector:
    # smooth movement by not applying the velocity directly
    # but rather by keeping track of the momentum
    for ii in range(2,T):
        momentum[ii] = 0.9 * momentum[ii-1] + 0.1 * velocity[ii-1]
        position[ii] = position[ii-1] + momentum[ii] + jump[ii]

    # add some measurement noise
    noise = np.random.randn(T,2)
    position += noise
    return position

def demo(nframes=1000, npoints=3):
    # create data
    positions = np.array([_simulate_movement_2d(nframes) for ii in range(npoints)])

    # format to (nframes, npoints, 2)
    position = positions.transpose([1, 0, 2])

    # smooth
    smoothed = smooth(positions, window_length=11, cutoff=5., axis=1)

    # plot
    x, y = positions.T
    xs, ys = smoothed.T

    import matplotlib.pyplot as plt
    fig, ax = plt.subplots(1,1)
    ax.plot(x, y, 'o')
    ax.plot(xs, ys, 'k-', alpha=0.3, lw=2)
    plt.show()

demo()