您的位置:首页 > 编程语言 > Lua

Torch教程(2)-Storage

2017-01-05 15:01 323 查看

Storage

Storage是lua访存的基本方式,类似c语言的数组,除了可以保存定义的数值,还可以直接把文件映射到内存中进行操作。

Storage主要有以下几种类型:

ByteStorage: 无符号char数组

CharStorage: 有符号的char数组

ShortStorage: short类型的数组

IntStorage: int 类型的数组

LongStorage: Long 类型数组

FloatStorage: Float 类型数组

DoubleStorage: Double类型数组。

其中默认为DoubleShorage。可以通过torch.setdefaulttensortype函数设定默认的torch.Storage()类型。

构造函数

torch.TYPEStorage([size [, ptr]]) 设定size的值,直接分配内存,否则返回一个空的storage。构造函数的数值是随机初始化的。

torch.TYPEStorage(table) ,用lua的table进行初始化。 例如

th> x=torch.IntStorage({1,2,3,4})
[0.0001s]
th> x
1
2
3
4
[torch.IntStorage of size 4]

[0.0002s]


torch.TYPEStorage(storage [, offset [, size]]) 使用现有的storage初始化,offset表示起始位置,size表示长度。需要注意的是,这种方式相当于从现有的storage截取一部分数据,但是不存在内存复制,在返回的storage操作会影响到原有的storage。

torch.TYPEStorage(filename [, shared [, size [, sharedMem]]]) 一种直接把文件映射到内存的方式,boolean类型的shared选项,如果为true,文件权限必须是可读可写的,文件和内存中是相同的,即是如果内存中存在变化,那么内存中的变化也会写入到文件中。如果设置为false,文件最起码的权限是可读的,在内存中的变化不会影响到原文件。sharedMem如果设置为true,那么文件通过共享内存的方式打开。

th> x = torch.CharStorage('hello.txt')
[0.0001s]
th> x
104
101
108
108
111
32
105
99
116
10
[torch.CharStorage of size 10]

[0.0003s]
th> x:string()
hello ict

[0.0001s]
th> x:fill(42):string()
**********
[0.0001s]
[***@localhost lua]$ cat hello.txt
hello ict
th> x = torch.CharStorage('hello.txt',ture)
[0.0001s]
th> x:string()
hello ict

[0.0001s]
th> x:fill(42):string()
**********
[0.0002s]
[***@localhost lua]$ cat hello.txt
**********


常用函数

[] 索引,同数组的索引,稍微不同的是下标从1开始。

[self] copy(storage) 复制将一个storage复制到另一个,如果存在类型转换,会损失精度。

[self] fill(value) 用指定value填充storage

[self] resize(size) 调整原storage大小为指定size

[self] string(str) 将ByteStorage,或者CharStorage的转化为字符。

th> x = torch.CharStorage():string("blsh blah")
[0.0001s]
th> print(x)
98
108
115
104
32
98
108
97
104
[torch.CharStorage of size 9]

[0.0003s]
th> x:string()
blsh blah
[0.0001s]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  lua torch 深度学习