C1 W3 Unq C6 Index Error

In C1 W3 Logistic regression UNQ C6, I am getting an error as:
“IndexError: invalid index to scalar variable.”

Is there something wrong with my code? I am not able to understand why this is happening.
I am attaching the code snippet here. Please help.


def compute_gradient_reg(X, y, w, b, lambda_ = 1):
Computes the gradient for linear regression

  X : (ndarray Shape (m,n))   variable such as house size 
  y : (ndarray Shape (m,))    actual value 
  w : (ndarray Shape (n,))    values of parameters of the model      
  b : (scalar)                value of parameter of the model  
  lambda_ : (scalar,float)    regularization constant
  dj_db: (scalar)             The gradient of the cost w.r.t. the parameter b. 
  dj_dw: (ndarray Shape (n,)) The gradient of the cost w.r.t. the parameters w. 

m, n = X.shape

dj_db, dj_dw = compute_gradient(X, y, w, b)

### START CODE HERE ###     

{moderator edit: code removed

### END CODE HERE ###         
return dj_db, dj_dw

X_mapped = map_feature(X_train[:, 0], X_train[:, 1])
initial_w = np.random.rand(X_mapped.shape[1]) - 0.5
initial_b = 0.5

lambda_ = 0.5
dj_db, dj_dw = compute_gradient_reg(X_mapped, y_train, initial_w, initial_b, lambda_)

print(f"dj_db: {dj_db}“, )
print(f"First few elements of regularized dj_dw:\n {dj_dw[:4].tolist()}”, )



Hi @vyomrastogi ,

The problem is in the line of code for adding the regularization term to the corresponding element of dj_dw. Indexing to the element is by j, so it should be dj_dw[j] and not dj_dw which is a vector.

hi @Kic ,
Thankyou very much for the prompt response.
That helped me in getting the correct solution.

I’ve deleted the code from your post, since we’re not supposed to share our code on the forum.