I am having the issue of multiplying the regularization term!
I don’t know how to solve it?
Anyone can help?
AssertionError: Wrong value. Expected 27, got 270.0. Check the regularization term

I have a similar problem. I also tried it with the code from the solution, the function seems to work since it returns the correct value in the following cells, the problem is just in the test function:

# GRADED FUNCTION: cofi_cost_func
# UNQ_C1
def cofi_cost_func(X, W, b, Y, R, lambda_):
"""
Returns the cost for the content-based filtering
Args:
X (ndarray (num_movies,num_features)): matrix of item features
W (ndarray (num_users,num_features)) : matrix of user parameters
b (ndarray (1, num_users) : vector of user parameters
Y (ndarray (num_movies,num_users) : matrix of user ratings of movies
R (ndarray (num_movies,num_users) : matrix, where R(i, j) = 1 if the i-th movies was rated by the j-th user
lambda_ (float): regularization parameter
Returns:
J (float) : Cost
"""
nm, nu = Y.shape
J = 0
### START CODE HERE ###
for j in range(nu):
w = W[j,:]
b_j = b[0,j]
for i in range(nm):
x = X[i,:]
y = Y[i,j]
r = R[i,j]
J += np.square(r * (np.dot(w,x) + b_j - y ))
J += lambda_* (np.sum(np.square(W)) + np.sum(np.square(X)))
J = J/2
### END CODE HERE ###
return J

# Public tests
from public_tests import *
test_cofi_cost_func(cofi_cost_func)

Wrong value. Expected 27, got 540.0. Check the regularization term

I have the same problem. One thing I’ve noticed as well is, if you comment out the J += lambda_ * (np.sum…) and just run the J += np.square(r *…), the error says that I got zero instead of 27. For some reason, that line of code is not updating J = 0 it seems. That may be where our problem lies, but I don’t know how to fix it.

Put adding the regularization term outside both for loops before you divide J by 2. If you do it like that for each loop you add the full value of the regularization term. In other words, you are adding it multiple times and you have to add it only once at the end of the calculation of J.

The regularization term is outside of the summation over i and j which means that it should be added to the J function after you exit from both for-loops (just before you divide J by 2).

In your code, you added a regularization term inside the for-loop. Therefore you add it multiple times and you should add it only once.