• 4.批量处理数据


     1 '''
     2 torch-批量训练数据
     3 DataLoader:是 torch 给你用来包装你的数据的工具. 
     4 所以你要讲自己的 (numpy array 或其他) 数据形式装换成 Tensor, 然后再放进这个包装器中.
     5 使用 DataLoader 有什么好处呢? 就是帮你有效地迭代数据, 举例:
     6 '''
     7 import torch
     8 import torch.utils.data as Data
     9 torch.manual_seed(1)    # reproducible
    10 
    11 BATCH_SIZE = 5     # 批训练的数据个数
    12 #设置假数据
    13 x = torch.linspace(1, 10, 10)       # x data (torch tensor)
    14 y = torch.linspace(10, 1, 10)       # y data (torch tensor)
    15 
    16 # 先转换成 torch 能识别的 Dataset
    17 torch_dataset = Data.TensorDataset(x,y)
    18 
    19 # 把 dataset 放入 DataLoader
    20 loader = Data.DataLoader(
    21     dataset=torch_dataset,      # torch TensorDataset format
    22     batch_size=BATCH_SIZE,      # mini batch size
    23     shuffle=True,               # 要不要打乱数据 (打乱比较好)
    24     num_workers=2,              # 多线程来读数据
    25 )
    26 
    27 for epoch in range(3):   # 训练所有!整套!数据 3 次
    28     for step, (batch_x, batch_y) in enumerate(loader):  # 每一步 loader 释放一小批数据用来学习
    29         # 假设这里就是你训练的地方...
    30         # 打出来一些数据
    31         print('Epoch: ', epoch, '| Step: ', step, '| batch x: ',
    32               batch_x.numpy(), '| batch y: ', batch_y.numpy())

    '''
    Epoch:  0 | Step:  0 | batch x:  [ 2.  7. 10.  1.  4.] | batch y:  [ 9.  4.  1. 10.  7.]
    Epoch:  0 | Step:  1 | batch x:  [3. 5. 6. 8. 9.] | batch y:  [8. 6. 5. 3. 2.]
    Epoch:  1 | Step:  0 | batch x:  [7. 8. 2. 3. 9.] | batch y:  [4. 3. 9. 8. 2.]
    Epoch:  1 | Step:  1 | batch x:  [ 5.  1.  6.  4. 10.] | batch y:  [ 6. 10.  5.  7.  1.]
    Epoch:  2 | Step:  0 | batch x:  [ 8.  1.  4.  9. 10.] | batch y:  [ 3. 10.  7.  2.  1.]
    Epoch:  2 | Step:  1 | batch x:  [7. 6. 5. 2. 3.] | batch y:  [4. 5. 6. 9. 8.]
    '''
  • 相关阅读:
    包含游标、数组的例子
    团队开发的注意点
    养成逻辑的习惯
    C# DEV 右键出现菜单
    C#中ToString数据类型格式大全 千分符(转)
    Oracle系统查询的语句
    PLSQLDevelop 查询当前未完成的会话
    Oracle 异常工作中出现的
    Oracle 返回结果集 sys_refcursor
    DevExpress.XtraEditors.TextEdit,设定为必须number类型的。
  • 原文地址:https://www.cnblogs.com/xuechengmeigui/p/12388609.html
Copyright © 2020-2023  润新知