对tensorflow中的tensor,如程序中的fliping_points向量中的数据,每隔一个数字被1减一次.即1-fliping_points[0],1-fliping_points[2]....., 其余数字不发生变化
import tensorflow as tf
import numpy as np
import collections
fliping_points0 =np.array([[['320', '124.425'], ['328', '147'], ['304', '156'], ['296', '133.425']], [['346', '123.8'], ['332', '131'], ['326', '119'], ['340', '111.8']], [['357', '145.6'], ['347', '126'], ['321', '139'], ['331', '158.6']]])
fliping_points1 = fliping_points0.flatten()
fliping_points = tf.string_to_number(fliping_points1,out_type=tf.float32)
var_t = tf.constant(0, dtype=tf.int32)
# cond = lambda i: tf.less(i, 5)
def condition(i):
conda = tf.cond(tf.equal(i % 2, 0), lambda: tf.subtract(1.0, tf.cast(fliping_points[i], dtype=tf.float32)),
lambda: tf.cast(fliping_points[i], dtype=tf.float32))
return conda
cond = lambda i: tf.less(i,5)
image = lambda i,: (i+1,condition(i))
f= tf.while_loop(cond=cond, body=image,loop_vars=[var_t])
with tf.Session() as sess:
k = sess.run(f)
print(k)
粗暴方法之一
import tensorflow as tf
import numpy as np
fliping_points0 =np.array([[['320', '124.425'], ['328', '147'], ['304', '156'], ['296', '133.425']], [['346', '123.8'], ['332', '131'], ['326', '119'], ['340', '111.8']], [['357', '145.6'], ['347', '126'], ['321', '139'], ['331', '158.6']]])
fliping_points1 = fliping_points0.flatten()
fliping_points = tf.string_to_number(fliping_points1,out_type=tf.float32)
v = tf.reshape(fliping_points,[-1,2])
vv =tf.transpose(v,[1,0])
vvv = 1.0-vv[0]
ccc = [vvv,vv[1]]
cc = tf.stack(ccc)
cc = tf.transpose(cc,[1,0])
cc = tf.reshape(cc,[-1])
with tf.Session() as sess:
f=sess.run(cc)
print(f)
fff = sess.run(fliping_points)
print(fff)
2.while_loop 循环添加张量维度的方法
import tensorflow as tf
i0 = tf.constant(0)
m0 = tf.ones([2, 2])
mm = tf.ones([2,2])*10
c = lambda i, m,d: i < 10
b = lambda i, m,d: [i+1,m, tf.concat([d, m], axis=0)]
d,f,kk=tf.while_loop(
c, b, loop_vars=[i0, m0,mm],
shape_invariants=[i0.get_shape(), m0.get_shape(),tf.TensorShape([None, 2])])
# e,e1,e2 =sess.run([a1,b1,c])
with tf.Session() as sess:
aa = sess.run(kk)
print(aa)
输出结果为:
[[10. 10.]
[10. 10.]
[ 1. 1.]
[ 1. 1.]
[ 1. 1.]
[ 1. 1.]
[ 1. 1.]
[ 1. 1.]
[ 1. 1.]
[ 1. 1.]
[ 1. 1.]
[ 1. 1.]
[ 1. 1.]
[ 1. 1.]
[ 1. 1.]
[ 1. 1.]
[ 1. 1.]
[ 1. 1.]
[ 1. 1.]
[ 1. 1.]
[ 1. 1.]
[ 1. 1.]]
3.
index = tf.constant(0)
selected_bb = tf.reshape(tf.constant([],dtype=tf.float32),[-1,4])
all_step = tf.reduce_sum(tf.cast(Selected_mask, dtype=tf.int32))
def condition(index,all_step,last_bboxes,selected_bb):
return tf.less(index,all_step)
def body(index,all_step,last_bboxes,selected_bb):
bb = tf.expand_dims(last_bboxes[index],axis=0)
selected_bb = tf.concat([selected_bb,bb],axis=0)
return index+1,all_step,last_bboxes,selected_bb
[index, all_step,last_bboxes, selected_bb] = \
tf.while_loop(condition,body,[index,all_step,last_bboxes,selected_bb],
shape_invariants=[index.get_shape(),all_step.get_shape(),last_bboxes.get_shape(),tf.TensorShape([None,4])])
s = tf.expand_dims(selected_bb,axis=0)
predictions={'sum':s}