Keras 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的前三项是标签的一次性编码,其余三项是函数内部使用的值。

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]],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.]]

我手动检查了损失函数中的操作,返回的值符合预期。为什么我无法获得与损失函数内部相同的输出

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)