Torch 中提供了一种帮你整理你的数据结构的好东西, 叫做 DataLoader, 我们能用它来包装自己的数据, 进行批训练.
DataLoader 是 torch 给你用来包装你的数据的工具. 所以你要将自己的 (numpy array 或其他) 数据形式装换成 Tensor, 然后再放进这个包装器中. 使用 DataLoader 有什么好处呢? 就是他们帮你有效地迭代数据, 举例:
首先导入库,import torch.utils.data as Data 是对数据的读取1和处理
import torch
import torch.utils.data as Data
定义数据
BATCH_SIZE = 5
x = torch.linspace(1,10,10)
#tensor([ 1., 2., 3., 4., 5., 6., 7., 8., 9., 10.])
y = torch.linspace(10,1,10)
#tensor([10., 9., 8., 7., 6., 5., 4., 3., 2., 1.])
定义一批处理数据的个数,BATCH_SIZE = 5表示每一批数据有5个
最重要的一部分:
torch_dataset = Data.TensorDataset(x,y)
loader = Data.DataLoader(
dataset = torch_dataset,
batch_size = BATCH_SIZE,
shuffle = True,
num_workers = 2
)
Data.TensorDataset(x,y)表示把x,y传入,创建数据集
Data.DataLoader表示创建DataLoader
batch_size设置为5
shuffle=True每一次epoch打乱数据顺序,False代表每次epoch的数据顺序是一样的
num_workers= 2使用2个子进程
for epoch in range(3):
for step,(batch_x,batch_y) in enumerate(loader):
print('Epoch:',epoch,'| step:',step,'| batch_x:'
,batch_x.numpy(),'| batch_y:',batch_y.numpy())
Epoch: 0 | step: 0 | batch_x: [ 9. 6. 1. 10. 2.] | batch_y: [ 2. 5. 10. 1. 9.]
Epoch: 0 | step: 1 | batch_x: [5. 4. 3. 8. 7.] | batch_y: [6. 7. 8. 3. 4.]
Epoch: 1 | step: 0 | batch_x: [ 4. 10. 7. 3. 6.] | batch_y: [7. 1. 4. 8. 5.]
Epoch: 1 | step: 1 | batch_x: [9. 8. 5. 1. 2.] | batch_y: [ 2. 3. 6. 10. 9.]
Epoch: 2 | step: 0 | batch_x: [9. 2. 3. 7. 5.] | batch_y: [2. 9. 8. 4. 6.]
Epoch: 2 | step: 1 | batch_x: [ 8. 1. 10. 6. 4.] | batch_y: [ 3. 10. 1. 5. 7.]
Epoch: 训练集中的全部样本都在训练模型中走了一遍,并返回一次(有去有回),为一个epoch。
这里表示将所有的训练样本在同一个模型中训练3遍
batchsize:简单点说,就是我们一次要将多少个数据扔进模型去训练,这个值介于1和训练样本总个数之间。
enumerate用法举例
seasons = ['Spring', 'Summer', 'Fall', 'Winter']
print(list(enumerate(seasons)))
[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]