我有以下代碼:
a = tf.constant([[10],
[0],
[4]])
s = tf.sparse.from_dense(a)
b = tf.constant([[3, 4],
[1, 2],
[2, 5]])
# print(tf.multiply(s, b)) # this didn't work either though it works if s is dense
print(s.__mul__(b))
我想將 a 與 b 的每一列相乘得到:
[[30, 40],
[ 0, 0],
[ 8, 20]]
但是上面的代碼給了我一個錯誤,即無法廣播稀疏張量以使形狀匹配。
tensorflow.python.framework.errors_impl.InvalidArgumentError: SparseDenseBinaryOpShared broadcasts dense to sparse only; got incompatible shapes: [3,1] vs. [3,2] [Op:SparseDenseCwiseMul]
如何在不將稀疏張量 a 變為密集張量的情況下有效地實作上述目標?
uj5u.com熱心網友回復:
不確定這有多有效以及它是否適合您,但您可以嘗試使用tf.TensorArraywith tf.sparse.sparse_dense_matmul:
import tensorflow as tf
a = tf.constant([[10],
[0],
[4]])
s = tf.sparse.from_dense(a)
b = tf.constant([[3, 4],
[1, 2],
[2, 5]])
ta = tf.TensorArray(dtype=tf.int32, size=0, dynamic_size=True)
for i in range(len(b)):
if i == len(b):
ta = ta.write(ta.size(), tf.sparse.sparse_dense_matmul(s, b[i:])[i])
else:
ta = ta.write(ta.size(), tf.sparse.sparse_dense_matmul(s, b[i:i 1])[i])
print(ta.stack())
tf.Tensor(
[[30 40]
[ 0 0]
[ 8 20]], shape=(3, 2), dtype=int32)
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/372849.html
