使用贝叶斯层时,keras自定义损失输出错误

时间:2019-01-28 21:42:35

标签: tensorflow keras bayesian-networks tensorflow-probability

keras的

custom-loss-function输出错误: 当我使用贝叶斯层(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)

0 个答案:

没有答案