使用 Python 沿列插值二维矩阵

Unk*_*ser 2 python interpolation numpy matrix

我正在尝试将维度为 (5, 3) 的 2D numpy 矩阵插值到沿轴 1(列)维度为 (7, 3) 的矩阵。显然,错误的方法是在原始矩阵之间的任意位置随机插入行,请参见以下示例:

Source:
 [[0, 1, 1]
  [0, 2, 0]
  [0, 3, 1]
  [0, 4, 0]
  [0, 5, 1]]

Target (terrible interpolation -> not wanted!):
 [[0, 1, 1]
  [0, 1.5, 0.5]
  [0, 2, 0]
  [0, 3, 1]
  [0, 3.5, 0.5]
  [0, 4, 0]
  [0, 5, 1]]
Run Code Online (Sandbox Code Playgroud)

正确的方法是考虑每一行并在所有行之间进行插值,以将源矩阵扩展为 (7, 3) 矩阵。我知道 scipy.interpolate.interp1d 或 scipy.interpolate.interp2d 方法,但无法使其与其他 Stack Overflow 帖子或网站一起使用。我希望收到任何类型的提示或技巧。

更新#1:预期值应该等距。

更新#2:我想做的基本上是使用原始矩阵的单独列,将列的长度扩展到 7 并在原始列的值之间进行插值。请参见以下示例:

Source:
 [[0, 1, 1]
  [0, 2, 0]
  [0, 3, 1]
  [0, 4, 0]
  [0, 5, 1]]

Split into 3 separate Columns:
 [0    [1    [1
  0     2     0
  0     3     1
  0     4     0
  0]    5]    1] 

Expand length to 7 and interpolate between them, example for second column:
 [1
  1.66
  2.33
  3
  3.66
  4.33
  5]   
Run Code Online (Sandbox Code Playgroud)

rwp*_*rwp 7

似乎每一列都可以完全独立地处理,但是对于每一列,您基本上需要定义一个“x”坐标,以便您可以拟合一些函数“f(x)”,从中生成输出矩阵。除非矩阵中的行与某些其他数据结构(例如时间戳向量)相关联,否则一组明显的 x 值就是行号:

x = numpy.arange(0, Source.shape[0])
Run Code Online (Sandbox Code Playgroud)

然后您可以构造一个插值函数:

fit = scipy.interpolate.interp1d(x, Source, axis=0)
Run Code Online (Sandbox Code Playgroud)

并用它来构造你的输出矩阵:

Target = fit(numpy.linspace(0, Source.shape[0]-1, 7)
Run Code Online (Sandbox Code Playgroud)

其产生:

array([[ 0.        ,  1.        ,  1.        ],
       [ 0.        ,  1.66666667,  0.33333333],
       [ 0.        ,  2.33333333,  0.33333333],
       [ 0.        ,  3.        ,  1.        ],
       [ 0.        ,  3.66666667,  0.33333333],
       [ 0.        ,  4.33333333,  0.33333333],
       [ 0.        ,  5.        ,  1.        ]])
Run Code Online (Sandbox Code Playgroud)

默认情况下,scipy.interpolate.interp1d 使用分段线性插值。scipy.interpolate中有许多更奇特的选项,基于高阶多项式等。插值本身就是一个大主题,除非矩阵的行具有一些特定的属性(例如,是具有已知频率的信号的常规样本) range),可能没有“真正正确”的插值方式。因此,在某种程度上,插值方案的选择会有些随意。