在循环内修改 Tensorflow 变量 [英] Modify a Tensorflow Variable inside a loop

查看:43
本文介绍了在循环内修改 Tensorflow 变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 while 循环中修改某个变量的某些索引.基本上将下面的python代码转换为Tensorflow:

I would like to modify certain indexes of a Variable inside a while loop. Basically convert the python code below to Tensorflow:

import numpy
tf_variable=numpy.zeros(10,numpy.int32)
for i in range (10):
    tf_variable[i]=i
tf_variable

Tensorflow 代码如下所示:除非它给出错误

Tensorflow code would look like following: except it gives error

import tensorflow as tf
var=tf.get_variable('var',initializer=tf.zeros([10],tf.int32),trainable=False)
itr=tf.constant(0)
sess=tf.Session()
sess.run(tf.global_variables_initializer()) #initializing variables


print('itr=',sess.run(itr))
def w_c(itr,var):
    return(tf.less(itr,10))
def w_b(itr,var):
    var=tf.assign(var[1],9) #lets say i want to modify index 1 of variable var
    itr=tf.add(itr,1)
    return [itr,var] #these tensors when returning actually get called


OP=tf.while_loop(w_c,w_b,[itr,var],parallel_iterations=1,back_prop=False)
print(sess.run(OP))

谢谢

推荐答案

在 CPU 上绕道而行"并不总是可行的(您会丢失渐变).这是如何在 TensorFlow 中实现您的 numpy 示例的可能性(灵感来自 这篇文章 以及我在 另一个帖子)

Making a "detour" over the CPU is not always feasible (you lose the gradients). Here is a possibility how to implement your numpy example in TensorFlow (inspired by this post and an answer I gave on this other post)

import tensorflow as tf

tf_variable = tf.Variable(tf.ones([10]))

def body(i, v):
    index = i
    new_value = tf.to_float(i)
    delta_value = new_value - v[index:index+1]
    delta = tf.SparseTensor([[index]], delta_value, (10,))
    v_updated = v + tf.sparse_tensor_to_dense(delta)
    return tf.add(i, 1), v_updated


_, updated = tf.while_loop(lambda i, _: tf.less(i, 10), body, [0, tf_variable])

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    print(sess.run(tf_variable))
    print(sess.run(updated))

打印出来

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

这篇关于在循环内修改 Tensorflow 变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆