沿numpy数组中的维度进行回归 [英] Regression along a dimension in a numpy array
问题描述
我有一个4维的numpy数组(x,y,z,time),并希望在每个x,y,z坐标处的时间维度上做一个numpy.polyfit
.例如:
I've got a 4-dimensional numpy array (x,y,z,time) and would like to do a numpy.polyfit
through the time dimension, at each x,y,z coordinate. For example:
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
数组而不必经历所有循环.这可能吗?
I'd like to get to the regressions
array without having to go through all of the looping. Is this possible?
推荐答案
调整数据的形状,使每个单独的切片位于2d数组的一列上.然后运行一次polyfit.
Reshape your data such that each individual slice is on a column of a 2d array. Then run polyfit once.
A2 = A.reshape(time_len, -1)
regressions = np.polyfit(X, A2, degree)
regressions = regressions.reshape(A.shape)
或者类似的东西……我不太了解您的数据集中的所有尺寸对应什么,因此我不确定您想要的形状是什么.但要注意的是,每个polyfit
数据集都应在矩阵A2
中占据一列.
Or something like that ... I don't really understand what all of the dimensions correspond to in your dataset, so I'm not sure exactly what shape you will want. But the point is, each individual dataset for polyfit
should occupy a column in the matrix A2
.
顺便说一句,如果您对性能感兴趣,那么应该使用配置文件模块或类似的东西对代码进行配置.一般而言,您不能总是仅仅通过盯着它来预测代码将以多快的速度运行.您必须运行它.尽管在这种情况下,删除循环也将使您的代码更具可读性100倍,这甚至更为重要.
By the way, if you are interested in performance, then you should profile your code using the profile module or something like that. Generally speaking, you can't always predict how quickly code will run just by eyeballing it. You have to run it. Although in this case removing the loops will also make your code 100x more readable, which is even more important.
这篇关于沿numpy数组中的维度进行回归的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!