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))

根据上面的代码我该怎么做(第一部分)?谢谢你的帮助!!

4

1 回答 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 也会处理这个问题。
于 2018-02-07T02:22:33.543 回答