Keras:自定义损失函数:尺寸问题(无,无)

时间:2020-06-02 01:08:24

标签: keras tensor loss-function

我正在用Keras构建一个神经网络。我需要定义一个简单的自定义损失函数。但是,在创建自定义损失函数时遇到了y_True的尺寸问题。

我在损失函数中插入了打印函数,以验证y_true(目标变量)的尺寸。它显示y_true的维数为(无,无),但应为(无,10)。 y_pred的尺寸为(none,10)。

任何人都可以指出错误在哪里?非常感谢。

from keras.datasets import mnist

(train_images, train_labels), (test_images, test_labels) = mnist.load_data()

from keras import models
from keras import layers

network = models.Sequential()
network.add(layers.Dense(512, activation='relu', input_shape=(28 * 28,)))
network.add(layers.Dense(10, activation='softmax'))

def customLoss(yTrue,yPred):
    print(yTrue)
    print(yPred)
    print(K.int_shape(yTrue))
    return K.dot(yTrue, yPred)  # K.mean(K.dot(yTrue,yPred), axis=-1)


network.compile(optimizer='rmsprop',
                loss=customLoss,
                metrics=['accuracy'])  # loss='categorical_crossentropy',

train_images = train_images.reshape((60000, 28 * 28))
train_images = train_images.astype('float32') / 255

test_images = test_images.reshape((10000, 28 * 28))
test_images = test_images.astype('float32') / 255

from keras.utils import to_categorical

train_labels = to_categorical(train_labels)
test_labels = to_categorical(test_labels)



network.fit(train_images, train_labels, epochs=5, batch_size=128)

0 个答案:

没有答案