作者:台湾菜文 | 来源:互联网 | 2022-12-06 10:03
我有一个独立变量值的一维数组(x_array
),它与具有多个时间步长()的3D numpy空间数据数组中的时间步长相匹配y_array
.我的实际数据要大得多:300+时间步长和高达3000*3000像素:
import numpy as np
from scipy.stats import linregress
# Independent variable: four time-steps of 1-dimensional data
x_array = np.array([0.5, 0.2, 0.4, 0.4])
# Dependent variable: four time-steps of 3x3 spatial data
y_array = np.array([[[-0.2, -0.2, -0.3],
[-0.3, -0.2, -0.3],
[-0.3, -0.4, -0.4]],
[[-0.2, -0.2, -0.4],
[-0.3, np.nan, -0.3],
[-0.3, -0.3, -0.4]],
[[np.nan, np.nan, -0.3],
[-0.2, -0.3, -0.7],
[-0.3, -0.3, -0.3]],
[[-0.1, -0.3, np.nan],
[-0.2, -0.3, np.nan],
[-0.1, np.nan, np.nan]]])
我想计算每个像素的线性回归,将获得的R平方,P值,截距和斜率为每个xy
像素y_array
,为每个时间步长值x_array
作为我的独立变量.
我可以重新整形以获取表单中的数据以将其输入到np.polyfit
矢量化和快速:
# Reshape so rows = number of time-steps and columns = pixels:
y_array_reshaped = y_array.reshape(len(y_array), -1)
# Do a first-degree polyfit
np.polyfit(x_array, y_array_reshaped, 1)
但是,这会忽略包含任何NaN
值(np.polyfit
不支持NaN
值)的像素,并且不会计算我需要的统计数据(R平方,P值,截距和斜率).
这里的答案用于scipy.stats import linregress
计算我需要的统计数据,并建议NaN
通过屏蔽这些NaN
值来避免问题.但是,这个例子适用于两个1D数组,我无法弄清楚如何对我的情况应用类似的掩码方法,其中每个列y_array_reshaped
将具有不同的NaN
值集.
我的问题:如何NaN
以合理快速的矢量化方式计算包含许多值的大型多维数组(300 x 3000 x 3000)中每个像素的回归统计量?
期望的结果:每个像素的3 x 3回归统计值数组(例如R平方)y_array
,即使该像素包含NaN
时间序列中某个点的值