What is the best way to implement 1D-Convolution in python?

Viewed 1416

I am trying to implement 1D-convolution for signals.

It should have the same output as:

ary1 = np.array([1, 1, 2, 2, 1])
ary2 = np.array([1, 1, 1, 3])
conv_ary = np.convolve(ary2, ary1, 'full')

>>>> [1 2 4 8 8 9 7 3]

I came up with this approach:

def convolve_1d(signal, kernel):
    n_sig = signal.size
    n_ker = kernel.size
    n_conv = n_sig - n_ker + 1

    # by a factor of 3.
    rev_kernel = kernel[::-1].copy()
    result = np.zeros(n_conv, dtype=np.double)
    for i in range(n_conv):
        result[i] = np.dot(signal[i: i + n_ker], rev_kernel)
    return result

But my result is [8,8] I might have to zero pad my array instead and change its indexing.

Is there a smoother way to achieve the desired outcome?

1 Answers

Here is a possible solution:

def convolve_1d(signal, kernel):
    kernel = kernel[::-1]
    return [
        np.dot(
            signal[max(0,i):min(i+len(kernel),len(signal))],
            kernel[max(-i,0):len(signal)-i*(len(signal)-len(kernel)<i)],
        )
        for i in range(1-len(kernel),len(signal))
    ]

Here is an example:

>>> convolve_1d([1, 1, 2, 2, 1], [1, 1, 1, 3])
[1, 2, 4, 8, 8, 9, 7, 3]
Related