ValueError: shapes (3,) and (4,) not aligned: 3 (dim 0) != 4

Question:

import numpy as np

inputs = [1, 2, 3, 2.5]
weights = [
    [0.2, 0.8, -0.5, 1.0],
    [0.5 -0.91, 0.26, -0.5],
    [-0.26, -0.27, 0.17, 0.87]]

biases = [2, 3, 0.5]

output = np.dot(weights, inputs) + biases
print(output)

I’m very new to numpy, and wrote a dot product using the following "inputs" vector, "weights" matrix, and "biases" vector. The output gives me a shape error:

ValueError: shapes (3,) and (4,) not aligned: 3 (dim 0) != 4

Asked By: Aidan Pastor

||

Answers:

I found out your problem, it is a common problem of forgetting a comma and "fusing together" array elements, here I added np.array to your code:

import numpy as np

inputs = np.array([1, 2, 3, 2.5])
weights = np.array([
    [0.2, 0.8, -0.5, 1.0],
    [0.5 -0.91, 0.26, -0.5],
    [-0.26, -0.27, 0.17, 0.87]
    ])

biases = [2, 3, 0.5]


output = np.dot(weights, inputs) + biases
print(output)

Now I get the deprecation warning:

VisibleDeprecationWarning: Creating an ndarray from ragged nested sequences (which is a list-or-tuple of lists-or-tuples-or ndarrays with different lengths or shapes) is deprecated. If you meant to do this, you must specify 'dtype=object' when creating the ndarray.
  weights = np.array([

You must add the comma , to separate the items here:

[0.5 -0.91, 0.26, -0.5], ->     [0.5, -0.91, 0.26, -0.5],

Final code:

import numpy as np

inputs = np.array([1, 2, 3, 2.5])
weights = np.array([
    [0.2, 0.8, -0.5, 1.0],
    [0.5, -0.91, 0.26, -0.5],
    [-0.26, -0.27, 0.17, 0.87]
    ])

biases = [2, 3, 0.5]


output = np.dot(weights, inputs) + biases
print(output)
Answered By: Caridorc
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.