gpt4 book ai didi

python - 使用 Python 沿列插入二维矩阵

转载 作者:行者123 更新时间:2023-12-01 22:10:16 25 4
gpt4 key购买 nike

我正在尝试将维度为 (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]]

正确的方法是考虑每一行并在所有行之间进行插值以将源矩阵扩展为 (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]

最佳答案

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

x = numpy.arange(0, Source.shape[0])

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

fit = scipy.interpolate.interp1d(x, Source, axis=0)

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

Target = fit(numpy.linspace(0, Source.shape[0]-1, 7)

产生:

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. ]])

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

关于python - 使用 Python 沿列插入二维矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48356593/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com