Implementing Cost function

In my implementation of finding the total cost in the week 2 homework, my code is passing the first 4 test cases but not the 5th. When I run the code in Jupyter I get 2.925 instead of 4.525. When I run the same code in PyCharm with which I am more familiar I get 3.9 instead of 4.525.

Any thoughts on what might be the problem with case 5?

Common issues are:

  • mistakes in indentation.
  • mistakes in parenthesis grouping.

I think all my indentations and parenthesis are correct.

{moderator edit: code removed}


GRADED FUNCTION: compute_cost

def compute_cost(x, y, w, b): 
# moderator edit: code removed
    return total_cost

The 2 and m do have an asterisk between them

Please do not post your code on the forum. That’s not allowed by the course community standards.

If a mentor needs to see your code, we’ll ask you to send it via a private message.

1 Like

Note: Please review the equation for the cost calculation - specifically where the “1/(2*m)” factor is applied. It should be outside the summation - yours is inside.

Why does this matter? It is distributive. Whether I choose to apply 1/2m term by term or after the summation should not yield a new answer

You’re probably correct, my first thought was a recursive application of the 1/(2*m) scaling for every iteration, giving a result more like 1/(2*m^2). But on further review, that’s not the case.


The issue with your code is that it redefined the variable x, when you wrote this:
x[i] = ...

I set x[i] = w*x[i] + b, but I’m not sure why this would be the problem.
What I believe my code does is for each value in x, multiplies x by the weight and adds the bias. This becomes the new value of x[i]
Then it takes this value and computes 1/2m cost^2 and adds this to the total.

What is strange is in my own program I get 3.9 and in jyupter notebook I get 2.925.

I don’t see how changing x[i] is effecting my answer because I use this updated value to represent f_wb

You used the x[i] value to compute w*x + b, then you overwrote the original value in x[i].

If you ever need that value back, it’s gone forever.

Try using another local variable name and see if it helps.

I’ll review your notebook if you send it to me via a private message.

1 Like