在numpy数组中沿维度的回归

2024-04-25 23:13:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个4维的numpy数组(x,y,z,time),我想在每个x,y,z坐标下,通过时间维做一个numpy.polyfit。例如:

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

我想在不经历所有循环的情况下到达regressions数组。这可能吗?在


Tags: ofinnumpyforlentimenpslice
1条回答
网友
1楼 · 发布于 2024-04-25 23:13:03

调整数据的形状,使每个单独的切片位于二维数组的列上。然后运行polyfit一次。在

A2 = A.reshape(time_len, -1)
regressions = np.polyfit(X, A2, degree)
regressions = regressions.reshape(A.shape)

或者类似的事情。。。我真的不知道你的数据集中所有的维度都对应什么,所以我不确定你到底想要什么形状。但关键是,polyfit的每个单独数据集都应该占据矩阵A2中的一列。在

顺便说一句,如果您对性能感兴趣,那么您应该使用profile模块或类似的工具来评测代码。一般来说,你不能总是通过观察来预测代码的运行速度。你必须运行它。尽管在这种情况下,删除循环也会使代码的可读性提高100倍,这一点更为重要。在

相关问题 更多 >