[SOLVED] "name 'X' is not defined

I’m having an issue that I cannot troubleshoot. I added the code to compute the cost with logistic regression. Running, the complaint is about the variable X itself, which is passed as an argument to compute_cost. Please see below.
They are both uppercase and with the correct indentation.
I ran all the code prior to this. Any suggestions are appreciated!

# UNQ_C2
# GRADED FUNCTION: compute_cost
def compute_cost(X, y, w, b, *argv):
    Computes the cost over all examples
      X : (ndarray Shape (m,n)) data, m examples by n features
      y : (ndarray Shape (m,))  target value 
      w : (ndarray Shape (n,))  values of parameters of the model      
      b : (scalar)              value of bias parameter of the model
      *argv : unused, for compatibility with regularized version below
      total_cost : (scalar) cost 

m = n = X.shape

total_cost = 0.0

for i in range(m):
    z_i = np.dot(X[i],w) + b
    f_wb_i = sigmoid(z_i)
    total_cost +=  -y[i]*np.log(f_wb_i) - (1-y[i])*np.log(1-f_wb_i)
total_cost = total_cost / m
### END CODE HERE ### 

return total_cost

NameError Traceback (most recent call last)
14 “”"
—> 16 m = n = X.shape
18 ### START CODE HERE ###

NameError: name ‘X’ is not defined

I reformatted your post using the </> tool so that the code formats more normally, but I’m not sure whether that still reflects exactly how it looks in your notebook. If I got it right, then note that you have not indented that line so python does not think it is part of the body of the function compute_cost. Indentation is a key part of the syntax in python: it’s how you define what is in a function or what is in a for loop or if statement.

If my interpretation of indentation is correct, than that would explain the error, since X is a parameter of the function, which makes it a local variable but only in the scope of the function.

Thank you. Indenting the entire code solved the problem.

1 Like