Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/blackberry/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x pytorch中的apply(fn)函数如何处理没有返回语句作为参数的函数?_Python 3.x_Pytorch - Fatal编程技术网

Python 3.x pytorch中的apply(fn)函数如何处理没有返回语句作为参数的函数?

Python 3.x pytorch中的apply(fn)函数如何处理没有返回语句作为参数的函数?,python-3.x,pytorch,Python 3.x,Pytorch,我对以下代码片段有一些疑问: >>> def init_weights(m): print(m) if type(m) == nn.Linear: m.weight.data.fill_(1.0) print(m.weight) >>> net = nn.Sequential(nn.Linear(2, 2), nn.Linear(2, 2)) >>> net.a

我对以下代码片段有一些疑问:

>>> def init_weights(m):
        print(m)
        if type(m) == nn.Linear:
            m.weight.data.fill_(1.0)
            print(m.weight)

>>> net = nn.Sequential(nn.Linear(2, 2), nn.Linear(2, 2))
>>> net.apply(init_weights)
apply()是pytorch.nn包的一部分。您可以在这个包的文档中找到代码。最后的问题: 1.为什么这个代码示例可以工作,尽管当它被指定为apply()时,init_weights()中没有添加参数或括号?
2.当函数init_weights(m)作为函数apply()的参数(不带括号和m)给出时,它的参数m从何而来?

我们在上述文档中找到了您的问题的答案:

fn
递归应用于每个子模块(由返回) 还有我自己。典型用途包括初始化模型的参数 (另见)

  • 为什么这个代码示例可以工作,尽管在init_weights()中没有添加参数或括号,但它被指定为apply()?
    • 在调用
      apply
      之前,不会调用给定的函数
      init_weights
      ,这正是因为没有括号,而是将对
      init_weights
      的引用提供给
      apply
      ,并且只从
      apply
      内部调用
      init_weights
  • 当函数init_weights(m)作为参数提供给函数apply()而不带括号和m时,它的参数m从何而来?
    • 它通过
      apply
      中的每个调用获取其参数,并且,正如文档所述,由于方法调用
      net.apply(…)
      ,它被调用来迭代(在本例中)
      net
      的每个子模块以及
      net
      本身