import tensorflow.kera.backend as K
tf.multiply
和*
有什么区别?
类似地,K.pow(x, -1)
和1/x
有什么区别?
我根据其他代码编写了以下自定义指标函数的代码。
def dice_coef_weight_sub(y_true, y_pred):
"""
Returns the product of dice coefficient for each class
"""
y_true_f = (Lambda(lambda y_true: y_true[:, :, :, :, 0:])(y_true))
y_pred_f = (Lambda(lambda y_pred: y_pred[:, :, :, :, 0:])(y_pred))
product = tf.multiply([y_true_f, y_pred_f]) # multiply should be import from tf or tf.math
red_y_true = K.sum(y_true_f, axis=[0, 1, 2, 3]) # shape [None, nb_class]
red_y_pred = K.sum(y_pred_f, axis=[0, 1, 2, 3])
red_product = K.sum(product, axis=[0, 1, 2, 3])
smooth = 0.001
dices = (2. * red_product + smooth) / (red_y_true + red_y_pred + smooth)
ratio = red_y_true / (K.sum(red_y_true) + smooth)
ratio = 1.0 - ratio
# ratio = K.pow(ratio + smooth, -1.0) # different method to get ratio
return K.sum(multiply([dices, ratio]))
在代码中,我可以将tf.multiply
替换为*
吗?我可以将K.pow(x,-1)
替换为1/x
吗?
(从tensorflow的文档中,我知道tf.pow
和K.pow
之间的区别:tf.pow(x,y)
接收2个张量来计算x
和{{ 1}},而y
接收张量K.pow(x,a)
和整数x
来计算x ^ a,但我不知道为什么上面的代码a
接收浮点数1.0,仍然可以正常使用)
答案 0 :(得分:1)
假设*
的两个操作数都是tf.Tensor
而不是tf.sparse.SparseTensor
,则*
运算符与tf.multiply
相同,即按元素广播支持。
如果您有兴趣研究执行运算符重载的源代码,则关键部分包括:
对于tf.sparse.SparseTensor
s,*
的稀疏特定于张量的乘法运算会过载。
假设您使用的是Python3,/
运算符将重载到tf.math.truediv
(即浮点除法,它对应于TensorFlow的RealDiv
op)。
在Python2中,/
运算符可能正在执行整数除法,在这种情况下,它会以与dtype相关的方式重载。对于浮动dtype,它是tf.math.truediv
,对于整数dtype,它是tf.math.floordiv
(整数下限)。
tf.pow()
使用其他运算符(即Pow
)运算符。但是,假设您所有的dtypes是浮点数,则1 / x
和tf.pow(x, -1.0)
应该等效。