Recently, I am preparing for a ship detection competition and learning tensorflow at the same time. But I noticed that the code style of tensorflow is awful. I do not want to waste a lot of time to learn the tensorflow grammar even if I am a big Google fan. So I try to find some alternatives.
After reading a lot of introductions, I make a decision to learn Pytorch and use it as my major tools during my postgraduate period. Pytorch is so awesome.
I have tried to write a ConvAutoEncoder and I will introduce that how to make the autoencoder with Pytorch in this blog.
The first thing that you need to do is import the module:
import torch.nn as nn
The second thing that you should do is define a class like this:
we define every layers of autoencoder in the initialization function. But you should call the initialization function of the superclass at the begining. In this example, I use one conv layer and one pooling layer in the encoder part, one unpooling layer and one deconv layer in the decoder part.
Then, you shoud define the foward function like this:
def forward(self, x):
The forward function is very clear. You can just write it follow the real flow of the data. In this example, x is the input data, output_conv is the output of the convolution encoder. h is the hidden matrix also is the thing that we want to use. output_unpool is the output of the unpooling layer. The unpooling function need the indices parameter so you should set ‘return_indices=True’ as a parameter of the pooling layer initialization and receive the indices with the variable ind.
And then, you should write a main function to istantiate a autoencoder and train it with a loss function.
Pytorch provide a useful module called torchvision, we can use this module to import many datasets such as cifar10, mnist or coco. We use cifar10 as our training datasets. you can use this code to import the datasets:
transform = transforms.Compose(
train_loader is a loader which can unpack the image and label from the cifar dataset.
I use L1loss as my loss function:
loss_func = nn.L1Loss()
optim module can make a auto optimizer to update the weight, bias or any parameters in your network.
The last thing that you should is write a interation to train your network:
for epoch in range(2):
you can call the zero_grad function to clear your optimizer, and just send the image to the autoencoder object, it will return the output. Then you can caculate the loss and call the backward function to update the weight and bias.
If you want to train your network on GPU, just call the cuda() function after the net object and the input object.
Now, run the code and you will get the loss output in the console.
If anything wrong, PLEASE tell me by e-mail or leave a message on this page.
import torch.nn as nn