Home > Enterprise >  Upsampling using Numpy
Upsampling using Numpy

Time:10-01

I want to upsample a given 1d array by adding 'k-1' zeros between the elements for a given upsampling factor 'k'.
k=2
A = np.array([1,2,3,4,5])
B = np.insert(A,np.arange(1,len(A)), values=np.zeros(k-1))

The Above code works for k=2.
Output: [1 0 2 0 3 0 4 0 5]

k=3
A = np.array([1,2,3,4,5])
B = np.insert(A,np.arange(1,len(A)), values=np.zeros(k-1))

For k=3, it's throwing me an error.

The output I desire is k-1 i.e., 3-1 = 2 zeros between the elements.

Output: [1,0,0,2,0,0,3,0,0,4,0,0,5]

I want to add k-1 zeros between the elements of the 1d array.

ValueError                                Traceback (most recent call last)
Cell In [98], line 4
      1 k = 3
      3 A = np.array([1,2,3,4,5])
----> 4 B = np.insert(A, np.arange(1,len(A)), values=np.zeros(k-1))
      6 print(k,'\n')
      7 print(A,'\n')

File <__array_function__ internals>:180, in insert(*args, **kwargs)

File c:\Users\Nihar\AppData\Local\Programs\Python\Python310\lib\site-packages\numpy\lib\function_base.py:5325, in insert(arr, obj, values, axis)
   5323 slobj[axis] = indices
   5324 slobj2[axis] = old_mask
-> 5325 new[tuple(slobj)] = values
   5326 new[tuple(slobj2)] = arr
   5328 if wrap:

ValueError: shape mismatch: value array of shape (2,) could not be broadcast to indexing result of shape (4,)```


CodePudding user response:

Would this be what you are looking for?

k=3
A=np.array([1,2,3,4,5])
B=np.insert(A, list(range(1,len(A) 1))*(k-1), 0)

I just duplicate the indexes in the obj array. Plus, no need to build an array of zeros, a single 0 scalar will do for the value argument.

Note that there are certainly better ways than the list to create that index (since it actually build a list). I fail to think of a one-liner for now. But, if that list is big, it might be a good idea to create an iterator for that.

I am not sure (I've never asked myself this question before) if this insert is optimal neither. For example

B=np.zeros((len(A)*k,), dtype=np.int)
B[::k]=A

also does the trick. Which one is better memory wise (I would say this one, but just at first glance, because it doesn't create the obj list), and cpu-wise, not sure.

EDIT: in fact, I've just tried. The second solution is way faster (27 ms vs 1586 ms, for A with 50000 values and k=100). Which is not surprising. It is quite easy to figure out what it does (in C, I mean, in numpy code, not in python): just an allocation, and then a for loop to copy some values. It could hardly be simpler. Whereas insert probably computes shifting and such

CodePudding user response:

A simple and fast method using np.zeros to create B, then assign values from A.

k = 3
A = np.array([1,2,3,4,5])
B = np.zeros(k*len(A)-k 1, dtype=A.dtype)
B[::k] = A
  • Related