随机采样
下面的代码每次从数据里随机采样一个小批量。其中批量大小batch_size
是每个小批量的样本数,num_steps
是每个样本所包含的时间步数。
在随机采样中,每个样本是原始序列上任意截取的一段序列,相邻的两个随机小批量在原始序列上的位置不一定相毗邻。
1 | import torch |
1 | my_seq = list(range(30)) |
X: tensor([[18, 19, 20, 21, 22, 23],
[ 6, 7, 8, 9, 10, 11]])
Y: tensor([[19, 20, 21, 22, 23, 24],
[ 7, 8, 9, 10, 11, 12]])
X: tensor([[12, 13, 14, 15, 16, 17],
[ 0, 1, 2, 3, 4, 5]])
Y: tensor([[13, 14, 15, 16, 17, 18],
[ 1, 2, 3, 4, 5, 6]])
相邻采样
在相邻采样中,相邻的两个随机小批量在原始序列上的位置相毗邻。
1 | def data_iter_consecutive(corpus_indices, batch_size, num_steps, device=None): |
1 | for X, Y in data_iter_consecutive(my_seq, batch_size=2, num_steps=6): |
X: tensor([[ 0, 1, 2, 3, 4, 5],
[15, 16, 17, 18, 19, 20]])
Y: tensor([[ 1, 2, 3, 4, 5, 6],
[16, 17, 18, 19, 20, 21]])
X: tensor([[ 6, 7, 8, 9, 10, 11],
[21, 22, 23, 24, 25, 26]])
Y: tensor([[ 7, 8, 9, 10, 11, 12],
[22, 23, 24, 25, 26, 27]])