我有一个四维的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更具可读性,这一点更为重要.
归档时间: |
|
查看次数: |
1690 次 |
最近记录: |