Pytorch中的forward有哪些功能

其他教程   发布日期:2024年12月02日   浏览次数:191

今天小编给大家分享一下Pytorch中的forward有哪些功能的相关知识点,内容详细,逻辑清晰,相信大部分人都还太了解这方面的知识,所以分享这篇文章给大家参考一下,希望大家阅读完这篇文章后有所收获,下面我们一起来了解一下吧。

forward有什么特殊功能?

第一条:.forward()可以不写

我最开始发现forward()的与众不同之处就是在此,首先举个例子:

  1. import torch.nn as nn
  2. class test(nn.Module):
  3. def __init__(self, input):
  4. super(test,self).__init__()
  5. self.input = input
  6. def forward(self,x):
  7. return self.input * x
  8. T = test(8)
  9. print(T(6))
  10. # print(T.forward(6))
  11. --------------------------运行结果-------------------------
  12. D:UsersLenovoanaconda3python.exe C:/Users/Lenovo/Desktop/DL/pythonProject/tt.py
  13. 48
  14. Process finished with exit code 0

可以发现,T(6)是可以输出的!而且

  1. 不用指定,默认了调用forward方法
。当然如果非要写上.forward()这也是可以正常运行的,和不写是一样的。

如果不调用Pytorch(正常的Python语法规则),这样肯定会报错的

  1. # import torch.nn as nn #不再调用torch
  2. class test():
  3. def __init__(self, input):
  4. self.input = input
  5. def forward(self,x):
  6. return self.input * x
  7. T = test(8)
  8. print(T.forward(6))
  9. print("************************")
  10. print(T(6))
  11. --------------------------运行结果-------------------------
  12. D:UsersLenovoanaconda3python.exe C:/Users/Lenovo/Desktop/DL/pythonProject/tt.py
  13. 48
  14. ************************
  15. Traceback (most recent call last):
  16. File "C:UsersLenovoDesktopDLpythonProject t.py", line 77, in <module>
  17. print(T(6))
  18. TypeError: 'test' object is not callable
  19. Process finished with exit code 1

这里会报:&lsquo;test&rsquo; object is not callable
因为class不能被直接调用,不知道你想调用哪个方法。

第二条:优先运行forward方法

如果在class中再增加一个方法:

  1. import torch.nn as nn
  2. class test(nn.Module):
  3. def __init__(self, input):
  4. super(test,self).__init__()
  5. self.input = input
  6. def byten(self):
  7. return self.input * 10
  8. def forward(self,x):
  9. return self.input * x
  10. T = test(8)
  11. print(T(6))
  12. print(T.byten())
  13. --------------------------运行结果-------------------------
  14. D:UsersLenovoanaconda3python.exe C:/Users/Lenovo/Desktop/DL/pythonProject/tt.py
  15. 48
  16. 80
  17. Process finished with exit code 0

可以见到,在class中有多个method的时候,如果不指定method,forward是会被优先执行的。

以上就是Pytorch中的forward有哪些功能的详细内容,更多关于Pytorch中的forward有哪些功能的资料请关注九品源码其它相关文章!