【问题标题】:Fill in missing values in 2d matrix using interpolation in numpy/scipy使用 numpy/scipy 中的插值填充 2d 矩阵中的缺失值
【发布时间】:2020-05-02 18:46:56
【问题描述】:

我需要在 2d 矩阵中填写缺失值(以 0 表示)。 我将如何在 numpy/scipy 中完成它? 我找到了scipy.interpolate.interp2d 函数,但我不太明白如何在不修改非零条目的情况下使其仅填充零。

这里是这个函数用于平滑图像https://scipython.com/book/chapter-8-scipy/examples/scipyinterpolateinterp2d/的示例

但这不是我想要的。我只想填写零值。

比如矩阵是

import numpy as np
mat = np.array([[1,2,0,0,4], [1,0,0,0,8], [0,4,2,2,0], [0,0,0,0,8], [1,0,0,0,1]])

mat
array([[1, 2, 0, 0, 4],
       [1, 0, 0, 0, 8],
       [0, 4, 2, 2, 0],
       [0, 0, 0, 0, 8],
       [1, 0, 0, 0, 1]])

在此矩阵中,所有零都必须替换为插值,而原始值应保持不变。 我可以用什么来完成这项任务?

【问题讨论】:

  • 你要填什么?哪些价值观?
  • @rammelmueller 全为零

标签: python numpy scipy interpolation


【解决方案1】:

您必须决定如何填写零。例如,您可以只使用数组中的平均值:

mat[mat == 0] = np.average(mat)
mat
# array([[1, 2, 1, 1, 4],
#        [1, 1, 1, 1, 8],
#        [1, 4, 2, 2, 1],
#        [1, 1, 1, 1, 8],
#        [1, 1, 1, 1, 1]])

或者您可以使用拟合到非零值的某个函数的值 --- scipy.interpolate.interp2d 使用“样条”(想想多项式):

from scipy.interpolate import interp2d

ix = np.where(mat != 0)
f = interp2d(ix[0], ix[1], mat[ix].flatten(), kind='linear')
mat2 = mat.copy()
mat2[mat==0] = f(range(5), range(5)).T[mat==0]
mat2
# array([[ 1,  2,  3,  4,  4],
#        [ 1,  1,  1,  1,  8],
#        [ 4,  4,  2,  2, 11],
#        [ 4,  3,  2,  1,  8],
#        [ 1,  0,  0,  0,  1]])

虽然我认为您会发现这种方法非常挑剔,尤其是对于这么小的数据集。

你也可以看看其他imputation approaches,比如最近的邻居等等。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-07-16
    • 1970-01-01
    • 1970-01-01
    • 2018-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-26
    相关资源
    最近更新 更多