【问题标题】:Numpy: Masked elements in computationNumpy:计算中的屏蔽元素
【发布时间】:2018-04-03 05:07:08
【问题描述】:

我有一个函数可以根据给定的 x 构建多项式:[1, x^2,x^3,x^4,...,x^degree]

def build_poly(x, degree):
    """polynomial basis functions for input data x, for j=0 up to j=degree."""
    D = len(x)
    polyome = np.ones((D, 1))
    for i in range(1, degree+1):
        polyome = np.c_[polyome, x**i]

    return polyome

现在,我想计算给定 x 的多项式,但忽略 sume 值。

因此,这就是我所做的:

创建 X:

x=np.array([[1,2,3],[4,5,6]])])

我用我想省略的方式掩盖了这个值:

masked_x= np.ma.masked_equal(x, 5)
print(masked_x)

但是当我进行计算时:

print(build_poly(masked_x,2))

遮罩消失了。 为什么? 我想让程序省略被屏蔽的元素

【问题讨论】:

  • for 语句之后立即添加print(i,x**i)

标签: python numpy computation


【解决方案1】:

显然,在使用掩码数组时,必须始终使用numpy.ma 版本的例程。任何偏离这一点,numpy 都会“忘记”存在掩蔽元素。

def build_poly(x, degree):
    """polynomial basis functions for input data x, for j=0 up to j=degree."""
    D = len(x)
    polyome = np.ones((D, 1))
    for i in range(1, degree+1):
        polyome = np.ma.concatenate([polyome, np.ma.power(x,i)], axis=1)
    return polyome

【讨论】:

  • 对,关键是使用concatenate的“屏蔽”感知版本。
  • 更不用说ma.power
  • 虽然masked_x**2 对我来说也同样有效。通过__pow__,它委托给np.ma.power
  • 好的,谢谢!!您知道在计算时省略二维数组某些特定元素的另一种方法吗?
  • @hpaulj:我不知道。我主要担心提到这个问题的人不会错过代码中的两个地方都需要注意。
猜你喜欢
  • 2017-12-18
  • 1970-01-01
  • 2021-12-15
  • 1970-01-01
  • 2015-09-29
  • 1970-01-01
  • 2015-10-08
  • 1970-01-01
相关资源
最近更新 更多