【问题标题】:Normalization: how to avoid zero standard deviation标准化:如何避免零标准偏差
【发布时间】:2020-02-18 22:35:54
【问题描述】:

有以下任务:

按列标准化矩阵。从列中的每个值减去平均值(列中),然后除以标准偏差(列中)。您的输出不应包含 nan (由零除引起)。将 Nans 替换为 1。不要使用 if 和 while/for。

我正在使用 numpy,所以我编写了以下代码:

def normalize(matrix: np.array) -> np.array:
    res = (matrix - np.mean(matrix, axis = 0)) / np.std(matrix, axis = 0, dtype=np.float64)
    return res
matrix = np.array([[1, 4, 4200], [0, 10, 5000], [1, 2, 1000]])
assert np.allclose(
    normalize(matrix),
    np.array([[ 0.7071, -0.39223,  0.46291],
              [-1.4142,  1.37281,  0.92582],
              [ 0.7071, -0.98058, -1.38873]])
)

答案是对的。

但是,我的问题是:如何避免被零除?如果我有一列相似数字,我将得到标准偏差 = 0 和结果中的 Nan 值。我该如何解决?不胜感激!

【问题讨论】:

    标签: python numpy


    【解决方案1】:

    您的任务指定在输出中避免 nan 并将出现的 nan 替换为 1。它没有指定中间结果可能不包含 nan. 一个有效的解决方案是在 @987654325 上使用 numpy.nan_to_num @返回前:

    import numpy as np
    def normalize(matrix: np.array) -> np.array:
        res = (matrix - np.mean(matrix, axis = 0)) / np.std(matrix, axis = 0, dtype=np.float64)
        return np.nan_to_num(res, False, 1.0)
    matrix = np.array([[2, 4, 4200], [2, 10, 5000], [2, 2, 1000]])
    print(normalize(matrix))
    

    产量:

    [[ 1.         -0.39223227  0.46291005]
     [ 1.          1.37281295  0.9258201 ]
     [ 1.         -0.98058068 -1.38873015]]
    

    【讨论】:

      猜你喜欢
      • 2016-07-28
      • 2022-01-23
      • 1970-01-01
      • 2014-05-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-16
      • 2018-05-17
      相关资源
      最近更新 更多