如何实现卷积神经网络的L2正则化代价函数

时间:2017-10-20 10:37:30

标签: tensorflow computer-vision conv-neural-network regularized

我已经为数字分类实施了CNN模型。我的模型过度拟合,为了克服过度拟合,我试图在我的成本函数中使用L2 Regularization。我有一点困惑 如何选择<weights>以放入成本等式(代码的最后一行)。

...

x = tf.placeholder(tf.float32, shape=[None, img_size, img_size, num_channels], name='x') # Input
y_true = tf.placeholder(tf.float32, shape=[None, num_classes], name='y_true') # Labels

<Convolution Layer 1>

<Convolution Layer 2>

<Convolution Layer 3>

<Fully Coonected 1>

<Fully Coonected 2> O/P = layer_fc2 

# Loss Function
lambda = 0.01
cross_entropy = tf.nn.softmax_cross_entropy_with_logits(logits=layer_fc2, labels=y_true)
# cost        = tf.reduce_mean(cross_entropy) # Nornmal Loss
cost          = tf.reduce_mean(cross_entropy + lambda * tf.nn.l2_loss(<weights>)) # Regularized Loss

...

1 个答案:

答案 0 :(得分:3)

您应该根据权重定义L2损失 - 使用trainable_variables

C = tf.nn.softmax_cross_entropy_with_logits(logits=layer_fc2, labels=y_true)
l2_loss = tf.add_n([tf.nn.l2_loss(v) for v in tf.trainable_variables()])
C = C + lambda * l2_loss