【问题标题】:python **kwags Error: function takes 6 positional arguments but 8 were givenpython **kwags 错误:函数接受 6 个位置参数,但给出了 8 个
【发布时间】:2018-11-02 16:38:24
【问题描述】:

当我尝试开发梯度下降时,我发现了一个有趣的问题,即我无法有效地使用 **kwargs。我的功能看起来像

def gradient_descent(g,x,y,alpha,max_its,w,**kwargs):    
    # switch for verbose
    verbose = True
    if 'verbose' in kwargs:
        verbose = kwargs['verbose']

    # determine num train and batch size
    num_train = y.size()[1]
    batch_size = num_train
    if 'batch_size' in kwargs:
        batch_size = kwargs['batch_size']
    ........

错误看起来像:

TypeError                                 Traceback (most recent call last)
<ipython-input-12-f71adb8a241b> in <module>()
  3 w_train = Variable(torch.Tensor(w_init), requires_grad=True)
  4 g = softmax; alpha_choice = 10**(-1); max_its = 100; num_pts = y.size; 
batch_size = 10;
----> 5 weight_hist_2,train_hist_2 = gradient_descent(g,x_train,y_train,alpha_choice,max_its,w_train,num_pts,batch_size,verbose = False)

TypeError: gradient_descent() 接受 6 个位置参数,但给出了 8 个。

开发这个功能有什么我没有注意到的吗?

【问题讨论】:

  • 你能显示对 gradient_descent 的调用吗?因为这是发生错误的地方。你忘了传递一些参数,而不是 kwargs。

标签: python function machine-learning gradient-descent


【解决方案1】:

您的函数签名与您使用的参数数量不匹配:

gradient_descent(g,x,y,alpha,max_its,w,**kwargs)

有 6 个位置参数 g,x,y,alpha,max_its,w 但是,在您的通话中:

gradient_descent(g,x_train,y_train,alpha_choice,max_its,w_train,num_pts,batch_size,verbose = False)

你给它 8 g,x_train,y_train,alpha_choice,max_its,w_train,num_pts,batch_size

我猜你想使用num_pts 作为batch_size 参数,所以它看起来像这样:

weight_hist_2,train_hist_2 = gradient_descent(
    g,
    x_train,
    y_train,
    alpha_choice,
    max_its,
    w_train,
    batch_size=num_pts,
    verbose = False)

【讨论】:

  • 谢谢!我会试试这个。真的很有帮助!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-25
  • 1970-01-01
  • 2020-12-29
相关资源
最近更新 更多