我知道有tf.keras.metrics.Precision()
,tf.keras.metrics.TruePositives()
,tf.keras.metrics.FalsePositives()
.但是如何在自定义指标函数中实现这些内置指标的输出?下面是我的工作代码:
import tensorflow_addons as tfa
import tensorflow as tf
import autokeras as ak
def f1_loss(y_true, y_pred): # not coded by me
tp = K.sum(K.cast(y_true*y_pred, 'float'), axis=0)
tn = K.sum(K.cast((1-y_true)*(1-y_pred), 'float'), axis=0)
fp = K.sum(K.cast((1-y_true)*y_pred, 'float'), axis=0)
fn = K.sum(K.cast(y_true*(1-y_pred), 'float'), axis=0)
p = tp / (tp + fp + K.epsilon())
r = tp / (tp + fn + K.epsilon())
f1 = 2*p*r / (p+r+K.epsilon())
f1 = tf.where(tf.math.is_nan(f1), tf.zeros_like(f1), f1)
return 1- K.mean(f1)
length=100000;WIDTH = 3; HEIGHT=3;CLASSES=2
X=np.random.random((length,HEIGHT,WIDTH)).astype(np.float32)
Y_float=np.ones((length,CLASSES)).astype(np.float32)
for i in range (length):
Y_float[i]=np.array([np.mean( X[i]),np.mean( X[i])/2])
Y_binary= (Y_float>=0.5).astype(np.int32)
input_node = ak.Input()
output_node=ak.DenseBlock()(input_node)
Classification_output = ak.ClassificationHead(loss=f1_loss,metrics=[tfa.metrics.F1Score(num_classes=2),
tf.keras.metrics.TruePositives(), tf.keras.metrics.FalsePositives()],multi_label=True)(output_node)
auto_model= ak.AutoModel( inputs=[input_node], outputs=[Classification_output], max_trials=1,overwrite=True)
ak_history=auto_model.fit(x=[X],y=Y_binary,validation_split=0.2 )
搜索最好的模型和训练是非常好的,尽管f1_loss
永远不等于tfa.metrics.F1Score
或1-tfa.metrics.F1Score
。真正的问题是,我需要添加一个指标,可以在以后搜索最好的模型时使用。
def diff(y_true, y_pred): # the new custom metric I would like to add
d=tf.keras.metrics.TruePositives()- tf.keras.metrics.FalsePositives()
return d
现在,如果更新指标是
metrics=[diff,tfa.metrics.F1Score(num_classes=2),tf.keras.metrics.TruePositives(), tf.keras.metrics.FalsePositives()]
我得到了错误:
TypeError: in user code:
/opt/conda/lib/python3.7/site-packages/keras/engine/training.py:853 train_function *
return step_function(self, iterator)
/tmp/ipykernel_33/1113116857.py:16 diff *
d=tf.keras.metrics.TruePositives()- tf.keras.metrics.FalsePositives()
TypeError: unsupported operand type(s) for -: 'TruePositives' and 'FalsePositives'
2条答案
按热度按时间9gm1akwq1#
您可以编写一个
function
来计算TP - FP
的自定义丢失,如下所示:输出:
lyfkaqu12#
自定义度量here适合我的要求。