简体   繁体   English

如何在Tensorflow中操作变量

[英]How to manipulate Variables in Tensorflow

I want to do something as simple as this a = a + b , example code as follow 我想做这样简单的事情a = a + b ,示例代码如下

sess = tf.InteractiveSession()

embed = tf.Variable(tf.random_uniform([10, 2], -1, 1))

saver = tf.train.Saver([embed])
saver.restore(sess, 'save/model.ckpt')

new_embed = tf.Variable(tf.random_uniform([5, 2], -1, 1))

init = tf.initialize_variables([new_embed])
sess.run(init)

embed = tf.Variable(tf.concat(0, [embed, new_embed]))

However the last line won't execute because embed becomes an uninitialized value. 但是,最后一行将不会执行,因为embed变为未初始化的值。

What I wish to accomplish here is to restore a variable from a file and concat with a new variable, ie make the [10, 2] variable to be a [15, 2] variable, where the first 10 rows are from the stored variable. 我想在这里完成的工作是从文件中还原变量,并用新变量concat进行连接,即使[10,2]变量成为[15,2]变量,其中前10行来自存储的变量。

I was thinking to restore the [10, 2] variable to a new variable say old_ebmed , but I couldn't find a way to do so. 我正在考虑将[ old_ebmed ]变量恢复为一个新变量,例如old_ebmed ,但是我找不到办法。

Any help would be appreciated. 任何帮助,将不胜感激。

I found a way to restore the variable to a varialbe with a different name 我找到了一种将变量还原为具有不同名称的varialbe的方法

import tensorflow as tf

sess = tf.InteractiveSession()

old_embed = tf.Variable(tf.constant(0.0, shape = [10, 2]))

restorer = tf.train.Saver({'embed': old_embed})
restorer.restore(sess, 'test/d.ckpt')

new_embed = tf.Variable(tf.random_uniform([5, 2], -1, 1))

init_new = tf.initialize_variables([new_embed])
sess.run(init_new)

embed = tf.Variable(tf.concat(0, [old_embed, new_embed]))
init_embed = tf.initialize_variables([embed])
sess.run(init_embed)

saver = tf.train.Saver({'embed': embed})
saver.save(sess, 'test/d.ckpt')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM