(1)简要介绍
Batch_Size在深度学习用于设定批处理的参数,目前机器学习训练的参数更新主要有三种方法:批梯度下降(Batch Gradient Descent)、随机梯度下降(Stochastic Gradient Descent)、小批梯度下降(Mini-batch Gradient Decent)。其中,批梯度下降是要遍历全部数据集计算一次损失函数,进行一次参数更新,通过这种方式得到的方向能够更加准确的指向极值的方向,由于大量的计算开销,导致学习速度慢;随机梯度下降是对每一个样本计算一次损失函数,进行一次参数更新,由此可见,速度很快,但是方向波动大,不能准确的指向极值的方向,有时甚至两次更新相互抵消;小批梯度下降,把样本数据分为若干批,分批来计算损失函数和更新参数,方向比较稳定,计算开销也相对较小。
根据三种方法的优缺点,在深度学习训练的时候一般采用 小批梯度下降,Batch_Size就是小批量梯度下降中一批的数据量大小。
(2)源码
import torch
import torch.utils.data as Data
torch.manual_seed(1) # reproducible
BATCH_SIZE = 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, y)
torch_dataset = Data.TensorDataset(x, y)
loader = Data.DataLoader(
dataset=torch_dataset, # torch TensorDataset format
batch_size=BATCH_SIZE, # mini batch size
shuffle=True, # random shuffle for training 随机洗牌训练
num_workers=2, # subprocesses for loading data
)
def show_batch():
for epoch in range(3): # train entire dataset 3 times
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__':
show_batch()
注:代码主要参考 https://github.com/MorvanZhou
了解更多关于《计算机视觉与图形学》相关知识,请关注公众号:
下载我们视频中代码和相关讲义,请在公众号回复:计算机视觉课程资料