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
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]