Python Tensorflow中张量的逐行处理
我正在测试代码,以便逐行处理张量 张量可以有最后4个元素为0或非零值的行 如果行的最后4个元素为0[1.0,2.0,2.3,3.4,0,0,0] 最后四个元素将被删除,形状将更改为行中的5个元素。 第一个元素表示行索引。它变得像[0.0,1.0,2.0,2.3,3.4] 如果该行包含所有8个非零值元素,则将其拆分为两行,并将行索引放在第一位。然后Python Tensorflow中张量的逐行处理,python,tensorflow,tensor,Python,Tensorflow,Tensor,我正在测试代码,以便逐行处理张量 张量可以有最后4个元素为0或非零值的行 如果行的最后4个元素为0[1.0,2.0,2.3,3.4,0,0,0] 最后四个元素将被删除,形状将更改为行中的5个元素。 第一个元素表示行索引。它变得像[0.0,1.0,2.0,2.3,3.4] 如果该行包含所有8个非零值元素,则将其拆分为两行,并将行索引放在第一位。然后[3.0,4.0,1.0,2.1,1.2,1.4,1.2,1.5]变得像[2.0,3.0,4.0,1.0,2.1],[2.0,1.2,1.4,1.2,1
[3.0,4.0,1.0,2.1,1.2,1.4,1.2,1.5]
变得像[2.0,3.0,4.0,1.0,2.1],[2.0,1.2,1.4,1.2,1.5]
。第一个元素2.0是以张量表示的行索引
所以经过处理,
[[1.0,2.0,2.3,3.4,0,0,0,0],[2.0,3.2,4.2,4.0,0,0,0,0],[3.0,4.0,1.0,2.1,1.2,1.4,1.2,1.5],[1.2,1.3,3.4,4.5,1,2,3,4]
[[0,1.0,2.0,2.3,3.4],[1.0,2.0,3.2,4.2,4.0],[2.0,3.0,4.0,1.0,2.1],[2.0,1.2,1.4,1.2,1.5],[3.0,1.2,1.3,3.4,4.5],[3.0,1,2,3,4]]
我照做了。但是错误为TypeError:TypeErro…pected',)在map\u fn
import tensorflow as tf
boxes = tf.constant([[1.0,2.0,2.3,3.4,0,0,0,0],[2.0,3.2,4.2,4.0,0,0,0,0],[3.0,4.0,1.0,2.1,1.2,1.4,1.2,1.5],[1.2,1.3,3.4,4.5,1,2,3,4]])
rows = tf.expand_dims(tf.range(tf.shape(boxes)[0], dtype=tf.int32), 1)
def bbox_organize(box, i):
if(tf.reduce_sum(box[4:]) == 0):
box=tf.squeeze(box, [5,6,7]
box=tf.roll(box, shift=1, axis=0)
box[0]=i
else:
box=tf.reshape(box, [2, 4])
const_=tf.constant(i, shape=[2, 1])
box=tf.concat([const_, box], 0)
return box
b_boxes= tf.map_fn(lambda x: (bbox_organize(x[0], x[1]), x[1]), (boxes, rows), dtype=(tf.int32, tf.int32))
with tf.Session() as sess: print(sess.run(b_boxes))
我不擅长Tensorflow,还在学习
有没有更好的方法实现Tensorflow API来处理它?您需要做的是变换
框的形状,并获得非零行
import tensorflow as tf
tf.enable_eager_execution();
boxes = tf.constant([[1.0,2.0,2.3,3.4,0,0,0,0],[2.0,3.2,4.2,4.0,0,0,0,0],[3.0,4.0,1.0,2.1,1.2,1.4,1.2,1.5],[1.2,1.3,3.4,4.5,1,2,3,4]])
boxes = tf.reshape(boxes,[tf.shape(boxes)[0]*2,-1])
# [[1. 2. 2.3 3.4]
# [0. 0. 0. 0. ]
# [2. 3.2 4.2 4. ]
# [0. 0. 0. 0. ]
# [3. 4. 1. 2.1]
# [1.2 1.4 1.2 1.5]
# [1.2 1.3 3.4 4.5]
# [1. 2. 3. 4. ]]
rows = tf.floor(tf.expand_dims(tf.range(tf.shape(boxes)[0]), 1)/2)
# [[0.]
# [0.]
# [1.]
# [1.]
# [2.]
# [2.]
# [3.]
# [3.]]
add_index = tf.concat([tf.cast(rows,tf.float32),boxes],-1)
index = tf.not_equal(tf.reduce_sum(add_index[:,4:],axis=1),0)
# [ True False True False True True True True]
boxes_ = tf.gather_nd(add_index,tf.where(index))
print(boxes_)
# tf.Tensor(
# [[0. 1. 2. 2.3 3.4]
# [1. 2. 3.2 4.2 4. ]
# [2. 3. 4. 1. 2.1]
# [2. 1.2 1.4 1.2 1.5]
# [3. 1.2 1.3 3.4 4.5]
# [3. 1. 2. 3. 4. ]], shape=(6, 5), dtype=float32)
我想你更需要上面的代码。矢量化方法将大大快于tf.map\u fn()