第1关:torch.nn.Module

import torch
import torch.nn as nn
from torch.autograd import Variable


#/********** Begin *********/
#声明一个in_features=2,out_features=3的线性模型 l并输出
l = nn.Linear(2, 2)
print(l)
# 变量net由三个l序列构成并输出net
net = nn.Sequential(l, l)
print(net)
print()
print('Congratulation!',end="")

#/********** End *********/

第2关:线性--Linear layers

import torch
import torch.nn as nn
from torch.autograd import Variable

#/********** Begin *********/
# 创建in_features=3, out_features=2线性层变量 linear
linear = nn.Linear(3, 2)
#输出linear
print ("linear: ", linear)
#输出linear的 type 属性
print("type of linear : ", linear.type)
print()
print("Congratulation!", end="")

#/********** End *********/

第3关:非线性--Nonlinearities

import torch
import torch.nn as nn
from torch.autograd import Variable

input = Variable(torch.Tensor([2.3,-1.4,0.54]))

#/********** Begin *********/
#创建 Tanh 模型 m
m = nn.Tanh()
#输出经 m 变化后的 input 值

print(m(input))
print()
print("Congratulation!", end="")
#/********** End *********/

第4关:卷积--Convolution Layers

import torch
import torch.nn as nn
from torch.autograd import Variable

input = Variable(torch.randn(10, 16, 40))

#/********** Begin *********/

#创建一个in_channels=16, out_channels=24, kernel_size=4, stride=3的Conv1d变量conv
conv= nn.Conv1d(16, 24, 4, stride=3)

#对input应用卷积操作并赋值给变量 output
output = conv(input)

#输出 output 的大小,要求输出不换行
print(output.size())

#/********** End *********/

第5关:池化--Pooling Layers

import torch
import torch.nn as nn
from torch.autograd import Variable


x = Variable(torch.randn(10, 3, 28, 28))

#/********** Begin *********/

#创建一个in_channels=3, out_channels=32, kernel_size=(3, 3), stride=1, padding=1, bias=True的Conv2d变量conv

conv=nn.Conv2d(3,32,(3,3),stride=1,padding=1,bias=True)
#创建一个kernel_size=(2, 2), stride=2的MaxPool2d变量pool
pool=nn.MaxPool2d((2,2),stride=2)

#对x应用卷积和最大池化操作并赋值给变量outpout_pool
a=conv(x)
out_pool=pool(a)
#输出 outpout_pool 的大小,要求输出打印不换行
print('Pool output size :  ',end='')
print(out_pool.size())
#/********** End *********/

加油!!!

Logo

有“AI”的1024 = 2048,欢迎大家加入2048 AI社区

更多推荐