在循环内修改 Tensorflow 变量

编程入门 行业动态 更新时间:2024-10-07 18:20:19
本文介绍了在循环内修改 Tensorflow 变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我想在 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屋!

更多推荐

[db:关键词]

本文发布于:2023-05-01 01:48:57,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1402417.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:变量   Tensorflow

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!