Search code examples
pythonmachine-learninggradient-descent

NameError: name 'x' is not defined for a gradient descent function already defined. self.function() also not working


I had defined a gradient descent function which works perfectly fine and all the parameters are included too. Here is the code for the same below.

def gradient_descent(init_m,init_c,x,t,learning_rate,iterations,error_threshold):
    m=init_m
    c=init_c
    error_values=list()
    mc_values=list()
    for i in range(iterations):
            e=error(m,x,c,t)
            if e<error_threshold:
                    print('Error less than the threshold. Stopping gradient descent')
                    break
        error_values.append(e)
        m,c=update(m,x,c,t,learning_rate)
        mc_values.append((m,c))
    return m,c,error_values,mc_values

But when I move onto the next cell and try to run this function it generates a traceback. I even tried using self.gradient_descent but it didn't work as well. Here is the code below.

init_m=0.9
init_c=0
learning_rate=0.001
iterations=250
error_threshold=0.001
m,c,error_values,mc_values= gradient_descent(init_m,init_c,x,t,learning_rate,iterations,error_threshold)

If someone could provide some inputs, it would be of immense help. I am getting this output.

NameError                                 Traceback (most recent call last)
<ipython-input-18-ea467e4f9ae1> in <module>()
  4 iterations=250
  5 error_threshold=0.001
 ----> 6 m,c,error_values,mc_values= 
  gradient_descent(init_m,init_c,x,t,learning_rate,iterations,error_threshold)

   NameError: name 'x' is not defined

Solution

  • This works when we define the function again in the subsequent cell. The variables were previously defined.