Home > database >  How can I pass a positional argument to an optional argument in python functions?
How can I pass a positional argument to an optional argument in python functions?

Time:07-27

I am writing a gradient descent function for linear regression and want to include a default initial guess of parameters as a numpy zero array whose length is determined by the shape of an input 2D array. I tried writing the following

def gradient_descent(X,w0=np.zeros(X.shape[1])):

which does not work, raising an error that X is not defined in the optional argument. Is it possible to pass a positional argument to the optional argument in a python function?

CodePudding user response:

I think you want to contain the logic into the function itself:

def gradient_descent(X, w0=None):
    if w0 == None:
        w0 = np.zeros(X.shape[1])
    #Then continue coding here

Does that make sense? As a whole, you want to specify the parameters when defining the function, but not include logic. As a concept, the logic should primarily be included into the body of the function.

CodePudding user response:

You could do this:

def gradient_descent(X, w0=None):
  if not w0:
    w0 = np.zeros(X.shape[1])
  ...
  • Related