Week 2 - Exercise 8 : Assertion error on length of costs

While trying to run the optimize function with num_iterations=2000 as specified, I run into an assertion error about the length of the cost vector. It looks like the cost vector expects 100 entries (as defined in the optimize function initially), but breaks when you override the num_iterations parameter with any value over 100.

AssertionError: Wrong length for d[‘costs’]. 20 != 1

If I go back and run the optimize function with num_iterations=100, then the function doesn’t optimize dw to the right level and I get another assertion error.

AssertionError: Wrong values for d[‘w’]. [[0] [0] [0] [0]] != [[ 0.08639757] [-0.08231268] [-0.11798927] [ 0.12866053]]

This is my code snippet from the assignment Exercise 8

{moderator edit - solution code removed}

Please let me know how anyone was able to move beyond this?

Yes, the bug is that you are “hard-coding” the number of iterations. No matter what value is passed in, your code will always run 2000 iterations. That is a bug.


And you have the same bug with respect to the learning rate and the print flag as well. The high level point here is that defining a function is different than calling a function, right? It does not work to just “copy/paste” the definition of a function where you need to call the function. That does not work for precisely the reason we see here.


Thanks for the help @paulinpaloalto. I cleaned up the code like you suggested and it worked, but I’m running into a new problem now.

It looks like the solution expects the value of costs in the dictionary d to be a list with length of 1
assert len(d[‘costs’]) == 1, f"Wrong length for d[‘costs’]. {len(d[‘costs’])} != 1"

Whereas in the optimize function costs is defined as a list of costs for every 100 iterations
So when I run it for 2000 iterations, I get a list of 20 values.

How am I supposed to reduce this to just one value? Am I misunderstanding something?

But the point of the previous bug is that you’re not supposed to be running 2000 iterations, right? You’re supposed to be running whatever number they actually asked you to run. So how many iterations does the particular test case that is failing actually ask for? If it’s not one of the test cases in the notebook, you can find the code by clicking “File → Open” and then opening the file public_tests.py.

1 Like

Thanks for pointing out the public tests file Paul!!! I actually didn’t see where the function was getting initialized, and so was initializing it myself (incorrectly). Reading the public tests file makes so much more sense :slight_smile: Thanks for your patience.