Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading