由于keras在做二分类损失的时候,激活函数选择的是sigmod,所以此处不能超过1
当选择的损失函数对应的取值超出范围的时候就会报错。
如下合理的loss使用方式供参考:
# 由于此处为二分类问题,此处选择sigmoid作为激活函数
out1 = layers.Dense(units=1, activation="sigmoid", name='out1')(features)
# 为多分类,此处选择softmax作为激活函数
out2 = layers.Dense(units=6, activation="softmax", name='out2')(features)
# Received a label value of 1 which is outside the valid range of [0, 1) - Python, Keras
# In the last Dense layer you used model.add(Dense(1, activation='softmax')).
# Here 1 restricts its value from [0, 1) change its shape to the maximum output label.
# For eg your output is from label [0,7) then use model.add(Dense(7, activation='softmax'))
def focal_loss(y_true, y_pred):
print('focal_loss', y_true, y_pred)
return sparse_categorical_focal_loss(y_true, y_pred, gamma=2, from_logits=True)
model = tf.keras.Model(inputs=inputs, outputs=[out1, out2])
model = create_model(encoding_size)
model.compile(
optimizer=tf.keras.optimizers.Adam(learning_rate=learning_rate),
loss={'out1': tf.keras.losses.BinaryCrossentropy(), "out2": focal_loss},
loss_weights={'out1': 0.5, "out2": 0.5},
metrics=["accuracy"
# tf.keras.metrics.SparseCategoricalAccuracy(name="accuracy"),
# tf.keras.metrics.AUC(name="auc")
]
)
参考:https://stackoverflow.com/questions/44151760/received-a-label-value-of-1-which-is-outside-the-valid-range-of-0-1-python



