Pytorch学习笔记【8】:批量训练数据(自定义每次训练数据量)

注意看代码注释,解析全在 注释里

1. 代码:

import torch
import torch.utils.data as Data

torch.manual_seed(1)    # reproducible

BATCH_SIZE = 5    # 每次训练5个数据
# BATCH_SIZE = 8

x = torch.linspace(1, 10, 10)       # this is x data (torch tensor)
y = torch.linspace(10, 1, 10)       # this is y data (torch tensor)
# print(x)
# print(y)
torch_dataset = Data.TensorDataset(x, y) # 设置我们的Data形式
loader = Data.DataLoader(
    dataset=torch_dataset,      # 加载我们设置好的数据
    batch_size=BATCH_SIZE,      # 每次的训练数据个数
    shuffle=True,               # 随机打乱训练数据
    num_workers=2,              # 开2个线程来训练
)


def batch_train():
    for epoch in range(3):   # 训练3次
        for step, (batch_x, batch_y) in enumerate(loader):  # for each training step
            # train your data...
            print('Epoch: ', epoch, '| Step: ', step, '| batch x: ',
                  batch_x.numpy(), '| batch y: ', batch_y.numpy())


if __name__ == '__main__':
    batch_train()

2. 运行结果

Pytorch学习笔记【8】:批量训练数据(自定义每次训练数据量)_第1张图片

你可能感兴趣的:(#,Pytorch)