[英]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.我正在编写用于线性回归的梯度下降 function 并希望将参数的默认初始猜测包含为 numpy 零数组,其长度由输入二维数组的形状确定。 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.这不起作用,引发一个错误,即 X 未在可选参数中定义。 Is it possible to pass a positional argument to the optional argument in a python function?
是否可以将位置参数传递给 python function 中的可选参数?
You could do this:你可以这样做:
def gradient_descent(X, w0=None):
if not w0:
w0 = np.zeros(X.shape[1])
...
I think you want to contain the logic into the function itself:我认为您想将逻辑包含在 function 本身中:
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.
总的来说,定义function时要指定参数,但不包括逻辑。 As a concept, the logic should primarily be included into the body of the function.
作为一个概念,逻辑应该主要包含在 function 的主体中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.