joelgrus / data-science-from-scratch

code for Data Science From Scratch book
MIT License
8.71k stars 4.52k forks source link

AssertionError: vectors must be same length #121

Closed wolfieboy09 closed 1 year ago

wolfieboy09 commented 1 year ago

Code:

from scratch.linear_algebra import Vector, dot

def step_function(x: float) -> float:
  return 1.0 if x >= 0 else 0.0

def preceptron_output(weights: Vector, bias: float, x: Vector) -> float:
  """Returns 1 if the preceptron 'fires', 0 if not"""
  calculation = dot(weights, x) + bias
  return step_function(calculation)

and_weights = [2., 2]
and_bias = -3.

assert preceptron_output(and_weights, and_bias, [1, 1]) == 1
assert preceptron_output(and_weights, and_bias, [0, 1]) == 0
assert preceptron_output(and_weights, and_bias, [1, 0]) == 0
assert preceptron_output(and_weights, and_bias, [0, 0]) == 0

or_weights = [2., 2]
or_bias = -1.

assert preceptron_output(or_weights, or_bias, [1, 1]) == 1
assert preceptron_output(or_weights, or_bias, [0, 1]) == 1
assert preceptron_output(or_weights, or_bias, [1, 0]) == 1
assert preceptron_output(or_weights, or_bias, [0, 0]) == 0

not_weights = [-2.]
not_bias = 1.

assert preceptron_output(or_weights, or_bias, [0]) == 1
assert preceptron_output(or_weights, or_bias, [1]) == 0

So I am doing the Neural Networks section, and I am getting the error AssertionError: vectors must be same length

Traceback:

Traceback (most recent call last):
  File "main.py", line 33, in <module>
    assert preceptron_output(or_weights, or_bias, [0]) == 1
  File "main.py", line 10, in preceptron_output
    calculation = dot(weights, x) + bias
  File "/home/runner/Neural-Network/scratch/linear_algebra.py", line 60, in dot
    assert len(v) == len(w), "vectors must be same length"
AssertionError: vectors must be same length

I am doing the exact code form the book (and downloaded the scratch file from this repo) and it does not want to work.

joelgrus commented 1 year ago

those AND and OR perceptrons are supposed to take 2 inputs (and then return the AND or the OR of them). here than means that x should be a "vector" (or list) of length 2.

you seem to be giving it a list of length 1, that's causing your error.

the NOT perceptron takes only a single input, I think maybe you meant to use not_weights and not_bias in your last set of examples.

wolfieboy09 commented 1 year ago

Oh, I did not see that I accidentally put or_weight and or_bias in the file until now. That will fix it