【发布时间】:2020-04-14 04:26:05
【问题描述】:
下面是一个简单的 numpy 示例,说明我想做的事情:
import numpy as np
y_true = np.array([0,0,1])
y_pred = np.array([0.1,0.2,0.7])
yc = (1-y_true).astype('bool')
desired = y_pred[yc]
>>> desired
>>> array([0.1, 0.2])
所以ground truth对应的预测是0.7,我想对一个包含y_pred的所有元素的数组进行操作,除了ground truth元素。
我不确定如何在 Keras 中进行这项工作。这是损失函数中问题的一个工作示例。现在'期望'没有完成任何事情,但这是我需要处理的:
# using tensorflow 2.0.0 and keras 2.3.1
import tensorflow.keras.backend as K
import tensorflow as tf
from tensorflow.keras.layers import Input,Dense,Flatten
from tensorflow.keras.models import Model
from keras.datasets import mnist
(x_train, y_train), (x_test, y_test) = mnist.load_data()
# Normalize data.
x_train = x_train.astype('float32') / 255
x_test = x_test.astype('float32') / 255
# Convert class vectors to binary class matrices.
y_train = tf.keras.utils.to_categorical(y_train, 10)
y_test = tf.keras.utils.to_categorical(y_test, 10)
input_shape = x_train.shape[1:]
x_in = Input((input_shape))
x = Flatten()(x_in)
x = Dense(256,'relu')(x)
x = Dense(256,'relu')(x)
x = Dense(256,'relu')(x)
out = Dense(10,'softmax')(x)
def loss(y_true,y_pred):
yc = tf.math.logical_not(kb.cast(y_true, 'bool'))
desired = tf.boolean_mask(y_pred,yc,axis = 1) #Remove and it runs
CE = tf.keras.losses.categorical_crossentropy(
y_true,
y_pred)
L = CE
return L
model = Model(x_in,out)
model.compile('adam',loss = loss,metrics = ['accuracy'])
model.fit(x_train,y_train)
我最终得到一个错误
ValueError: Shapes (10,) and (None, None) are incompatible
其中 10 是类别数。最终目的是实现这一点:ComplementEntropy 在 Keras,我的问题似乎是第 26-28 行。
【问题讨论】:
-
请同时提供
rest that works fine后面的代码。所以我们有你试图使用的全部损失。 -
我添加了一个示例,您可以运行该示例来重现相同的错误。
标签: python tensorflow keras tensorflow2.0 loss-function