Keras:自定义损失函数:维度问题(无,无)

Keras:自定义损失函数:维度问题(无,无),keras,tensor,loss-function,Keras,Tensor,Loss Function,我正在用Keras构建一个神经网络。我需要定义一个简单的自定义损耗函数。然而,我在创建自定义损失函数时遇到了y_True的维数问题 我在loss函数中插入了print函数,以验证y_true(目标变量)的维度。它表明y_的维数为真(无,无),但它应该为(无,10)。y_pred的维度为(无,10) 任何人都可以指出错误在哪里?非常感谢 from keras.datasets import mnist (train_images, train_labels), (test_images, tes

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

我在loss函数中插入了print函数,以验证y_true(目标变量)的维度。它表明y_的维数为真(无,无),但它应该为(无,10)。y_pred的维度为(无,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)