感谢已有的一些博客,但是感觉总结的不到位,于是自己写了一下:
https://www.cnblogs.com/sbj123456789/p/9834018.html
http://www.voidcn.com/article/p-fmyxrtak-brn.html
直接上测试代码
import torch
import numpy as np
input = torch.from_numpy(np.array([[1,2,3,4],[5,6,7,0],[9,3,0,0]]))
length = [4,3,2] # lengths array has to be sorted in decreasing order
result = torch.nn.utils.rnn.pack_padded_sequence(input,lengths=length,batch_first=True)
print("==============二维输出=============")
print(result)
# input = torch.randn(8,10,300)
# length = [10,10,10,10,10,10,10,10]
#注意,这里length代表每一个batch里面数据的长度,length的数量是8个,因为对应batch_first=True,也就是input的第一维是8个,也就是有8个batch
# perm = torch.LongTensor(range(8))
# result = torch.nn.utils.rnn.pack_padded_sequence(input[perm],lengths=length,batch_first=True)
# print(result)
input = torch.randn(2,3,4)
print("===========三维原始向量================")
print(input)
length = [3,3]
perm = torch.LongTensor(range(2))
result = torch.nn.utils.rnn.pack_padded_sequence(input[perm],lengths=length,batch_first=True)
print("=============三维原始向量==batchsize变换============")
print(result)
input = torch.randn(2,3,4)
print("===========三维原始向量================")
print(input)
length = [2,2,2]
perm = torch.LongTensor(range(2))
result = torch.nn.utils.rnn.pack_padded_sequence(input[perm],lengths=length)
print("=============三维原始向量==batchsize 不等于true变换============")
print(result)
测试结果如下:
注意: 输出里面的batch_sizes=tensor([3,3]), 元素的个数表示数据分为2组,每一个元素的数量是3
结论:
针对三维数组的操作,其输出结论如下
1:最终结果的输出和是否使用batch_first=True,有很大的关系
2:设置batch_first=True,则会将每一个batch里面的相对应的行抽出来,然后顺序组成最终的输出结果
3:设置batch_first=False,也就是默认不设置设置batch_first的情况下,其输出是直接将每一个seq_length对应的数组,叠加起来即可。可以参考:https://blog.csdn.net/u012436149/article/details/79749409,有图形示例。
后续对pad_packed_sequence解析!