- TensorDataset
作用:可以用来对tensor进行打包。主要作用是对数据集中的特征及标签进行打包,便于使用或输出。
代码:
a = torch.tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9], [1, 2, 3], [4, 5, 6], [7, 8, 9], [1, 2, 3], [4, 5, 6], [7, 8, 9], [1, 2, 3], [4, 5, 6], [7, 8, 9]])
b = torch.tensor([44, 55, 66, 44, 55, 66, 44, 55, 66, 44, 55, 66])
# TensorDataset对tensor进行打包
train_ids = TensorDataset(a, b)
for x_train, y_label in train_ids:
print(x_train, y_label)
# dataloader进行数据封装
print('=' * 80)
train_loader = DataLoader(dataset=train_ids, batch_size=4, shuffle=True)
for i, data in enumerate(train_loader, 1):
# 注意enumerate返回值有两个,一个是序号,一个是数据(包含训练数据和标签)
x_data, label = data
print(' batch:{0} x_data:{1} label: {2}'.format(i, x_data, label))
输出结果:
tensor([1, 2, 3]) tensor(44)
tensor([4, 5, 6]) tensor(55)
tensor([7, 8, 9]) tensor(66)
tensor([1, 2, 3]) tensor(44)
tensor([4, 5, 6]) tensor(55)
tensor([7, 8, 9]) tensor(66)
tensor([1, 2, 3]) tensor(44)
tensor([4, 5, 6]) tensor(55)
tensor([7, 8, 9]) tensor(66)
tensor([1, 2, 3]) tensor(44)
tensor([4, 5, 6]) tensor(55)
tensor([7, 8, 9]) tensor(66)
================================================================================
batch:1 x_data:tensor([[1, 2, 3],
[1, 2, 3],
[4, 5, 6],
[4, 5, 6]]) label: tensor([44, 44, 55, 55])
batch:2 x_data:tensor([[4, 5, 6],
[7, 8, 9],
[7, 8, 9],
[7, 8, 9]]) label: tensor([55, 66, 66, 66])
batch:3 x_data:tensor([[1, 2, 3],
[1, 2, 3],
[7, 8, 9],
[4, 5, 6]]) label: tensor([44, 44, 66, 55])
附录:
enumerate() 函数用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标,一般用在 for 循环当中。
语法:
enumerate(sequence, [start=0])
#参数
#sequence -- 一个序列、迭代器或其他支持迭代对象。
#start -- 下标起始位置。
#返回值
#返回 enumerate(枚举) 对象。
实例:
>>>seasons = ['Spring', 'Summer', 'Fall', 'Winter']
>>> list(enumerate(seasons))
[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
>>> list(enumerate(seasons, start=1)) # 下标从 1 开始
[(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]
for循环实例:
>>>seq = ['one', 'two', 'three']
>>> for i, element in enumerate(seq):
... print i, element
...
0 one
1 two
2 three
参考:
1.https://zhuanlan.zhihu.com/p/349083821
2.https://www.jianshu.com/p/eaf1e9bb1913