这基本上归结为简单的数学运算并在手电筒手册中查找一些函数。
好吧,我很无聊……
replicate(x,batch_size) 定义在https://github.com/wojzaremba/lstm/blob/master/data.lua
-- Stacks replicated, shifted versions of x_inp
-- into a single matrix of size x_inp:size(1) x batch_size.
local function replicate(x_inp, batch_size)
local s = x_inp:size(1)
local x = torch.zeros(torch.floor(s / batch_size), batch_size)
for i = 1, batch_size do
local start = torch.round((i - 1) * s / batch_size) + 1
local finish = start + x:size(1) - 1
x:sub(1, x:size(1), i, i):copy(x_inp:sub(start, finish))
end
return x
end
此代码使用Torch 框架。
x_inp:size(1) 返回Torch tensor(可能是多维矩阵)x_inp 的维度 1 的大小。
见https://cornebise.com/torch-doc-template/tensor.html#toc_18
所以x_inp:size(1) 为您提供x_inp 中的行数。 x_inp:size(2),会给你列数...
local x = torch.zeros(torch.floor(s / batch_size), batch_size)
创建一个新的用零填充的二维张量并创建一个对它的局部引用,命名为x
行数由s、x_inp 的行数和batch_size 计算得出。因此,对于您的示例输入,结果是floor(11/2) = floor(5.5) = 5。
您的示例中的列数为 2,因为 batch_size 为 2。
火炬。
简单来说x 是 5x2 矩阵
0 0
0 0
0 0
0 0
0 0
以下行将x_inp 的内容复制到x。
for i = 1, batch_size do
local start = torch.round((i - 1) * s / batch_size) + 1
local finish = start + x:size(1) - 1
x:sub(1, x:size(1), i, i):copy(x_inp:sub(start, finish))
end
在第一次运行中,start 计算结果为 1,finish 计算结果为 5,因为 x:size(1) 当然是 x 的行数,即 5。 1+5-1=5
在第二次运行中,start 评估为 6,finish 评估为 10
所以x_inp的前5行(你的第一批)被复制到x的第一列,第二批被复制到x的第二列
x:sub(1, x:size(1), i, i) 是x 的子张量,第 1 行到第 5 行,第 1 到第 1 列,在第二次运行中第 1 到第 5 行,第 2 到第 2 列(在您的示例中)。所以无非就是x的第一列和第二列
见https://cornebise.com/torch-doc-template/tensor.html#toc_42
:copy(x_inp:sub(start, finish))
将x_inp 中的元素复制到x 的列中。
总而言之,您获取一个输入张量,然后将其分成多个批次,这些批次存储在一个张量中,每个批次有一列。
所以x_inp
0
1
2
3
4
5
6
7
8
9
10
和batch_size = 2
x是
0 5
1 6
2 7
3 8
4 9
进一步:
local function testdataset(batch_size)
local x = load_data(ptb_path .. "ptb.test.txt")
x = x:resize(x:size(1), 1):expand(x:size(1), batch_size)
return x
end
是另一个从文件加载一些数据的函数。这个x 与上面的x 无关,只是两者都是张量。
让我们用一个简单的例子:
x 存在
1
2
3
4
和batch_size = 4
x = x:resize(x:size(1), 1):expand(x:size(1), batch_size)
第一个 x 将被调整为 4x1,读取 https://cornebise.com/torch-doc-template/tensor.html#toc_36
然后通过将第一行复制3次将其扩展为4x4。
导致x 成为张量
1 1 1 1
2 2 2 2
3 3 3 3
4 4 4 4
阅读https://cornebise.com/torch-doc-template/tensor.html#toc_49