1

keras 的自定义损失函数输出错误:当我使用贝叶斯层 ( tensorflow_probability.layers.DenseFlipout) 并使用我的自定义损失函数时,我得到了错误的输出损失。但是如果我用传统tf.keras.layers.Dense层替换贝叶斯层,输出是正确的。有谁能够帮我 ?

import tensorflow as tf

from tensorflow.examples.tutorials.mnist import input_data as mnist_data

train, valid, test = mnist_data.read_data_sets('~/code/Python')

num_classes = 10
from tensorflow import keras
import tensorflow_probability as tfp
model = keras.Sequential()

#model.add(keras.layers.Dense(10, activation = 'softmax', input_shape=(784,)))
model.add(tfp.layers.DenseFlipout(10, activation = 'softmax', input_shape=(784,)))

sgd = keras.optimizers.SGD(lr=.1, momentum=0.9, nesterov=True)
def my_loss(y_true,y_pred):
    return tf.reduce_mean((y_true-y_pred)**2)
model.compile(loss=my_loss, optimizer=sgd, metrics=['accuracy'])

x_train, y_train = train.images, train.labels
x_test, y_test = test.images, test.labels

y_train = keras.utils.to_categorical(y_train, num_classes)
y_test = keras.utils.to_categorical(y_test, num_classes)
model.fit(x_train, y_train,
          batch_size=128,
          epochs=10,
          validation_data=(x_test, y_test),
          shuffle=True)
4

0 回答 0