Torch 使用总结

来源:互联网 发布:淘宝怎么设置客服认证 编辑:程序博客网 时间:2024/06/09 20:20

1、安装torch7

这里写图片描述

2使用torch

th> x=torch.Tensor(3,1,8)                                                                      [0.0000s]th> x(1,.,.) =  0  0  0  0  0  0  0  0(2,.,.) =  0  0  0  0  0  0  0  0(3,.,.) =  0  0  0  0  0  0  0  0[torch.DoubleTensor of size 3x1x8]  #这里第二个维度为1,有特别的用意

2.1 Tensor赋值

th> x[1][1][4]=8                                                                      [0.0000s]th> x(1,.,.) =  0  0  0  8  0  0  0  0(2,.,.) =  0  0  0  0  0  0  0  0(3,.,.) =  0  0  0  0  0  0  0  0   #必须说明torch是从【1】开始计数的

2.2 导入nn模块

require 'nn'  #导入nn模块之后既可用nn#现有矩阵x如下:th> x(1,.,.) =  5  5  5  5  6  5  5  5(2,.,.) =  0  0  9  0  0  0  0  0(3,.,.) =  0  0  0  0  0  0  7  0[torch.DoubleTensor of size 3x1x8]#定义net,加入View层th> net = nn.Sequential()net:add(nn.View(6,-1))   #【3,1,8】--> 【6,-1】  其中-1指的是不进行最后一个维度的设置,由计算机来自己计算,本例中为4 th> output=net:forward(x)                                                                      [0.0001s]th> output 5  5  5  5 6  5  5  5 0  0  9  0 0  0  0  0 0  0  0  0 0  0  7  0[torch.DoubleTensor of size 6x4]  #可以发现,tensor是一个连续地址的向量,View将从向量首地址开始填充新的tensor。#再看transpose的作用,假设有数组th> w[4][2]=1                                                                      [0.0001s]th> w 2  0 0  4 3  0 0  1[torch.DoubleTensor of size 4x2]th> model=nn.Sequential()  #设置网络th> model:add(nn.Transpose({1, 2}))nn.Sequential {  [input -> (1) -> output]  (1): nn.Transpose}th> model:forward(w)  #transpose 就是矩阵的转置 2  0  3  0 0  4  0  1#在添加一层SplitTable,看看作用th> model:add(nn.SplitTable(2, 3))nn.Sequential {  [input -> (1) -> (2) -> output]  (1): nn.Transpose  (2): nn.SplitTable}th> ww=model:forward(w)                                                                      [0.0001s]th> ww{  1 : DoubleTensor - size: 2  2 : DoubleTensor - size: 2  3 : DoubleTensor - size: 2  4 : DoubleTensor - size: 2}                                                                      [0.0001s]th> ww[1] 2 0[torch.DoubleTensor of size 2]                                                                      [0.0001s]th> ww[2] 0 4[torch.DoubleTensor of size 2]                                                                      [0.0001s]th> ww[3] 3 0[torch.DoubleTensor of size 2]
原创粉丝点击