Torch 笔记:神经网络(Neural Networks)

1. Sequential

require ‘nn’;

mlp = nn.Sequential()
mlp:add(nn.Linear(10, 25)) -- Linear module (10 inputs, 25 hidden units)
mlp:add(nn.Tanh())         -- apply hyperbolic tangent transfer function on each hidden units
mlp:add(nn.Linear(25, 1))  -- Linear module (25 inputs, 1 output)

> mlp
nn.Sequential {
  [input -> (1) -> (2) -> (3) -> output]
  (1): nn.Linear(10 -> 25)
  (2): nn.Tanh
  (3): nn.Linear(25 -> 1)
}

> print(mlp:forward(torch.randn(10)))
-0.1815
[torch.Tensor of dimension 1]

图片名称

插入网络层

model = nn.Sequential()
model:add(nn.Linear(10, 20))
model:add(nn.Linear(20, 30))
model:insert(nn.Linear(20, 20), 2)

> model
nn.Sequential {
  [input -> (1) -> (2) -> (3) -> output]
  (1): nn.Linear(10 -> 20)
  (2): nn.Linear(20 -> 20)      -- The inserted layer
  (3): nn.Linear(20 -> 30)
}

删除网络层

model = nn.Sequential()
model:add(nn.Linear(10, 20))
model:add(nn.Linear(20, 20))
model:add(nn.Linear(20, 30))
model:remove(2)
> model
nn.Sequential {
  [input -> (1) -> (2) -> output]
  (1): nn.Linear(10 -> 20)
  (2): nn.Linear(20 -> 30)
}

2. Parallel

module = Parallel( inputDimension, outputDimension )

mlp = nn.Parallel(2,1);   -- Parallel container will associate a module to each slice of dimension 2
                           -- (column space), and concatenate the outputs over the 1st dimension.

mlp:add(nn.Linear(10,3)); -- Linear module (input 10, output 3), applied on 1st slice of dimension 2
mlp:add(nn.Linear(10,2))  -- Linear module (input 10, output 2), applied on 2nd slice of dimension 2

                                  -- After going through the Linear module the outputs are
                                  -- concatenated along the unique dimension, to form 1D Tensor
> mlp:forward(torch.randn(10,2)) -- of size 5.
-0.5300
-1.1015
 0.7764
 0.2819
-0.6026
[torch.Tensor of dimension 5]

图片名称

3. Concat

module = nn.Concat( dim )

mlp = nn.Concat(1);
mlp:add(nn.Linear(5,3))
mlp:add(nn.Linear(5,7))

> print(mlp:forward(torch.randn(5)))
 0.7486
 0.1349
 0.7924
-0.0371
-0.4794
 0.3044
-0.0835
-0.7928
 0.7856
-0.1815
[torch.Tensor of dimension 10]

图片名称

4. Convolutional Neural Network

net = nn.Sequential()
net:add(nn.SpatialConvolution(1, 6, 5, 5)) -- 1 input image channel, 6 output channels, 5x5 convolution kernel
net:add(nn.ReLU())                       -- non-linearity 
net:add(nn.SpatialMaxPooling(2,2,2,2))     -- A max-pooling operation that looks at 2x2 windows and finds the max.
net:add(nn.SpatialConvolution(6, 16, 5, 5))
net:add(nn.ReLU())                       -- non-linearity 
net:add(nn.SpatialMaxPooling(2,2,2,2))
net:add(nn.View(16*5*5))                    -- reshapes from a 3D tensor of 16x5x5 into 1D tensor of 16*5*5
net:add(nn.Linear(16*5*5, 120))             -- fully connected layer (matrix multiplication between input and weights)
net:add(nn.ReLU())                       -- non-linearity 
net:add(nn.Linear(120, 84))
net:add(nn.ReLU())                       -- non-linearity 
net:add(nn.Linear(84, 10))                   -- 10 is the number of outputs of the network (in this case, 10 digits)
net:add(nn.LogSoftMax())                     -- converts the output to a log-probability. Useful for classification problems

print('Lenet5\n' .. net:__tostring());

5. Training

Loss Function(Criterion)

  • 对于回归或二分类问题,可采用Mean Squared Error loss(MSE) :
criterion = nn.MSECriterion()
  • 对于多分类问题或输出层为 Log-Softmax 的网络,可采用Negative Log-likelihood :
criterion = nn.ClassNLLCriterion() 

Stochastic Gradient Descent

trainer = nn.StochasticGradient(mlp, criterion)
trainer.learningRate = 0.001
trainer.maxIteration = 5
trainer:train(trainset)

数据集有两点要求:首先dataset[index]返回第Index个数据;其次就是dataset:size()函数返回整个数据集的example的个数。

以上为一种简单的训练方式,更多的模型优化方式可参考Optimization package

参考资料

### 关于神经网络的学习资料 #### 1. 基础概念与入门教程 神经网络是一种模拟人类大脑工作方式的计算模型,它通过一系列互连的人工神经元来实现复杂的模式识别和决策制定[^1]。对于初学者来说,《神经网络从入门到精通》是一个很好的起点,涵盖了从基础知识到实际应用的内容。 为了更好地理解和实践神经网络的概念,可以参考 MATLAB 工具箱的相关书籍,例如《MATLAB语言常用算法程序集》,该书提供了丰富的代码示例以及详细的解释。 #### 2. 高级主题与多层神经网络 多层人工神经网络由输入层、输出层和若干隐藏层组成,其中每一层中的神经元与其他层中的神经元相连[^2]。这种结构允许网络捕捉更深层次的数据特征,从而提高预测性能。如果希望进一步了解深度学习的基础理论和技术细节,则可查阅《深度学习》等相关教材。 #### 3. 图神经网络及其应用 图神经网络(Graph Neural Networks, GNNs)扩展了传统神经网络的能力范围至非欧几里得空间内的数据形式——即图形化表达的信息单元之间存在关系的情况之下运作良好[^3]。针对这一领域感兴趣的读者建议阅读斯坦福大学开设的CS224W课程材料或者参与在线互动实验项目以获得直观感受;另外,“图Transformer”的研究方向也为解决某些特定类型的图表征问题提出了新颖思路尽管伴随一定局限性但仍值得探索[^5]。 ```python import torch from torch_geometric.data import Data edge_index = [[0, 1], [1, 0]] x = [[-1], [1]] data = Data(x=torch.tensor(x), edge_index=torch.tensor(edge_index).t().contiguous()) print(data) ``` 上述代码片段展示了如何利用 PyTorch Geometric 库创建简单的图数据对象 `Data` ,这是进行 GNN 实验的第一步。 #### 4. 推荐参考资料汇总 以下是综合整理的一些优质资源列表供您选择适合自己的学习路径: - **通用型指南** - *Neural Network and Deep Learning Notes* - **编程环境支持文档** - *Matlab From Beginner To Master Tutorial Series* - **学术论文与高级课题探讨** - *Introduction to Graph Neural Networks via Examples Using Pytorch Geometrics Library* - *Graph Transformers: A New Perspective on Modeling Relational Structures with Attention Mechanisms* ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值