pytorch __init__、forward和__call__小結

1.介紹

    當我們使用pytorch來構建網絡框架的時候,也會遇到和tensorflow(tensorflow __init__、build 和call小結)類似的情況,即經常會遇到__init__、forward和call這三個互相搭配着使用,那麼它們的主要區別又在哪裏呢?

    1)__init__主要用來做參數初始化用,比如我們要初始化卷積的一些參數,就可以放到這裏面,這點和tf裏面的用法是一樣的

    2)forward是表示一個前向傳播,構建網絡層的先後運算步驟

    3)__call__的功能其實和forward類似,所以很多時候,我們構建網絡的時候,可以用__call__替代forward函數,但它們兩個的區別又在哪裏呢?當網絡構建完之後,調__call__的時候,會去先調forward,即__call__其實是包了一層forward,所以會導致兩者的功能類似。在pytorch在nn.Module中,實現了__call__方法,而在__call__方法中調用了forward函數:https://github.com/pytorch/pytorch/blob/master/torch/nn/modules/module.py

 

2.代碼

import torch
import torch.nn as nn
import torch.nn.functional as F


class Net(nn.Module):
  def __init__(self, in_channels, mid_channels, out_channels):
    super(Net, self).__init__()
    self.conv0 = torch.nn.Sequential(
      torch.nn.Conv2d(in_channels, mid_channels, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1)),
      torch.nn.LeakyReLU())
    self.conv1 = torch.nn.Sequential(
      torch.nn.Conv2d(mid_channels, out_channels * 2, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1)))

  def forward(self, x):
    x = self.conv0(x)
    x = self.conv1(x)
    return x


class Net(nn.Module):
  def __init__(self, in_channels, mid_channels, out_channels):
    super(Net, self).__init__()
    self.conv0 = torch.nn.Sequential(
      torch.nn.Conv2d(in_channels, mid_channels, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1)),
      torch.nn.LeakyReLU())
    self.conv1 = torch.nn.Sequential(
      torch.nn.Conv2d(mid_channels, out_channels * 2, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1)))

  def __call__(self, x):
    x = self.conv0(x)
    x = self.conv1(x)
    return x

 

發佈了137 篇原創文章 · 獲贊 140 · 訪問量 11萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章