我打算为我的深度学习神经网络程序创建迷你批次,训练集包含’m’个样本。我尝试过以下方法:
# 首先打乱(X, Y)
permutation = list(np.random.permutation(m))
shuffled_X = X[:, permutation]
shuffled_Y = Y[:, permutation].reshape((1,m))
# 分割(shuffled_X, shuffled_Y)。注意最后一个迷你批次可能包含较少的训练样本。
num_complete_minibatches = math.floor(m/mini_batch_size) # 在你的分割中,迷你批次大小为mini_batch_size的数量
for k in range(0, num_complete_minibatches):
### START CODE HERE ### (约2行)
mini_batch_X = shuffled_X[mini_batch_size*k:mini_batch_size*(k+2)]
mini_batch_Y = shuffled_Y[mini_batch_size*k:mini_batch_size*(k+2)]
但这给我带来了以下结果:
shape of the 1st mini_batch_X: (128, 148)
shape of the 2nd mini_batch_X: (128, 148)
shape of the 3rd mini_batch_X: (12288, 148)
shape of the 1st mini_batch_Y: (1, 148)
shape of the 2nd mini_batch_Y: (0, 148)
shape of the 3rd mini_batch_Y: (1, 148)
mini batch sanity check: [ 0.90085595 -0.7612069 0.2344157 ]
预期输出是:
shape of the 1st mini_batch_X (12288, 64)
shape of the 2nd mini_batch_X (12288, 64)
shape of the 3rd mini_batch_X (12288, 20)
shape of the 1st mini_batch_Y (1, 64)
shape of the 2nd mini_batch_Y (1, 64)
shape of the 3rd mini_batch_Y (1, 20)
mini batch sanity check [ 0.90085595 -0.7612069 0.2344157 ]
我确定我的切片实现有问题,但无法找出原因。任何帮助都非常感激。谢谢!
回答:
我认为您没有正确地切片numpy数组。最初打乱数组的方式是正确的。您不想切片第一维,所以保持它不变,使用:
,并使用<Start Index>:<End Index>
切片第二维。这是我在下面的代码中所做的。
for k in range(num_complete_minibatches+1):
### START CODE HERE ### (约2行)
mini_batch_X = shuffled_X[:,mini_batch_size*(k):mini_batch_size*(k+1)]
mini_batch_Y = shuffled_Y[:,mini_batch_size*(k):mini_batch_size*(k+1)]
print(mini_batch_X.shape,mini_batch_Y.shape)