Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are there any computational efficiency differences between nn.functional() Vs nn.sequential() in PyTorch

The following is a Feed-forward network using the nn.functional() module in PyTorch

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

class newNetwork(nn.Module):
    def __init__(self):
        super().__init__()
        self.fc1 = nn.Linear(784, 128)
        self.fc2 = nn.Linear(128, 64)
        self.fc3 = nn.Linear(64,10)

    def forward(self,x):
        x = F.relu(self.fc1(x))
        x = F.relu(self.fc2(x))
        x = F.softmax(self.fc3(x))
        return x

model = newNetwork()
model

The following is the same Feed-forward using nn.sequential() module to essentially build the same thing. What is the difference between the two and when would i use one instead of the other?

input_size = 784
hidden_sizes = [128, 64]
output_size = 10

Build a feed-forward network

 model = nn.Sequential(nn.Linear(input_size, hidden_sizes[0]),
                      nn.ReLU(),
                      nn.Linear(hidden_sizes[0], hidden_sizes[1]),
                      nn.ReLU(),
                      nn.Linear(hidden_sizes[1], output_size),
                      nn.Softmax(dim=1))
    print(model)
like image 985
ultrasounder Avatar asked Dec 12 '18 14:12

ultrasounder


People also ask

Is nn sequential faster?

nn. Sequential is faster than not using it.

What is the difference between nn ReLU and nn functional ReLU?

F. relu is a function that simply takes an output tensor as an input, converts all values that are less than 0 in that tensor to zero, and spits this out as an output. nn. ReLU does the exact same thing, except that it represents this operation in a different way, requiring us to first initialise the method with nn.

What does nn sequential do in PyTorch?

Secondly, nn. Sequential runs the three layers at once, this is, it takes the input, run layer1, take output1 and feed layer2 with it, take output2 and feed layer3 giving as result output3. So nn. Sequential is a construction which is used when you want to run certain layers sequentially.

What is a sequential model nn?

Basically, the sequential module is a container or we can say that the wrapper class is used to extend the nn modules. The sequential container is added to the constructor otherwise we can use the forward() method to pass the sequential container to the constructor.


1 Answers

There is no difference between the two. The latter is arguably more concise and easier to write and the reason for "objective" versions of pure (ie non-stateful) functions like ReLU and Sigmoid is to allow their use in constructs like nn.Sequential.

like image 104
Jatentaki Avatar answered Sep 22 '22 07:09

Jatentaki