簡體   English   中英

沿numpy數組中的維度回歸

[英]Regression along a dimension in a numpy array

我有一個4維的numpy數組(x,y,z,時間),並希望在每個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數組,而不必經歷所有的循環。 這可能嗎?

重塑數據,使每個切片位於2d數組的列上。 然后運行一次polyfit。

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

或類似的東西...我真的不明白你的數據集中所有尺寸對應的東西,所以我不確定你想要的形狀。 但重點是, polyfit每個單獨數據集應占據矩陣A2中的一列。

順便說一句,如果您對性能感興趣,那么您應該使用配置文件模塊或類似的東西來分析您的代碼。 一般來說,您無法始終通過觀察代碼來預測代碼的運行速度。 你必須運行它。 雖然在這種情況下刪除循環也會使您的代碼100x更具可讀性,這一點更為重要。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM