Keras softmax层返回一个热编码数组
我使用一个简单的网络进行分类,但是预测的输出是一个热编码的。我检查了损失函数内部,实际输出是正确的Keras softmax层返回一个热编码数组,keras,loss-function,one-hot-encoding,softmax,Keras,Loss Function,One Hot Encoding,Softmax,我使用一个简单的网络进行分类,但是预测的输出是一个热编码的。我检查了损失函数内部,实际输出是正确的 ip = Input(shape=(padding_size, n_features)) x = LSTM(50, activation='relu')(ip) x = Dropout(0.2)(x) out = Dense(3, activation='softmax')(x) model = Model(ip, out) 我正在使用一个自定义损失函数。y_true的前三项是标签的一个
ip = Input(shape=(padding_size, n_features))
x = LSTM(50, activation='relu')(ip)
x = Dropout(0.2)(x)
out = Dense(3, activation='softmax')(x)
model = Model(ip, out)
我正在使用一个自定义损失函数。y_true的前三项是标签的一个热编码,其余三项是函数内部使用的值
def odds_loss(y_true, y_pred):
print(y_pred) #see below
print(y_true) #see below
true_1 = y_true[:, 0:1]
true_2 = y_true[:, 1:2]
true_3 = y_true[:, 2:3]
feature_a = y_true[:, 3:4]
feature_b = y_true[:, 4:5]
feature_c = y_true[:, 5:6]
vector = K.concatenate([
true_1 * (feature_a - 0.3),
true_2 * (feature_b - 3.3) + K.log(feature_b - 1),
true_3 * (feature_c - 2.8)
], axis = 1)
return -1 * K.mean(K.sum(vector * y_pred, axis=1))
一批四种元素的打印输出为:
tf.Tensor(
[[0.33180252 0.3375508 0.3306467 ]
[0.3335974 0.3334575 0.33294514]
[0.33349878 0.333613 0.33288828]
[0.3354906 0.3324541 0.33205533]], shape=(4, 3),
dtype=float32)
tf.Tensor(
[[1. 0. 0. 1.467 3.252 5.312]
[0. 1. 0. 1.251 2.851 4.665]
[0. 1. 0. 1.642 2.319 5.133]
[0. 0. 1. 1.635 1.996 3.985]], shape=(4, 3),
dtype=float32)
正如所料,在这个阶段,这只是随机猜测。但是,如果我使用一些测试数据执行预测,我只会得到一个热编码数组,所有这些都是一样的:
y_pred = model.predict(X_test)
print(y_pred)
[[0. 0. 1.]
[0. 0. 1.]
[0. 0. 1.]
[0. 0. 1.]
[0. 0. 1.]
[0. 0. 1.]
[0. 0. 1.]
[0. 0. 1.]
[0. 0. 1.]
[0. 0. 1.]
[0. 0. 1.]
[0. 0. 1.]
[0. 0. 1.]
[0. 0. 1.]
[0. 0. 1.]
[0. 0. 1.]
[0. 0. 1.]
[0. 0. 1.]
[0. 0. 1.]
[0. 0. 1.]]
我手动检查了loss函数内部的操作,返回值与预期一致。为什么我得不到与损失函数内相同的输出