BUILD NEURAL NETWORK

The layers of a neural network can be built by API in namespace oneflow.nn, It provides common Module (such as oneflow.nn.Conv2d, oneflow.nn.ReLU). All Module classes inherit from oneflow.nn.Module, and many simple Module can form more complex Module. In this way, users can easily build and manage complex neural networks.

  1. import oneflow as flow
  2. import oneflow.nn as nn

Define Module class

oneflow.nn provides common Module classes and we can use them easily. Or we can build a neural network by customizing the Module class on the basis. This method consists of three parts:

  • Write a class that inherits from oneflow.nn.Module class
  • Write the method of __init__ class, in which we construct the network structure
  • Write the method of forward class, which calculates on the basis of the input of Module
  1. class NeuralNetwork(nn.Module):
  2. def __init__(self):
  3. super(NeuralNetwork, self).__init__()
  4. self.flatten = nn.Flatten()
  5. self.linear_relu_stack = nn.Sequential(
  6. nn.Linear(28*28, 512),
  7. nn.ReLU(),
  8. nn.Linear(512, 512),
  9. nn.ReLU(),
  10. nn.Linear(512, 10),
  11. nn.ReLU()
  12. )
  13. def forward(self, x):
  14. x = self.flatten(x)
  15. logits = self.linear_relu_stack(x)
  16. return logits
  17. net = NeuralNetwork()
  18. print(net)

The above code will output the structure of the NeuralNetwork network:

  1. NeuralNetwork(
  2. (flatten): Flatten(start_dim=1, end_dim=-1)
  3. (linear_relu_stack): Sequential(
  4. (0): Linear(in_features=784, out_features=512, bias=True)
  5. (1): ReLU()
  6. (2): Linear(in_features=512, out_features=512, bias=True)
  7. (3): ReLU()
  8. (4): Linear(in_features=512, out_features=10, bias=True)
  9. (5): ReLU()
  10. )
  11. )

Then, call net (notice:It is not recommended to explicitly call forward):

  1. X = flow.ones(1, 28, 28)
  2. logits = net(X)
  3. pred_probab = nn.Softmax(dim=1)(logits)
  4. y_pred = pred_probab.argmax(1)
  5. print(f"Predicted class: {y_pred}")

You will get output similar to the following:

  1. Predicted class: tensor([1], dtype=oneflow.int32)

The above process of data input, network calculation and the output of reasoning is shown in the figure below.

todo

flow.nn.functional

In addition to oneflow.nn, oneflow.nn.functional namespace also provides many API. It overlaps with oneflow.nn to some extent. For example, nn.functional.relu and nn.ReLU both can be used for activation in neural network.

The main differences between them are:

  • The API under nn is a class. It needs to be instantiated before being called; The API under nn.functional is a function. It is called directly.
  • The API under nn manages network parameters automatically;But for the function under NN. Functional, we need to define our own parameters and manually pass them in each call.

In fact, most of the Module provided by OneFlow is the result of encapsulating the methods under nn.functional. nn.functional can manage the network more finely.

The following example uses the methods in nn.functional to build a Module FunctionalNeuralNetwork equivalent to the NeuralNetwork class above. Readers can appreciate the similarities and differences between the two:

  1. class FunctionalNeuralNetwork(nn.Module):
  2. def __init__(self):
  3. super(FunctionalNeuralNetwork, self).__init__()
  4. self.weight1 = nn.Parameter(flow.randn(28*28, 512))
  5. self.bias1 = nn.Parameter(flow.randn(512))
  6. self.weight2 = nn.Parameter(flow.randn(512, 512))
  7. self.bias2 = nn.Parameter(flow.randn(512))
  8. self.weight3 = nn.Parameter(flow.randn(512, 10))
  9. self.bias3 = nn.Parameter(flow.randn(10))
  10. def forward(self, x):
  11. x = x.reshape(1, 28*28)
  12. out = flow.matmul(x, self.weight1)
  13. out = out + self.bias1
  14. out = nn.functional.relu(out)
  15. out = flow.matmul(out, self.weight2)
  16. out = out + self.bias2
  17. out = nn.functional.relu(out)
  18. out = flow.matmul(out, self.weight3)
  19. out = out + self.bias3
  20. out = nn.functional.relu(out)
  21. return out
  22. net = FunctionalNeuralNetwork()
  23. X = flow.ones(1, 28, 28)
  24. logits = net(X)
  25. pred_probab = nn.Softmax(dim=1)(logits)
  26. y_pred = pred_probab.argmax(1)
  27. print(f"Predicted class: {y_pred}")

Module container

Comparing the similarities and differences between the NeuralNetwork and FunctionalNeuralNetwork,we can find that nn.Sequential plays an important role in simplifying the code.

nn.Sequential is a special container. Any class inherited from nn.Module can be placed in it.

Its specialty is that when Sequential propagates forward, Sequential automatically “concatenates” the layers contained in the container. Specifically, the output of the previous layer will be automatically transferred as the input of the next layer according to the sequence of Sequential added to each layer until the output of the last layer of the whole Moudle is obtained.

The following is an example of building a network without Sequential (not recommended):

  1. class MyModel(nn.Module):
  2. def __init__(self):
  3. super(MyModel, self).__init__()
  4. self.conv1 = nn.Conv2d(1,20,5)
  5. self.relu1 = nn.ReLU()
  6. self.conv2 = nn.Conv2d(20,64,5)
  7. self.relu2 = nn.ReLU()
  8. def forward(self, x):
  9. out = self.conv1(x)
  10. out = self.relu1(out)
  11. out = self.conv2(out)
  12. out = self.relu2(out)
  13. return out

If sequential is used, it looks like this, which will be more concise.

  1. class MySeqModel(nn.Module):
  2. def __init__(self):
  3. super(MySeqModel, self).__init__()
  4. self.seq = nn.Sequential(
  5. nn.Conv2d(1,20,5),
  6. nn.ReLU(),
  7. nn.Conv2d(20,64,5),
  8. nn.ReLU()
  9. )
  10. def forward(self, x):
  11. return self.seq(x)

Besides Sequential, there are nn.Modulelist and nn.ModuleDict. They can automatically register parameters to the whole network. But their other behavior is similar to Python list and Python dict, which are just simple containers and do not automatically propagate forward. You need manually traverse to complete the calculation of each layer.

Please activate JavaScript for write a comment in LiveRe