WK#2 final code assignment-code passed tests but I keep getting errors with Model function

I am stuck in the place it appears most get stuck at. My code passed all individual tests but when I try to combine all in the model function, I get the below errors:

AssertionError Traceback (most recent call last)
in
1 from public_tests import *
2
----> 3 model_test(model)

~/work/release/W2A2/public_tests.py in model_test(target)
131 assert type(d[‘w’]) == np.ndarray, f"Wrong type for d[‘w’]. {type(d[‘w’])} != np.ndarray"
132 assert d[‘w’].shape == (X.shape[0], 1), f"Wrong shape for d[‘w’]. {d[‘w’].shape} != {(X.shape[0], 1)}"
→ 133 assert np.allclose(d[‘w’], expected_output[‘w’]), f"Wrong values for d[‘w’]. {d[‘w’]} != {expected_output[‘w’]}"
134
135 assert np.allclose(d[‘b’], expected_output[‘b’]), f"Wrong values for d[‘b’]. {d[‘b’]} != {expected_output[‘b’]}"

AssertionError: Wrong values for d[‘w’]. [[0.]

I went through the code and removed all hardcoded items in the args to the subroutines. Please help.

thank you,

James

You can use the File menu to open the public_tests.py file, and read the model_test() function.

That will let you inspect the condition that your code is failing. It’s the line labeled “-> 133” in the error summary.

I think in your error report, you did not display the entire contents of the assert output for the expected ‘w’ values. A screen capture image would be helpful.

The error indicates your code returned all zeros for the weights, instead of the expected values.

That’s what is confusing me. The W printout before the start of the AssertionError is a printout of my w prior to calling predict and that subroutine does not return w. My w prior to the call match what is expected.

What code did you add to print the w and b values? And where did you put that code?

Note that the optimize function returns the w and b values to you as a python dictionary. My guess is that you are using incorrect variable names for that parameters dictionary or perhaps you are not extracting the returned values from the dictionary. Note that w will be all zeros after the call to initialize_with_zeros, so how is it going to get changed later in the scope of the model function?

here is the code I am using for Model:

{moderator edit - solution code removed}

Here is the last output after running above:
(4, 1)
<class ‘numpy.ndarray’>
{‘w’: array([[ 0.08639757],
[-0.08231268],
[-0.11798927],
[ 0.12866053]]), ‘b’: -0.039832360948163205}

AssertionError Traceback (most recent call last)
in
1 from public_tests import *
2
----> 3 model_test(model)

~/work/release/W2A2/public_tests.py in model_test(target)
131 assert type(d[‘w’]) == np.ndarray, f"Wrong type for d[‘w’]. {type(d[‘w’])} != np.ndarray"
132 assert d[‘w’].shape == (X.shape[0], 1), f"Wrong shape for d[‘w’]. {d[‘w’].shape} != {(X.shape[0], 1)}"
→ 133 assert np.allclose(d[‘w’], expected_output[‘w’]), f"Wrong values for d[‘w’]. {d[‘w’]} != {expected_output[‘w’]}"
134
135 assert np.allclose(d[‘b’], expected_output[‘b’]), f"Wrong values for d[‘b’]. {d[‘b’]} != {expected_output[‘b’]}"

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

I just wanted to confirm that the below code is suppose to be in the predict function. Only thing I see changing w in predict and I thought that as a copy that was passed from model and stayed a local variable?

Returns:
Y_prediction – a numpy array (vector) containing all predictions (0/1) for the examples in X
‘’’

m = X.shape[1]
Y_prediction = np.zeros((1, m))
w  = w.reshape(X.shape[0], 1)

# Compute vector "A" predicting the probabilities of a cat being present in the picture
#(≈ 1 line of code)
# A = ...

Hi @JamesW22879 ,

Please check your direct message, and reply.

Hi @JamesW22879 ,

You did not pass the updated ‘w’ and ‘b’ to the predict()function. What you have passed to the predict() function are the values returned from the initialize_with_zeros(). The updated ‘w’ and ‘b’ are stored in the variable params, returned from calling the optimize() function. The variable params is a python dictionary. To access the w and b, you have to do:
w = params[“w”]
b = params[“b”]

I suggest you update your code, then do a clean run:
kernel → restart and clear all output
cell → run all code from start

I thought I tried that by passing params[“w”] but it did not work.

I just tried the below code with nearly the same results.

YOUR CODE STARTS HERE

w, b = initialize_with_zeros(np.shape(X_train)[0])
print(np.shape(w))
print(type(w))
params, grads, costs = optimize(w, b, X_train, Y_train, num_iterations, learning_rate, print_cost)
print(params)
w = params[“w”]
b = params[“b”]
Y_prediction_test = predict(w, b, X_test)
Y_prediction_train = predict(w, b, X_train)
# YOUR CODE ENDS HERE

(4, 1)
<class ‘numpy.ndarray’>
{‘w’: array([[ 0.08639757],
[-0.08231268],
[-0.11798927],
[ 0.12866053]]), ‘b’: -0.039832360948163205}

AssertionError Traceback (most recent call last)
in
1 from public_tests import *
2
----> 3 model_test(model)

~/work/release/W2A2/public_tests.py in model_test(target)
131 assert type(d[‘w’]) == np.ndarray, f"Wrong type for d[‘w’]. {type(d[‘w’])} != np.ndarray"
132 assert d[‘w’].shape == (X.shape[0], 1), f"Wrong shape for d[‘w’]. {d[‘w’].shape} != {(X.shape[0], 1)}"
→ 133 assert np.allclose(d[‘w’], expected_output[‘w’]), f"Wrong values for d[‘w’]. {d[‘w’]} != {expected_output[‘w’]}"
134
135 assert np.allclose(d[‘b’], expected_output[‘b’]), f"Wrong values for d[‘b’]. {d[‘b’]} != {expected_output[‘b’]}"

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

Never mind!!! got it to work once I but in the correct quote symbol!

Thank you for your assistance!!

Hi @JamesW22879 ,

The code you attached on the DM didn’t have the lines extracting w and b. Please check your code carefully.

I got it to work with no errors. I submitted the assignment and received a grade of 83% and the feedback showed the following:

[ValidateApp | INFO] Validating ‘/home/jovyan/work/submitted/courseraLearner/W2A2/Logistic_Regression_with_a_Neural_Network_mindset.ipynb’
[ValidateApp | INFO] Executing notebook with kernel: python3
[ValidateApp | ERROR] Timeout waiting for execute reply (30s).
[ValidateApp | ERROR] Interrupting kernel
[ValidateApp | ERROR] Timeout waiting for execute reply (30s).
[ValidateApp | ERROR] Interrupting kernel
Tests failed on 1 cell(s)! These tests could be hidden. Please check your submission.

The following cell failed:

from public_tests import *

model_test(model)

The error was:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-20-9408a3dffbf6> in <module>
      1 from public_tests import *
      2 
----> 3 model_test(model)

~/work/submitted/courseraLearner/W2A2/public_tests.py in model_test(target)
    123     y_test = np.array([[0, 1, 0]])
    124 
--> 125     d = target(X, Y, x_test, y_test, num_iterations=50, learning_rate=0.01)
    126 
    127     assert type(d['costs']) == list, f"Wrong type for d['costs']. {type(d['...

TypeError: model() missing 1 required positional argument: 'print_cost'

Now when I go back to my code I get the same error. Why did the error only show up after submitting the code? It ran clean prior to that. I made no changed to costs in my code.

This seems a grader (or Coursera) issue. Please try Kernel → Restart & Run all. Let us know the result…

Alright! After reviewing the code, it turns out that the model function was missing some default values. Maybe James deleted it by mistake. See the below figure. Adding print_cost = False to the model function will resolve the issue. It is extremely important not to change the prewritten code.

Have been having issues with this for several days now… on the verge of becoming bald… Seems no matter what I do I just end up with a new error. Please help. here is my current error.ValueError Traceback (most recent call last)
in
1 from public_tests import *
2
----> 3 model_test(model)

~/work/release/W2A2/public_tests.py in model_test(target)
123 y_test = np.array([[0, 1, 0]])
124
→ 125 d = target(X, Y, x_test, y_test, num_iterations=50, learning_rate=0.01)
126
127 assert type(d[‘costs’]) == list, f"Wrong type for d[‘costs’]. {type(d[‘costs’])} != list"

in model(X_train, Y_train, X_test, Y_test, num_iterations, learning_rate, print_cost)
36 # YOUR CODE STARTS HERE
37 w, b = initialize_with_zeros(X_train.shape[0])
—> 38 params, grads, costs = optimize(X_train, Y_train, X_test, Y_test, num_iterations, learning_rate, print_cost=False)
39 Y_prediction_test = predict(w, b, X_test)
40 Y_prediction_train = predict(w, b, X_train)

in optimize(w, b, X, Y, num_iterations, learning_rate, print_cost)
35 # grads, cost = …
36 # YOUR CODE STARTS HERE
—> 37 grads, cost = propagate(w, b, X, Y)
38
39 # YOUR CODE ENDS HERE

in propagate(w, b, X, Y)
31 # cost = …
32 # YOUR CODE STARTS HERE
—> 33 A = sigmoid(np.dot(w.T, X) + b)
34 cost = -( 1 / m) * np.sum(Y * np.log(A) + (1 - Y) * (np.log(1 - A)))
35 # YOUR CODE ENDS HERE

ValueError: operands could not be broadcast together with shapes (7,3) (1,7)

Some things to check in your model() function:

  1. Check if you have the correct parameters and in the correct order in the call to optimize().
  2. Don’t hard-code print_cost to False. Just use the value that’s provided when model() is called.