Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Array of 1d not matching Matrix Shape

I am getting an error message in my basic numpy code, stating that the shape of my matrix and id array (which I np.dot() together) are not aligned.

I have tried to read the code thoroughly again and again but I still can’t figure it out.

Code:
import numpy as np

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

X = [0.2, 0.1, 0.1, -0.9 ]
weights = [[0.3, 0.4, 0.5],
           [-0.1, 0.9, -0.23],
           [0.05, -0.3, 0.7],
           [0.5, -0.123 , -0.008]]
   

biases = 2   
output = np.dot(weights, X) + biases

print(output)

As you can see, there is a matrix and a 1d array, the matrix’s shape = (3,4) and the 1d array’s shape = (4,)

Here is the error code:

  output = np.dot(weights, X) + biases
  File "<__array_function__ internals>", line 200, in dot
ValueError: shapes (4,3) and (4,) not aligned: 3 (dim 1) != 4 (dim 0)

>Solution :

The matrix is not (3,4) as you say but (4,3), which the error message tells you. Hence, your dimensions are incompatible. You can fix this by swapping the order of your dot product call or transposing weights.

Since you have Python lists, you’ll have to convert them to numpy arrays to perform the transpose. It is best practice to only work with numpy arrays when using numpy.

import numpy as np

X = np.array([0.2, 0.1, 0.1, -0.9])
weights = np.array([[0.3, 0.4, 0.5],
                    [-0.1, 0.9, -0.23],
                    [0.05, -0.3, 0.7],
                    [0.5, -0.123, -0.008]])

biases = 2
output = np.dot(weights.T, X) + biases
print(output)  # [1.605  2.2507 2.1542]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading