>> A = tf.Tensor([4135047. 1193752.], shape=(2,), dtype=float32)
>> B = tf.Tensor(
[1226019. 4135047. 4135047. 4169911. 1193752. 4135047. 4135047. 4135047.],
shape=(8,), dtype=float32
)
>> compare_1 = tf.math.equal(B, A[0])
tf.Tensor([False True True False False True True True], shape=(8,), dtype=bool)
>> compare_2 = tf.math.equal(B, A[1])
tf.Tensor([False False False False True False False False], shape=(8,), dtype=bool)
# final results
>> tf.math.logical_or(compare_1, compare_2)
tf.Tensor([False True True False True True True True], shape=(8,), dtype=bool)
我想要的是在不使用tf.map()函式的情況下一次比較兩個不同形狀的張量。
更準確地說,我想將 的每個元素tensor B與 的所有元素進行比較tensor A。tensor A如果來自的任何元素與我們要比較的元素匹配,則結果應設定為 Truetensor B
預期結果:
>> compare(B, A)
tf.Tensor([False True True False True True True True])
# logic:
- 1st element from B, 1226019 doesn't match with any elements of A => False
- 2nd element from B, 4135047 match with an element in A => True
...
...
...
看起來tf.math.equal無法比較兩個不同形狀的張量,所以現在我必須在 n-pass(對于張量 A 的每個元素)中將它與張量 B 進行比較,然后將其logical_or()應用于這些結果。
uj5u.com熱心網友回復:
重新表述您的問題(以一種我覺得更容易理解的方式),您似乎想要一個與 B 長度相同的一維張量,True如果相應的元素B出現在其中,則其元素為A假,否則為假。
假設我理解正確,這是獲得此結果的一種方法。請注意,因為我替換logical_or為reduce_any,所以這種方法可以應用于陣列A和B任意長度。請注意,這只適用于A并且B是一維陣列時。
import tensorflow as tf
A = tf.constant([4135047., 1193752.])
B = tf.constant([1226019., 4135047., 4135047., 4169911., 1193752., 4135047., 4135047., 4135047.])
m = len(A)
n = len(B)
result = tf.math.reduce_any(
tf.math.equal(
tf.broadcast_to(A[:,None],[m,n]),tf.broadcast_to(B,[m,n])
), axis = 0
)
print(result)
結果:
tf.Tensor([False True True False True True True True], shape=(8,), dtype=bool)
uj5u.com熱心網友回復:
從根本上說,它的作用沒有區別。但是你可以讓代碼比其他答案更干凈。
c = tf.math.reduce_any(B[:, None]==A[None, :], axis=1)
回傳,
tf.Tensor([False True True False True True True True], shape=(8,), dtype=bool)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/520890.html
標籤:Python张量流
上一篇:無法在docker容器中加載動態庫“libcudart.so.11.0”
下一篇:LSTM模型的所有預測值幾乎相同
