pytorch批訓練資料構造

2022-05-08 17:54:09 字數 2780 閱讀 8081

這是對莫凡python的學習筆記。

1.建立資料

import

torch

import

torch.utils.data as data

batch_size = 8x = torch.linspace(1,10,10)

y = torch.linspace(10,1,10)

可以看到建立了兩個一維資料,x:1~10,y:10~1

2.構造資料集物件,及資料載入器物件

torch_dataset =data.tensordataset(x,y)

loader =data.dataloader(

dataset =torch_dataset,

batch_size =batch_size,

shuffle =false,

num_workers = 2)

num_workers應該指的是多執行緒

3.輸出資料集,這一步主要是看一下batch長什麼樣子

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:', array([1., 2., 3., 4., 5., 6., 7., 8.], dtype=float32), '| batch y:', array([10.,  9.,  8.,  7.,  6.,  5.,  4.,  3.], dtype=float32))

('epoch:', 0, '| step:', 1, '| batch x:', array([ 9., 10.], dtype=float32), '| batch y:', array([2., 1.], dtype=float32))

('epoch:', 1, '| step:', 0, '| batch x:', array([1., 2., 3., 4., 5., 6., 7., 8.], dtype=float32), '| batch y:', array([10., 9., 8., 7., 6., 5., 4., 3.], dtype=float32))

('epoch:', 1, '| step:', 1, '| batch x:', array([ 9., 10.], dtype=float32), '| batch y:', array([2., 1.], dtype=float32))

('epoch:', 2, '| step:', 0, '| batch x:', array([1., 2., 3., 4., 5., 6., 7., 8.], dtype=float32), '| batch y:', array([10., 9., 8., 7., 6., 5., 4., 3.], dtype=float32))

('epoch:', 2, '| step:', 1, '| batch x:', array([ 9., 10.], dtype=float32), '| batch y:', array([2., 1.], dtype=float32))

可以看到,batch_size等於8,則第二個bacth的資料只有兩個。

將batch_size改為5,輸出如下

('epoch:', 0, '| step:', 0, '| batch x:', array([1., 2., 3., 4., 5.], dtype=float32), '| batch y:', array([10.,  9.,  8.,  7.,  6.], dtype=float32))

('epoch:', 0, '| step:', 1, '| batch x:', array([ 6., 7., 8., 9., 10.], dtype=float32), '| batch y:', array([5., 4., 3., 2., 1.], dtype=float32))

('epoch:', 1, '| step:', 0, '| batch x:', array([1., 2., 3., 4., 5.], dtype=float32), '| batch y:', array([10., 9., 8., 7., 6.], dtype=float32))

('epoch:', 1, '| step:', 1, '| batch x:', array([ 6., 7., 8., 9., 10.], dtype=float32), '| batch y:', array([5., 4., 3., 2., 1.], dtype=float32))

('epoch:', 2, '| step:', 0, '| batch x:', array([1., 2., 3., 4., 5.], dtype=float32), '| batch y:', array([10., 9., 8., 7., 6.], dtype=float32))

('epoch:', 2, '| step:', 1, '| batch x:', array([ 6., 7., 8., 9., 10.], dtype=float32), '| batch y:', array([5., 4., 3., 2., 1.], dtype=float32))

pytorch(五) 批訓練

import torch import torch.utils.data as data 虛構要訓練的資料 x torch.linspace 11,20,10 在 11,20 裡取出10個間隔相等的數 torch tensor y torch.linspace 20,11,10 batch size...

Pytorch教程 批訓練

torch and numpy 變數 variable 激勵函式 關係擬合 回歸 區分型別 分類 快速搭建法 批訓練加速神經網路訓練 optimizer優化器 卷積神經網路 cnn 卷積神經網路 rnn lstm rnn 迴圈神經網路 分類 rnn 迴圈神經網路 回歸 自編碼 autoencoder...

莫煩pytorch批訓練

import torch import torch.utils.data as data 包裝資料類 tensordataset 包裝資料和目標張量的資料集,通過沿著第乙個維度索引兩個張量來 class torch.utils.data.tensordataset data tensor,targe...