【问题标题】:How to standardize matrix row-wise (axis=1)?如何按行标准化矩阵(轴= 1)?
【发布时间】:2017-12-02 10:00:58
【问题描述】:

对于二维数组,我正在尝试创建一个标准化函数,它应该按行和按列工作。我不确定当使用axis = 1(按行)给出参数时该怎么做。

def standardize(x, axis=None):
if axis == 0:
    return (x - x.mean(axis)) / x.std(axis)
else:
    ?????

我尝试在这部分将axis 更改为axis = 1(x - x.mean(axis)) / x.std(axis)

然后我得到以下错误:

 ValueError: operands could not be broadcast together with shapes (4,3) (4,)

谁能解释一下我还是个初学者该怎么做?

【问题讨论】:

标签: python matrix standardized


【解决方案1】:

您看到错误的原因是您无法计算

x - x.mean(1)

因为

x.shape = (4, 3)
x.mean(1).shape = (4,)  # mean(), sum(), std() etc. remove the dimension they are applied to

但是,如果我们能够以某种方式确保 mean() 保持其应用到的维度,则您可以执行此操作,从而导致

x.mean(1).shape = (4, 1)

(查找NumPy Broadcasting rules)。

因为这是一个常见的问题,NumPy 开发人员引入了一个参数:keepdims=True,您应该在mean()std() 中使用它:

def standardize(x, axis=None):
    return (x - x.mean(axis, keepdims=True)) / x.std(axis, keepdims=True)

【讨论】:

    猜你喜欢
    • 2011-05-31
    • 2021-05-18
    • 1970-01-01
    • 2014-01-22
    • 2016-05-25
    • 1970-01-01
    • 1970-01-01
    • 2015-05-20
    相关资源
    最近更新 更多