RJ.*_* Lo 3 keras tensorflow loss-function
操作系统平台和发行版: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)
Run Code Online (Sandbox Code Playgroud)
但是,如果我想用自己的代码编写损失函数,例如:
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
Run Code Online (Sandbox Code Playgroud)
我可以使用自定义损失函数并根据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))
Run Code Online (Sandbox Code Playgroud)
如何根据上述代码(第一部分)进行操作?谢谢你的帮助!!
只需将损失包装成一个函数,然后提供给即可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'])
Run Code Online (Sandbox Code Playgroud)
另请注意,
y_true入float32。它由Keras自动完成。reduce_mean。Keras也会照顾这一点。| 归档时间: |
|
| 查看次数: |
1593 次 |
| 最近记录: |