python - 对不同形状向量的集合使用 tf.nn.l2_loss
问题描述
我想计算我神经网络中所有权重和偏差的 l2 损失。因此,我将所有权重和偏差添加到“tf.GraphKeys.REGULARIZATION_LOSSES”,并希望使用 tensorflow 中定义的函数计算 l2 损失:
W = tf.Variable(tf.truncated_normal([inputDim, outputDim], stddev=0.1), name='W')
b = tf.Variable(tf.ones([outputDim])/10, name='b')
tf.add_to_collection(tf.GraphKeys.REGULARIZATION_LOSSES, W)
tf.add_to_collection(tf.GraphKeys.REGULARIZATION_LOSSES, b)
...
稍后在代码中:
...
vars = tf.get_collection(tf.GraphKeys.REGULARIZATION_LOSSES)
l2_loss = tf.nn.l2_loss(vars) * config.L2PENALTY
我在具有 3 层的网络上使用该功能时遇到此错误,但找不到解决方案:
ValueError: Tried to convert 't' to a tensor and failed. Error: Shapes must be equal rank, but are 2 and 1
From merging shape 4 with other shapes. for 'l2_loss/L2Loss/packed' (op: 'Pack') with input shapes: [784,512], [512], [512,256], [256], [256,10], [10].
解决方案
尽管 tf.nn.l2_loss 接收张量作为其参数,但您将张量列表传递给 tf.nn.l2_loss。因此错误消息意味着 l2_loss 无法将列表转换为张量。
我们应该像这样计算 L2 损失
vars = tf.get_collection(tf.GraphKeys.REGULARIZATION_LOSSES)
list_l2_loss = []
for v in vars:
list_l2_loss.append(tf.nn.l2_loss(v))
total_l2_loss = tf.add_n(list_l2_loss)
添加信息
您可以通过 tf.add_to_collection 将 nD Tensor 添加到集合中。但是 tf.GraphKeys.REGULARIZATION_LOSSES 是 tf.get_variable 创建的正则化器的保留名称。所以我们应该给你一个像“MyReguralizers”这样的原始名称。