torch的常用模块学习

一、nn模块

nn.Identity()

这个函数建立一个输入模块,什么都不做,通常用在神经网络的输入层。用法如下:

mlp = nn.Identity()
print(mlp:forward(torch.ones(5, 2)))

这个可以用在残差学习中。

如果输入需要有多个保存,也可以使用多个nn.Identity()

mlp = nn.Identity()
nlp = nn.Identity()
print(mlp:forward(torch.ones(5, 2)))

多个输入可以在神经网络搭建中起到很好的作用,相当于一个容器,把输入都保留下来了。

可以看一下LSTM中的例子,因为LSTM是循环网络,需要保存上一次的信息,nn.Identity()能够很好的保留信息。

local inputs = {}
table.insert(inputs, nn.Identity()())   -- network input
table.insert(inputs, nn.Identity()())   -- c at time t-1
table.insert(inputs, nn.Identity()())   -- h at time t-1
local input = inputs[1]
local prev_c = inputs[2]
local prev_h = inputs[3]
th>LSTM = require'LSTM.lua'                                                                                [0.0224s]
th> layer = LSTM.create(3, 2)
                                             [0.0019s]
th> layer:forward({torch.randn(1,3), torch.randn(1,2), torch.randn(1,2)})
{
  1 : DoubleTensor - size: 1x2
  2 : DoubleTensor - size: 1x2
}                                                    
                                             [0.0005s]

 

nn.Squeeze()

可以把输入中的一维的那一层去除。可以直接来看一下官网上的例子:

x=torch.rand(2,1,2,1,2)
> x
(1,1,1,.,.) =
  0.6020  0.8897

(2,1,1,.,.) =
  0.4713  0.2645

(1,1,2,.,.) =
  0.4441  0.9792

(2,1,2,.,.) =
  0.5467  0.8648
[torch.DoubleTensor of dimension 2x1x2x1x2]

其具体形状是这样的:

+-------------------------------+
| +---------------------------+ |
| | +-----------------------+ | |
| | |   0.6020  0.8897      | | |
| | +-----------------------+ | |
| | +-----------------------+ | |
| | |   0.4441  0.9792      | | |
| | +-----------------------+ | |
| +---------------------------+ |
|                               |
| +---------------------------+ |
| | +-----------------------+ | |
| | |   0.4713  0.2645      | | |
| | +-----------------------+ | |
| | +-----------------------+ | |
| | |   0.5467  0.8648      | | |
| | +-----------------------+ | |
| +---------------------------+ |
+-------------------------------+

进行nn.squeeze()操作

> torch.squeeze(x)
(1,.,.) =
  0.6020  0.8897
  0.4441  0.9792

(2,.,.) =
  0.4713  0.2645
  0.5467  0.8648
[torch.DoubleTensor of dimension 2x2x2]

 

+-------------------------------+
|       0.6020  0.8897          |
|       0.4441  0.9792          |
+-------------------------------+
+-------------------------------+
|       0.4713  0.2645          |
|       0.5467  0.8648          |
+-------------------------------+

nn.JoinTable()

这个相当于tensorflow的concat操作,但是个人觉得没有concat的操作好用。整体来说torch的代码都没有tensorflow简洁,但是效率比较高。

module = JoinTable(dimension, nInputDims)
+----------+             +-----------+
| {input1, +-------------> output[1] |
|          |           +-----------+-+
|  input2, +-----------> output[2] |
|          |         +-----------+-+
|  input3} +---------> output[3] |
+----------+         +-----------+

例子如下:

x = torch.randn(5, 1)
y = torch.randn(5, 1)
z = torch.randn(2, 1)

print(nn.JoinTable(1):forward{x, y})
print(nn.JoinTable(2):forward{x, y})
print(nn.JoinTable(1):forward{x, z})

>1.3965
 0.5146
-1.5244
-0.9540
 0.4256
 0.1575
 0.4491
 0.6580
 0.1784
-1.7362
[torch.DoubleTensor of dimension 10x1]

 1.3965  0.1575
 0.5146  0.4491
-1.5244  0.6580
-0.9540  0.1784
 0.4256 -1.7362
[torch.DoubleTensor of dimension 5x2]

 1.3965
 0.5146
-1.5244
-0.9540
 0.4256
-1.2660
 1.0869
[torch.Tensor of dimension 7x1]

nn.gModel()

nngraph(nn) 是一个基于有向无环图的模块,所有的节点建立完后,需要使用nn.gModel()组成一个图。

module=nn.gModule(input,output)

这里的input 和output既可以是元素,也可以是列表。这个函数会生成一个从input到output的图。其中此前的每一个模块后面加上该模块输入,成为这个图中的节点。 
给出一个简单的例子:

x1 = nn.Identity()()
 x2 = nn.Identity()()
 a = nn.CAddTable()({x1, x2})
 m = nn.gModule({x1, x2}, {a})

图示下:

_|__   __|__
|    |  |    |
|____|  |____|
| x1    | x2
 \     /
  \z  /
  _\ /_
 |    |
 |____|
    |a

nn.SpatialConvolution()

module = nn.SpatialConvolution(nInputPlane, nOutputPlane, kW, kH, [dW], [dH], [padW], [padH])
or  cudnn.SpatialConvolution(nInputPlane, nOutputPlane, width, height, [dW = 1], [dH = 1], [padW = 0], [padH = 0],[groups=1])
  • nInputPlane: The number of expected input planes in the image given into forward().
  • nOutputPlane: The number of output planes the convolution layer will produce.
  • kW: The kernel width of the convolution
  • kH: The kernel height of the convolution
  • dW: The step of the convolution in the width dimension. Default is 1.
  • dH: The step of the convolution in the height dimension. Default is 1.
  • padW: The additional zeros added per width to the input planes. Default is 0, a good number is (kW-1)/2.
  • padH: The additional zeros added per height to the input planes. Default is padW, a good number is (kH-1)/2.
`torch.nn` 是 PyTorch 中的一个核心模块,用于搭建神经网络。它提供了各种各样的层(layers)、激活函数(activation functions)、损失函数(loss functions)和优化器(optimizers)等等。 使用 `torch.nn` 模块可以方便地定义和训练神经网络。一般来说,我们需要进行以下步骤: 1. 定义网络结构:使用 `torch.nn.Module` 类创建一个新的神经网络模型。 2. 定义前向传播函数:实现 `forward()` 方法,描述数据流在网络中的传播过程。 3. 定义损失函数:选择适当的损失函数,通常是交叉熵损失(cross-entropy loss)或均方误差(mean squared error)等。 4. 选择优化器:选择合适的优化器,如随机梯度下降(SGD)、Adam 等。 5. 训练网络:使用训练数据对网络进行训练,并在验证集上进行验证和调参。 下面是一个使用 `torch.nn` 模块搭建一个简单的全连接神经网络的示例代码: ```python import torch import torch.nn as nn import torch.optim as optim class Net(nn.Module): def __init__(self, input_size, hidden_size, output_size): super(Net, self).__init__() self.fc1 = nn.Linear(input_size, hidden_size) self.fc2 = nn.Linear(hidden_size, output_size) def forward(self, x): x = torch.relu(self.fc1(x)) x = self.fc2(x) return x net = Net(input_size=10, hidden_size=20, output_size=2) criterion = nn.CrossEntropyLoss() optimizer = optim.SGD(net.parameters(), lr=0.001) inputs = torch.randn(1, 10) labels = torch.LongTensor([0]) for i in range(100): optimizer.zero_grad() outputs = net(inputs) loss = criterion(outputs, labels) loss.backward() optimizer.step() ``` 在这个例子中,我们定义了一个带有一个隐藏层的全连接神经网络。使用了 `nn.Linear` 层来定义网络中的全连接层,使用了 ReLU 激活函数。我们使用交叉熵损失函数(`nn.CrossEntropyLoss()`)和随机梯度下降优化器(`optim.SGD()`)来训练网络。最后,我们使用输入数据 `inputs` 和标签 `labels` 对网络进行了训练。 总之,`torch.nn` 模块是 PyTorch 中非常重要的一个模块,它提供了许多常用的神经网络层和函数,可以帮助我们快速地搭建和训练神经网络。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值