Home > Blockchain >  Numpy: all the input arrays must have same number of dimensions
Numpy: all the input arrays must have same number of dimensions

Time:06-21

To easily calculate the dot product, I am writing a function to append a column with value 1 (concatenate at axis = 1), this is what I did:

def function(a):
    a = np.concatenate((a, np.ones(a.shape[0]), 1), axis=1)
    return a

train = function(train)
test = function(test)

When I run, I get this error:

ValueError: all the input arrays must have same number of dimensions, but the array at index 0 has 3 dimension(s) and the array at index 1 has 1 dimension(s)

I understand what it means, but I don't know how to fix this, can someone help me? Thanks for your help!

CodePudding user response:

You can use a temporary variable to perform the task using Python list operations like append():

import numpy as np

def function(a):
    b = a.tolist()
    for i in range(len(b)):
        b[i].append(1)
    return np.array(b)

train = function(np.array([[0]*4096]*2400))
print(train.shape, train)

Output:

(2400, 4097) 
[[0 0 0 ... 0 0 1]
 [0 0 0 ... 0 0 1]
 [0 0 0 ... 0 0 1]
 ...
 [0 0 0 ... 0 0 1]
 [0 0 0 ... 0 0 1]
 [0 0 0 ... 0 0 1]]

CodePudding user response:

Your just need to change your np.concatenate() function into this:

a = np.concatenate((a, np.ones(a.shape[0]), 1))

You just need to omit the axis = 1, then it will work.

CodePudding user response:

Look at the list you give concatenate:

(a, np.ones(a.shape[0]), 1)

You don't show your a (train or test), but according to the error, that has 3 dimensions - do you understand that.

np.ones(a.shape[0]) makes a 1d array. Do you understand why?

1 when converted to an array np.array(1) is a 0d array.

The 3 terms are supposed to have the same number of dimensions, not 3, 1, and 0! There's also a requirement that the dimensions match (except for the joining axis).

What's the intended shape of the result? We can't help without knowing what you intend. Or why you are using this construct.

edit

What was the purpose of the last 1 in your concatenate argument?

Did you mistype the function, intending instead to make a (n,1) array of ones?

np.concatenate((a, np.ones((a.shape[0], 1)), axis=1)

This would work if a was 2d, since the ones would also be 2d.

  • Related