我有一个满足需求的损失函数,但它只在PyTorch中。我需要将其实现到我的TensorFlow代码中,尽管大部分内容可以简单地“翻译”,但我在一行上遇到了困难:
y_hat[:, torch.arange(N), torch.arange(N)] = torch.finfo(y_hat.dtype).max # to be "1" after sigmoid
你可以在下面的代码中看到全部内容,除了那行之外确实非常简单:
def get_loss(y_hat, y): # No loss on diagonal B, N, _ = y_hat.shape y_hat[:, torch.arange(N), torch.arange(N)] = torch.finfo(y_hat.dtype).max # to be "1" after sigmoid # calc loss loss = F.binary_cross_entropy_with_logits(y_hat, y) # cross entropy y_hat = torch.sigmoid(y_hat) tp = (y_hat * y).sum(dim=(1, 2)) fn = ((1. - y_hat) * y).sum(dim=(1, 2)) fp = (y_hat * (1. - y)).sum(dim=(1, 2)) loss = loss - ((2 * tp) / (2 * tp + fp + fn + 1e-10)).sum() # fscorereturn loss
到目前为止,我想到的是以下内容:
def get_loss(y_hat, y): loss = tf.keras.losses.BinaryCrossentropy()(y_hat,y) # cross entropy (but no logits) y_hat = tf.math.sigmoid(y_hat) tp = tf.math.reduce_sum(tf.multiply(y_hat, y),[1,2]) fn = tf.math.reduce_sum((y - tf.multiply(y_hat, y)),[1,2]) fp = tf.math.reduce_sum((y_hat -tf.multiply(y_hat,y)),[1,2]) loss = loss - ((2 * tp) / tf.math.reduce_sum((2 * tp + fp + fn + 1e-10))) # fscorereturn loss
所以我的问题归结为:
torch.finfo()
做什么以及如何在TensorFlow中表达它?y_hat.dtype
只是返回数据类型吗?
回答:
1. torch.finfo()
做什么以及如何在TensorFlow中表达它?
.finfo()
提供了一种获取浮点类型机器极限的简便方法。这个函数在Numpy、Torch以及Tensorflow实验版中都可用。
.finfo().max
返回该数据类型可表示的最大可能数值。
注意:对于整数类型,也有.iinfo()
函数。
以下是finfo
和iinfo
的几个示例:
print('FLOATS')print('float16',torch.finfo(torch.float16).max)print('float32',torch.finfo(torch.float32).max)print('float64',torch.finfo(torch.float64).max)print('')print('INTEGERS')print('int16',torch.iinfo(torch.int16).max)print('int32',torch.iinfo(torch.int32).max)print('int64',torch.iinfo(torch.int64).max)
FLOATSfloat16 65504.0float32 3.4028234663852886e+38float64 1.7976931348623157e+308INTEGERSint16 32767int32 2147483647int64 9223372036854775807
如果你想在TensorFlow中实现这个功能,可以使用tf.experimental.numpy.finfo
来解决这个问题。
print(tf.experimental.numpy.finfo(tf.float32))print('Max ->',tf.experimental.numpy.finfo(tf.float32).max) #<---- THIS IS WHAT YOU WANT
Machine parameters for float32---------------------------------------------------------------precision = 6 resolution = 1.0000000e-06machep = -23 eps = 1.1920929e-07negep = -24 epsneg = 5.9604645e-08minexp = -126 tiny = 1.1754944e-38maxexp = 128 max = 3.4028235e+38nexp = 8 min = -max---------------------------------------------------------------Max -> 3.4028235e+38
2. y_hat.dtype
只是返回数据类型吗?
是的。
在torch中,它会返回torch.float32
或类似的东西。在TensorFlow中,它会返回tf.float32
或类似的东西。