1

I am trying to use the astropy module to smooth my data. As a 1D example I have tried the following code:

import numpy as np
from astropy import convolution as conv
var1=np.arange(10)
kernel=np.asarray([-1,1,0])
conv.convolve(var1,kernel)

This returns in my case: array([ nan, nan, nan, nan, nan, nan, nan, nan, nan, nan])

I assumed that it should return array([0,1,1,1,1,1,1,1,1,1]). I have tried using for var1 datatypes uint8, int8 and float32. I have also tried using convolve_fft, with the same result.

I am familiar with the convolution filter of scipy but I want to use astropy for when NaN values are actually present in my data, so as to smooth them over.

4

2 回答 2

3

您的内核总和为零,因此astropy会发出警告

RuntimeWarning: invalid value encountered in true_divide kernel_internal /= kernel_sum

最终导致所有nans.

于 2015-07-01T09:52:55.573 回答
0

正如已经指出的那样,这是因为您的内核的总和为零:

>>> import numpy as np
>>> np.sum(kernel)  # kernel = np.asarray([-1,1,0])
0

kernel如果不规范化但astropy.convolution.convolve总是规范化内核以插入NaN数组中的值(因为 astropy 1.3 也被屏蔽)并将结果再次乘以原始内核的总和,这本身不会成为问题(除非你明确使用normalize_kernel=True)。


即使您已经说过您熟悉它,您也可以始终使用scipy.ndimage.convolve

>>> from scipy.ndimage import convolve

>>> convolve(var1, kernel[::-1])  # var1=np.arange(10)
array([0, 1, 1, 1, 1, 1, 1, 1, 1, 1])

并自己进行插值和卷积以及NaN位置!(不是很好,但是对于零和、不对称和混合签名的内核,你不能正确地进行卷积)。

[::-1]但是,在使用时,您需要反转(因此是)内核。

在您的情况下,您也可以简单地使用numpy.diff(删除前导零):

>>> np.diff(var1)
array([1, 1, 1, 1, 1, 1, 1, 1, 1])
于 2016-12-27T16:13:16.453 回答