我遇到了同样的问题,经过一些研究,这是我的解决方案:
如果您使用的是张量流:
多标签损失:
cross_entropy = tf.nn.sigmoid_cross_entropy_with_logits(logits=logits, labels=tf.cast(targets,tf.float32))
loss = tf.reduce_mean(tf.reduce_sum(cross_entropy, axis=1))
prediction = tf.sigmoid(logits)
output = tf.cast(self.prediction > threshold, tf.int32)
train_op = tf.train.AdamOptimizer(0.001).minimize(loss)
解释 :
例如,如果来自模型和标签的 Logits 是:
logits = array([[ 1.4397182 , -0.7993438 , 4.113389 , 3.2199187 , 4.5777845 ],
[ 0.30619335, 0.10168511, 4.253479 , 2.3782277 , 4.7390924 ],
[ 1.124632 , 1.6056736 , 2.9778094 , 2.0808482 , 2.0735667 ],
[ 0.7051575 , -0.10341895, 4.990803 , 3.7019827 , 3.8265839 ],
[ 0.6333333 , -0.76601076, 3.2255085 , 2.7842572 , 5.3817415 ]],
dtype=float32)
labels = array([[1, 1, 0, 0, 0],
[0, 1, 0, 0, 1],
[1, 1, 1, 1, 0],
[0, 0, 1, 0, 1],
[1, 1, 1, 1, 1]])
then
cross_entropy = tf.nn.sigmoid_cross_entropy_with_logits(logits=logits, labels=tf.cast(targets,tf.float32))
will give you :
[[0.21268466 1.170648 4.129609 3.2590992 4.58801 ]
[0.85791767 0.64359653 4.2675934 2.466893 0.00870855]
[0.28124034 0.18294993 0.04965096 0.11762683 2.1920042 ]
[1.1066352 0.64277405 0.00677719 3.7263577 0.02155003]
[0.42580318 1.147773 0.03896642 0.059942 0.00458926]]
and
prediction = tf.cast(tf.sigmoid(one_placeholder) > 0.5, tf.int32)
will give you :
[[1 0 1 1 1]
[1 1 1 1 1]
[1 1 1 1 1]
[1 0 1 1 1]
[1 0 1 1 1]]
现在您已经有了预测标签和真实标签,您可以轻松计算准确度。
对于多类:
标签必须是 one-hot 编码
cross_entropy = tf.nn.softmax_cross_entropy_with_logits_v2(logits=logits, labels = one_hot_y)
loss = tf.reduce_sum(cross_entropy)
optimizer = tf.train.AdamOptimizer(learning_rate=self.lr).minimize(loss)
predictions = tf.argmax(logits, axis=1, output_type=tf.int32, name='predictions')
accuracy = tf.reduce_sum(tf.cast(tf.equal(predictions, true_labels), tf.float32))
另一个例子
# LOSS AND OPTIMIZER
loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(logits=output, labels=y))
optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate,
beta1=0.9,
beta2=0.999,
epsilon=1e-08).minimize(loss, global_step=global_step)
# PREDICTION AND ACCURACY CALCULATION
correct_prediction = tf.equal(y_pred_cls, tf.argmax(y, axis=1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))