0

I'm new to numpy.

I learned the difference between rank-1 array and 1-dim vector from Difference between numpy.array shape (R, 1) and (R,)

I'm also told to use vector where possible for machine learning tasks instead of rank1 array. (It's from https://www.coursera.org/learn/neural-networks-deep-learning/lecture/87MUx/a-note-on-python-numpy-vectors at 4:35)

I'm trying to use numpy.convolve and I don't see it takes 1-dim vector.

Is there a way to pass 1-dim vector to numpy.convolve or should I use (N,) shape array?

eugene
  • 39,839
  • 68
  • 255
  • 489

2 Answers2

1

The documentation for numpy.convolve describes the inputs as "one-dimensional arrays."

There is no separate "vector" in NumPy, only a 1D array. A higher-dimensional array where all but the first dimensions are 1 is often usable too.

I think you're at the point where you just need to try it and see. It should work the way you expect.

John Zwinck
  • 239,568
  • 38
  • 324
  • 436
0

The input arrays to numpy.convolve must be one-dimensional, of shape (N,).

To convolve arrays with more than one dimension, use scipy.signal.convolve

from scipy import signal
a = np.random.normal(size=(10, 1))
b = np.random.normal(size=(5, 1))
signal.convolve(a, b)

I would seriously question the wisdom of that advice (does it come from someone who works with Matlab more than with NumPy?) but if you must follow it in NumPy then squeeze() the arrays to remove singleton dimension prior to convolution and then reshape to restore that dimension

a = np.random.normal(size=(10, 1))
b = np.random.normal(size=(5, 1))     
c = np.convolve(a.squeeze(), b.squeeze()).reshape(-1, 1)

It looks like pointless waste of time for NumPy but who knows, maybe the benefits of obeying the Machine Learning Law are worth it.