简体   繁体   English

numpy:计算中的蒙版元素

[英]Numpy: Masked elements in computation

I have a function to built a polynomial from a given x: [1, x^2,x^3,x^4,...,x^degree] 我有一个从给定的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

Now, I would like to calculate polynom for a given x, but omiting sume values. 现在,我想为给定的x计算多项式,但忽略求和值。

Hence, what this is what I did: 因此,这就是我所做的:

Created X: 创建了X:

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

在此处输入图片说明

I masked away the value with I wanted to omit: 我想忽略掉它的价值:

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

在此处输入图片说明

But when I do the computation: 但是当我进行计算时:

print(build_poly(masked_x,2))

在此处输入图片说明

The masking has disappeeared. 掩饰消失了。 Why ? 为什么呢 I want to have the program omit the masked elements 我想让程序省略被遮罩的元素

Apparently when working with masked arrays one must consistently use the numpy.ma versions of the routines. 显然,使用屏蔽数组时,必须始终使用例程的numpy.ma版本。 Any departure from this, and numpy 'forgets' that masked elements are present. 对此的任何偏离都存在,并且存在蒙版元素的numpy'forgets'。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM