我試圖在我的張量中獲取每個單獨樣本的 MeanSquaredError。
這是一些示例代碼來顯示我的問題。
src = np.random.uniform(size=(2, 5, 10))
tgt = np.random.uniform(size=(2, 5, 10))
srcTF = tf.convert_to_tensor(src)
tgtTF = tf.convert_to_tensor(tgt)
print(srcTF, tgtTF)
lf = tf.keras.losses.MeanSquaredError(reduction=tf.compat.v1.losses.Reduction.NONE)
flowResults = lf(srcTF, tgtTF)
print(flowResults)
結果如下:
(2, 5, 10) (2, 5, 10)
(2, 5)
我想保留張量的所有原始尺寸,只計算單個樣本的損失。有沒有辦法在 Tensorflow 中做到這一點?請注意,pytorch 的 torch.nn.MSELoss(reduction = 'none') 完全符合我的要求,那么有沒有更類似的替代方法?
uj5u.com熱心網友回復:
這是一種方法:
[ins] In [97]: mse = tf.keras.losses.MSE(tf.expand_dims(srcTF, axis=-1) , tf.expand_dims(tgtTF, axis=-1))
[ins] In [98]: mse.shape
Out[98]: TensorShape([2, 5, 10])
我認為這里的關鍵是樣本。由于 MSE 是在最后一個軸上計算的,因此您會丟失該軸,因為這就是“減少”的內容。該五維向量中的每個點代表最后一個軸中 10 維的均方誤差。因此,為了恢復原始形狀,本質上,我們必須對每個標量進行 MSE,為此我們需要擴展維度。本質上,我們說 (2, 5, 10) 是我們擁有的批次數,每個標量是我們的樣本/預測,這就是 tf.expand_dims(<tensor>, -1) 完成的。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/464832.html
