简体   繁体   English

如何使用 tensorflow 损失 function 与 keras Z20F35E630DAF44DBDFA4C3F68F539?

[英]How do I use a tensorflow loss function with a keras model?

I am using Tensorflow 1.14, and I have designed a model using Keras.我正在使用 Tensorflow 1.14,并且我使用 Keras 设计了 model。 I want to use tf.nn.sparse_softmax_cross_entropy_with_logits when I compile my model, but I do not see any equivalent loss function in Keras.我想在编译tf.nn.sparse_softmax_cross_entropy_with_logits时使用 tf.nn.sparse_softmax_cross_entropy_with_logits,但在 Z7FEE7BB66F42794C3E3278EFFCD8CZ 中看不到任何等效损失 function Is there any way I can use this with my model?有什么办法可以将它与我的 model 一起使用?

My current code to compile:我当前要编译的代码:

model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])

Thank you for any help.感谢您的任何帮助。

You can use the tf.losses.sparse_categorical_crossentropy with from_logits set to True and wrap it in a function您可以使用tf.losses.sparse_categorical_crossentropy并将from_logits设置为True并将其包装在 function

import tensorflow as tf

def my_tf_loss_fn(y_true, y_pred):
    return tf.losses.sparse_categorical_crossentropy(y_true, y_pred, from_logits=True)

model = tf.keras.applications.ResNet50()
model.compile(loss=my_tf_loss_fn, optimizer='adam')

But if you insist on using tf.nn.sparse_softmax_cross_entropy_with_logits I cannot think of a clean way to do this, but this works但是如果你坚持使用tf.nn.sparse_softmax_cross_entropy_with_logits我想不出一个干净的方法来做到这一点,但这有效

import tensorflow as tf

def my_tf_loss_fn(y_true, y_pred):
    return tf.nn.sparse_softmax_cross_entropy_with_logits(labels=y_true, logits=y_pred)

model = tf.keras.applications.ResNet50()
dummy_tensor = tf.placeholder(dtype=tf.int32, shape=[None])
model.compile(loss=my_tf_loss_fn, optimizer='adam', target_tensors=dummy_tensor)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM