资讯

精准传达 • 有效沟通

从品牌网站建设到网络营销策划,从策略到执行的一站式服务

如何在pytorch中使用forward方法-创新互联

这篇文章将为大家详细讲解有关如何在pytorch中使用forward 方法,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。

创新互联建站于2013年创立,是专业互联网技术服务公司,拥有项目网站建设、成都网站设计网站策划,项目实施与项目整合能力。我们以让每一个梦想脱颖而出为使命,1280元西湖做网站,已为上家服务,为西湖各地企业和个人服务,联系电话:18982081108

forward 的使用

class Module(nn.Module):
 def __init__(self):
  super(Module, self).__init__()
  # ......
  
 def forward(self, x):
  # ......
  return x
data = ..... #输入数据
# 实例化一个对象
module = Module()
# 前向传播
module(data) 
# 而不是使用下面的
# module.forward(data)

实际上

module(data)

是等价于

module.forward(data)

forward 使用的解释

等价的原因是因为 python calss 中的__call__和__init__方法.

class A():
 def __call__(self):
  print('i can be called like a function')
 
a = A()
a()

out:

i can be called like a function

__call__里调用其他的函数

class A():
 def __call__(self, param):
  
  print('i can called like a function')
  print('传入参数的类型是:{} 值为: {}'.format(type(param), param))
 
  res = self.forward(param)
  return res
 
 def forward(self, input_):
  print('forward 函数被调用了')
 
  print('in forward, 传入参数类型是:{} 值为: {}'.format( type(input_), input_))
  return input_ 
a = A() 
input_param = a('i')
print("对象a传入的参数是:", input_param)

out:

i can called like a function

传入参数的类型是: 值为: i

forward 函数被调用了

in forward, 传入参数类型是: 值为: i

对象a传入的参数是: i

补充:Pytorch 模型中nn.Model 中的forward() 前向传播不调用 解释

在pytorch 中没有调用模型的forward()前向传播,只实列化后把参数传入。

定义模型

class Module(nn.Module):
 def __init__(self):
  super(Module, self).__init__()
  # ......
 
 def forward(self, x):
  # ......
  return x
data = ..... #输入数据
# 实例化一个对象
module = Module()
# 前向传播 直接把输入传入实列化
module(data) 
#没有使用module.forward(data)

实际上module(data) 等价于module.forward(data)

等价的原因是因为 python calss 中的__call__ 可以让类像函数一样调用

当执行model(x)的时候,底层自动调用forward方法计算结果

class A():
 def __call__(self):
  print('i can be called like a function')
 
a = A()
a()
>>>i can be called like a function

在__call__ 里可调用其它的函数

class A():
 def __call__(self, param):
  
  print('我在__call__中,传入参数',param)
 
  res = self.forward(param)
  return res
 
 def forward(self, x):
  print('我在forward函数中,传入参数类型是值为: ',x)
  return x
 
a = A()
y = a('i')
 >>> 我在__call__中,传入参数 i
 >>>我在forward函数中,传入参数类型是值为: i
print("传入的参数是:", y)
 >>>传入的参数是: i

关于如何在pytorch中使用forward 方法就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。


当前题目:如何在pytorch中使用forward方法-创新互联
标题来源:http://cdkjz.cn/article/hssig.html
多年建站经验

多一份参考,总有益处

联系快上网,免费获得专属《策划方案》及报价

咨询相关问题或预约面谈,可以通过以下方式与我们联系

业务热线:400-028-6601 / 大客户专线   成都:13518219792   座机:028-86922220