Numpy:计算中的屏蔽元素
Numpy: Masked elements in computation
我有一个函数可以根据给定的 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 的多项式,但忽略求和值。
因此,这就是我所做的:
创建 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))
遮罩已消失。 为什么?
我想让程序省略被屏蔽的元素
显然,在使用掩码数组时,必须始终使用例程的 numpy.ma
版本。任何与此的背离,以及存在屏蔽元素的 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
我有一个函数可以根据给定的 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 的多项式,但忽略求和值。
因此,这就是我所做的:
创建 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))
遮罩已消失。 为什么? 我想让程序省略被屏蔽的元素
显然,在使用掩码数组时,必须始终使用例程的 numpy.ma
版本。任何与此的背离,以及存在屏蔽元素的 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