使用Keras在TensorFlow中自定义损失函数

3

操作系统平台和发行版:Linux Ubuntu16.04;TensorFlow版本:'1.4.0'

以下代码可以正常运行:

import tensorflow as tf
from tensorflow.python.keras.layers import Dense
from tensorflow.python.keras.backend import categorical_crossentropy
from tensorflow.examples.tutorials.mnist import input_data
from tensorflow.python.keras.models import Model
from tensorflow.python.keras.layers import  Input

mnist_data = input_data.read_data_sets('MNIST_data', one_hot=True)
img_size_flat = 28*28
batch_size = 64

def gen(batch_size=32):
    while True:
        batch_data, batch_label = mnist_data.train.next_batch(batch_size)
        yield batch_data, batch_label   


inputs = Input(shape=(img_size_flat,))
x = Dense(128, activation='relu')(inputs)  # fully-connected layer with 128 units and ReLU activation
x = Dense(128, activation='relu')(x)
preds = Dense(10, activation='softmax')(x)  # output layer with 10 units and a softmax activation
model = Model(inputs=inputs, outputs=preds)

model.compile(optimizer='rmsprop',
               loss='categorical_crossentropy',
               metrics=['accuracy'])


model.fit_generator(gen(batch_size), steps_per_epoch=len(mnist_data.train.labels)//batch_size, epochs=2)

但是如果我想用自己的代码编写损失函数,该怎么办:

preds_softmax = tf.nn.softmax(preds)
step1 = tf.cast(y_true, tf.float32) * tf.log(preds_softmax)
step2 = -tf.reduce_sum(step1, reduction_indices=[1])
loss = tf.reduce_mean(step2)       # loss

我可以使用定制化的损失函数并基于keras的model.fit_generator进行训练吗?

像下面这样的代码在tensorflow上是否可行?

inputs = tf.placeholder(tf.float32, shape=(None, 784))
x = Dense(128, activation='relu')(inputs) # fully-connected layer with 128 units and ReLU activation
x = Dense(128, activation='relu')(x)
preds = Dense(10, activation='softmax')(x) # output layer with 10 units and a softmax activation

y_true = tf.placeholder(tf.float32, shape=(None, 10))

基于上述代码(第一部分),我该如何操作?感谢任何帮助!
1个回答

5
只需将您的损失函数包装成一个函数,并提供给model.compile即可。
def custom_loss(y_true, y_pred):
    preds_softmax = tf.nn.softmax(y_pred)
    step1 = y_true * tf.log(preds_softmax)
    return -tf.reduce_sum(step1, reduction_indices=[1])

model.compile(optimizer='rmsprop',
              loss=custom_loss,
              metrics=['accuracy'])

还要注意的是,

  • 您不需要将y_true转换为float32。Keras会自动完成此操作。
  • 您不需要进行最终的reduce_mean。Keras也会处理它。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接