沿numpy数组中的维度回归

ajw*_*ood 7 python numpy

我有一个四维的numpy数组(x,y,z,时间),并希望numpy.polyfit在每个x,y,z坐标的时间维度上做一个.例如:

import numpy as np
n = 10       # size of my x,y,z dimensions
degree = 2   # degree of my polyfit
time_len = 5 # number of time samples

# Make some data
A = np.random.rand(n*n*n*time_len).reshape(n,n,n,time_len)

# An x vector to regress through evenly spaced samples
X = np.arange( time_len )

# A placeholder for the regressions
regressions = np.zeros(n*n*n*(degree+1)).reshape(n,n,n,degree+1)

# Loop over each index in the array (slow!)
for row in range(A.shape[0] ) :
    for col in range(A.shape[1] ) :
        for slice in range(A.shape[2] ):
            fit = np.polyfit( X, A[row,col,slice,:], degree )
            regressions[row,col,slice] = fit
Run Code Online (Sandbox Code Playgroud)

我想进入regressions数组而不必经历所有的循环.这可能吗?

cxr*_*ers 10

重塑数据,使每个切片位于2d数组的列上.然后运行一次polyfit.

A2 = A.reshape(time_len, -1)
regressions = np.polyfit(X, A2, degree)
regressions = regressions.reshape(A.shape)
Run Code Online (Sandbox Code Playgroud)

或类似的东西...我真的不明白你的数据集中所有尺寸对应的东西,所以我不确定你想要的形状.但重点是,每个单独的数据集polyfit应该占据矩阵中的一列A2.

顺便说一句,如果您对性能感兴趣,那么您应该使用配置文件模块或类似的东西来分析您的代码.一般来说,您无法始终通过观察代码来预测代码的运行速度.你必须运行它.虽然在这种情况下删除循环也会使您的代码100x更具可读性,这一点更为重要.

  • +1这是一个比使用`apply_along_axis`,`vectorize`或`apply_over_axes`更好的解决方案,因为它实际上在C代码级别矢量化操作 (2认同)
  • 这非常有效.事实证明我需要'A2 = ATreshape(time_len,-1)`和`regressions = regressions.T.reshape((n,n,n,degree + 1)) (2认同)