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