簡體   English   中英

`tf.multiply` 和 `*` 有什么區別?

[英]what is the difference between `tf.multiply` and `*`?

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嗎? 我可以用1/x替換K.pow(x,-1)嗎??

(從tensorflow的文檔,我知道之間的差tf.powK.powtf.pow(x,y)接收2張量將計算的x ^ y表示相應的元素xy ,而K.pow(x,a)接收一個張量x和一個整數a來計算 x^a。但我不知道為什么在上面的代碼中K.pow收到一個浮點數 1.0 並且它仍然正常工作)

假設*的兩個操作數都是tf.Tensor s 而不是tf.sparse.SparseTensor s , *運算符與tf.multiply相同,即具有廣播支持的元素乘法。

如果您有興趣研究執行運算符重載的源代碼,關鍵部分是:

  1. https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/ops/math_ops.py#L891
  2. https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/ops/math_ops.py#L1225
  3. https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/ops/math_ops.py#L1201

對於tf.sparse.SparseTensor s, *被稀疏張量特定的乘法操作重載。

假設您使用的是 Python3, /運算符重載到tf.math.truediv (即浮點除法,對應於 TensorFlow 的RealDiv運算)。

在 Python2 中, /運算符可能正在執行整數除法,在這種情況下,它以依賴於 dtype 的方式重載。 對於浮動數據類型,它是tf.math.truediv ,對於整數數據類型,它是tf.math.floordiv (整數除法)。

tf.pow()使用不同的運算符(即Pow )運算符。 但假設你所有的 dtypes 都是浮點型, 1 / xtf.pow(x, -1.0)應該是等價的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM