在 Keras 中

,python,tensorflow,keras"/>

首页 > 解决方案 > 对 n< 中的 batch_size 感到困惑

在 Keras 中

问题描述

我对运行得很好的代码有点困惑,但我不明白为什么。

我处于 < < p 场景中,其功能比示例多 2 倍。我不小心将批量大小设置为 > n。

那么keras的默认行为是什么?只是回到纯梯度下降,在一个时期结束时对权重进行平均?

我在有监督的二进制分类器设置以及基于 LSTM/Autoencoder 的无监督异常检测器中使用此设置

这增加了额外的混乱,因为我认为在 LSTM 中 - 案例 n % batch_size 应该为零。

标签: pythontensorflowkeras

解决方案


我已经深入研究了源代码,我想我有这些问题的答案。

  1. 如果 batch_size > n,Keras 是否会“退化”为普通梯度下降?

答案是肯定的。从第 334 行开始的方法batch_shuffle中可以看出(注意:我链接到 V2.2 以保留行编号)如果 batch_size > n 则返回整个批次。这里是相关的代码和输出:

import numpy as np
index_array = np.array([0,1,2,3,4,5])
batch_size = 72
batch_count = int(len(index_array) / batch_size)
#batch_count = 0

last_batch = index_array[batch_count * batch_size:]
# last_batch = array([0, 1, 2, 3, 4, 5])

index_array = index_array[:batch_count * batch_size]
#index_array = array([], dtype=int64)

index_array = index_array.reshape((batch_count, batch_size))
#index_array =array([], shape=(0, 72), dtype=int64)

np.random.shuffle(index_array)
index_array = index_array.flatten()
return np.append(index_array, last_batch)
# np.append(index_array, last_batch) = array([0, 1, 2, 3, 4, 5])
  1. 为什么即使 n % batch_size <> 0 LSTM 也能正常工作?

n % batch_size = 0 的要求仅适用于有状态 LSTM,再次在以下代码第 817 行找到证据,仅当 stateful==True 和 n % batch_size <> 0 时才会引发错误


推荐阅读