tensorflow 小記——如何對張量做任意行求和,得到新tensor(一種方法:列表生成式)


希望實現圖片上的功能

 

 

import tensorflow as tf
a = tf.range(10,dtype=float)
b = a
a = tf.reshape(a,[-1,1])
a = tf.tile(a,[1,3])

sess = tf.Session()
print(sess.run(b))
print(sess.run(a))

[0. 1. 2. 3. 4. 5. 6. 7. 8. 9.]
[[0. 0. 0.]
[1. 1. 1.]
[2. 2. 2.]
[3. 3. 3.]
[4. 4. 4.]
[5. 5. 5.]
[6. 6. 6.]
[7. 7. 7.]
[8. 8. 8.]
[9. 9. 9.]]


有沒有什么方法讓10*3這個tensor,每三行相加?

解答圖片的問題:

tensorflow方法如下:

import tensorflow as tf
a = tf.range(10,dtype=float)
b = a
a = tf.reshape(a,[-1,1])
a = tf.tile(a,[1,3])


c = tf.convert_to_tensor([a[i] if i<=1 else tf.reduce_sum(a[i-2:i+1],0)/3 +a[i] for i in range(a.shape[0])])        
        
sess = tf.Session()
print(sess.run(b))
print(sess.run(a))
print(sess.run(c))

 

 

pytorch方法大致如下:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM