在会话中具有循环的递归更新张量

时间:2019-04-29 08:30:44

标签: python tensorflow

必须在不将其保存到python的情况下更新张量。

我想要得到:

[array([2.], dtype=float32), array([2.], dtype=float32)]
[array([2.], dtype=float32), array([4.], dtype=float32)]
[array([2.], dtype=float32), array([16.], dtype=float32)]
[array([2.], dtype=float32), array([65536.], dtype=float32)]

但是我得到了

[array([2.], dtype=float32), array([2.], dtype=float32)]
[array([2.], dtype=float32), array([2.], dtype=float32)]
[array([2.], dtype=float32), array([2.], dtype=float32)]
[array([2.], dtype=float32), array([2.], dtype=float32)]

我的代码:

import tensorflow as tf
inp = tf.placeholder(tf.float32,[None])
def ret(x, y):
    return x, tf.pow(x, y)
try:
    x, y = ret(inp,y)
except:
    x, y = ret(inp, tf.Variable([1.]))

sess = tf.Session()

sess.run(tf.global_variables_initializer())

for i in range(4):
    print (sess.run([x,y],{inp: [2.]}))

对不起,错误地描述了我的问题。 实际上,ret函数的代码略有不同。

def ret(inputs, compare_vectors=tf.Variable([])):
    boxes = tf.Variable(np.random.uniform(0,1,(10,4)).astype(np.float32))
    box_ind = tf.Variable(np.zeros([10],dtype=np.int))
    crop_size= tf.Variable([24,24])
    crop_boxes = tf.image.crop_and_resize(inputs, boxes, box_ind, crop_size)
    crop_boxes = tf.reshape(crop_boxes,[crop_boxes.get_shape().as_list()[0], 24,24,3])
    with slim.arg_scope(get_futures_maps_arg_scope()):
        future_maps, _ = get_futures_maps(crop_boxes, is_training = False)
    rows = tf.unstack(compare_vectors) 
    column = tf.unstack(future_maps) 
    result = tf.ones(shape=[len(rows), len(column)])
    for i, row in enumerate(rows):
        for j, future in enumerate(column):
            result[i,j]=tf.losses.cosine_distance(row, future)
    compare_vectors = future_maps

    return crop_boxes, boxes, future_maps, result

主要问题是结果总是看起来像[],但我在第二,第三和第四步中需要[10,10]

主要功能:

compare_vectors = None
if compare_vectors is None:
    crop_boxes, boxes, compare_vectors, result = ret(inputs)
else:
    crop_boxes, boxes, compare_vectors, result = ret(inputs, compare_vectors)

我更改代码:

import tensorflow as tf
import numpy as np
inp = tf.placeholder(tf.float32,shape=[10, 10])
test_shape_var = tf.Variable(np.ones([0,10], dtype=np.float32))
def ret(x, y):
    len_var = tf.fill([len(tf.unstack(y))], -1)
    return len_var
x = inp-1.
test_len_var = ret(x, test_shape_var)
update_shape_var = tf.assign(test_shape_var, x, validate_shape=False)
sess = tf.Session()
sess.run(tf.global_variables_initializer())
for i in range(10):
    x_, y_ = sess.run([test_len_var,test_shape_var],{inp: np.random.uniform(0,1, [10, 10])})
    sess.run(update_shape_var, {inp: np.random.uniform(0,1, [10, 10])})
    print (x_.shape, y_.shape)

但是我不知道为什么不更新函数“ ret”中的vars

最后一个代码计算张量x的两倍。

在原始代码中,需要更新矩阵大小“结果”

对不起,我的英语-这不是我的母语

0 个答案:

没有答案