Epoch vs Batch size vs Iterations
在学习机器学习的过程中,很容易对Epoch
Batch size
和Iterations
产生混淆。在这里,记录一下学习心得。
谈到这是三个概念,难以绕开梯度下降。
梯度下降
在机器学习中,梯度下降是一个重复优化的算法。梯度可以理解为某一点的斜率。
通过不断的优化,将损失函数降到最低。
然而,当数据集过大时,我们无法将所有的数据同时送入计算机,那么我们需要将数据集进行划分,分块送入计算机。
概念 | 代表的含义 |
---|---|
Epoch | 将数据集中的所有数据送入训练网络一次,叫一个Epoch |
Batch size | 将数据集进行划分时,每次划分的大小,叫 batch size |
Iteration | batch size * iteration = 完整的数据集 |
更新参数
既然有了epoch和iteration,就有另一个问题,经过一个epoch还是iteration之后完成更新呢。
答案是每经过一个iteration,就更新一次参数。这里的表述是需要框定情景的,即不同的随机梯度下降算法对于参数的更新,是不一样的,常见的梯度下降方法为BGD,SGD,MBGD。
BGD
- Batch gradient descent method BGD 批梯度下降
- 这是一种最基本的梯度下降方法,使用所有的样本来完成参数更新
- 缺点很明显,当数据集过大时,对内存和运算的要求很高,计算速度较慢,对于极大的数据集普通机器直接做BGD是无法完成的。
- 优点就是盲目性较低。
SGD
- Stochastic gradient decent SGD 随机梯度下降
- 使用单个的样本进行参数优化,需要进行多次盲目的参数更新
- 可以说SGD和BGD都是极端的方法,一个all-in,一个挤牙膏
MBGD
- Mini-Batch gradient decent 小批量梯度下降
- 每次优化都使用数据集的一部分数据
- 兼顾SGD和BGD的优势
举个例子
数据集大小为 10, batch size 为2, 那么跑完一个数据集需要 10 / 2 = 5 个iteration,5个iteration为一个epoch,在这个过程中参数更新了5次。
实现BGD和SGD
def gradientDescent(X, y, theta, alpha, num_iters):
"""
Performs gradient descent to learn theta
"""
m = y.size # number of training examples
for i in range(num_iters):
y_hat = np.dot(X, theta)
theta = theta - alpha * (1.0/m) * np.dot(X.T, y_true-y_pred)
return theta
def SGD(f, theta0, alpha, num_iters):
"""
Arguments:
f -- the function to optimize, it takes a single argument
and yield two outputs, a cost and the gradient
with respect to the arguments
theta0 -- the initial point to start SGD from
num_iters -- total iterations to run SGD for
Return:
theta -- the parameter value after SGD finishes
"""
start_iter = 0
theta= theta0
for iter in xrange(start_iter + 1, num_iters + 1):
_, grad = f(theta)
theta = theta - (alpha * grad) # there is NO dot product!
return theta
总结
写到这里,基本上就明白了,其实batch size和iteration就是针对MBGD产生的概念。而MBGD也是当前使用最为广泛的优化函数。
参考博客
- Epoch vs Batch Size vs Iterations
- Understanding Gradient Descent And Its Variants
rokuapp.com/towardsdatascience.com/understanding-gradient-descent-and-its-variants-cf0df5c45478) - Difference between Batch Gradient Descent and Stochastic Gradient Descent