'Name Error: X-Train is not defined Although its defined

I am coding for Logistic regression based neural network. After defining all the sub-functions, I made a model in which these functions are called. But its giving Name Error.

   def model(X_train, Y_train, X_test, Y_test, num_iterations = 2000,     learning_rate = 0.5, print_cost = False):
      Arguments:
      X_train -- training set represented by a numpy array of shape (num_px * num_px * 3, m_train)

      return d

#As the model is called after it is defined,
  d = model(train_set_x, train_set_y, test_set_x, test_set_y, num_iterations = 2000, learning_rate = 0.5, print_cost = True)

 #It gives error
 Name Error:  name 'train_set_x' is not defined. Traceback suggests that the error in  statement which calls function.


Solution 1:[1]

Looks like the wrong scope for me? You posted whole thing in a whole snippet, but it looks like you define a function:

def model(X_train, Y_train, X_test, Y_test, num_iterations = 2000,     
          learning_rate = 0.5, print_cost = False):
    X_train, Y_train, X_test, Y_test, classes = load_dataset() 

and then want to use it?

But notice this: you want the model function to get the values from somewhere - parameter list is what you get from the outside world, not what you want to return!

X_model and the rest are only assigned in that function, so calling d = model(X_train, Y_train, X_test, Y_test, num_iterations = 2000, learning_rate = 0.5, print_cost = True) doesn't have X_train, doesn't have Y_train, X_test, Y_test...

Arguments are parsed from left to right, so that's why you get only the first error. But if you do X_train = None before the d=..., then you'll get the same error message about Y_train.

Solution 2:[2]

this worked for me. try running the cell from the beginning to upload the data file

Solution 3:[3]

What is a NameError? A NameError is raised when you try to use a variable or a function name that is not valid.

In the model function, you used variables such as train_set_x, but they weren't predefined.

Simply run the following lines of code to fix this error:(These two lines standardize the data.)

train_set_x = train_set_x_flatten / 255.
test_set_x = test_set_x_flatten / 255.

You can now use train_set_x and other variables in model function.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 h4z3
Solution 2 user13704365
Solution 3 sheida