Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Numpy Append Matrix to Tensor

I am trying to build a list of matrices using numpy, but when I try to append a matrix to an empty tensor, I get the error:

ValueError: all the input arrays must have same number of dimensions

Concatenate and append both seem to fail. I tried calling:

tensor = np.concatenate((tensor, matrix), axis=0)

and

tensor = np.append(tensor, matrix, axis=0)

but I get the same error either way.

The tensor starts with a size of [0, h, w], and the matrix is of size [h, w]. The matrix is the correct shape in the direction I want to append to, but it won't seem to attach.

like image 910
Shadow0144 Avatar asked Oct 16 '25 08:10

Shadow0144


1 Answers

It seems matrix would representing the incoming ones, while you accumulate those into tensor. So, to solve it, add a new axis with None/np.newaxis as the leading one to matrix and then concatenate with tensor -

np.concatenate((tensor, matrix[None]),axis=0)

If you are accumulating, store it back into tensor.

Or use np.vstack((tensor, matrix[None])).

Sample run -

In [16]: h,w = 3,4
    ...: a = np.random.rand(0,h,w)
    ...: b = np.random.rand(h,w)

In [17]: np.concatenate((a, b[None]),axis=0).shape
Out[17]: (1, 3, 4)
like image 164
Divakar Avatar answered Oct 17 '25 21:10

Divakar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!