tensorflow - 如何用变量名更新 tf.variable_scope 中的变量?
问题描述
我想修改 tf.variable_scope 中关于变量“weight1”的值。
我尝试通过其他功能修改该值,但跟随我它不起作用。
def inference(q, reuse=False):
with tf.variable_scope('layer1', reuse = reuse):
x = tf.get_variable('weight1', [1, 3], initializer = tf.truncated_normal_initializer(stddev = 0.1))
y = tf.get_variable('weight2', [3, 1], initializer = tf.constant_initializer([[1],[2],[3]]))
return tf.matmul(x, y)
def update_process(reuse=True):
with tf.variable_scope('layer1', reuse = reuse):
x = tf.get_variable('weight1',[1, 3])
update=tf.assign(x, x-1)
with tf.Session() as sess:
sess.run(init)
print(sess.run(x))
init = tf.global_variables_initializer()
z = inference(1)
with tf.Session() as sess:
sess.run(init)
for i in range(5):
update_process(reuse = True)
print(sess.run(z))
print('\n')
我希望此代码输出有关 sess.run(z) 的不同列表,但值始终相同。
解决方案
您需要在图形部分运行sess.run(update)
的update_process
同一会话中运行:inference
import tensorflow as tf
def inference(q, reuse=False):
with tf.variable_scope('layer1', reuse = reuse):
x = tf.get_variable('weight1', [1, 3], initializer = tf.truncated_normal_initializer(stddev = 0.1))
y = tf.get_variable('weight2', [3, 1], initializer = tf.constant_initializer([[1],[2],[3]]))
return tf.matmul(x, y)
def update_process(reuse=True):
with tf.variable_scope('layer1', reuse = reuse):
x = tf.get_variable('weight1',[1, 3])
update=tf.assign(x, x-1)
print(sess.run(update))
z = inference(1)
init = tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init)
for i in range(5):
update_process(reuse = True)
print(sess.run(z))
print('\n')
推荐阅读
- ruby-on-rails - 如何通过可执行文件运行我的 ruby on rails 项目?
- python - Python 3.x - 如何从需要参数的函数中返回值
- google-colaboratory - 当我在 colab 上运行 fairseq 命令行结构时,我总是得到“返回非零退出状态 2”
- excel - Excel AverageIF:平均给定类型的前 X 个单元格
- qt - 如何使用 PyQt 中的样式表将小部件置于前面?
- r - 读取具有多个分隔符的 txt 文件
- javascript - 如何在 oracle apex 18 中编辑交互式网格(带有复杂的 sql 查询)?
- lua - 为什么在遍历表时会出现这种“尝试调用表值”?
- scala - @Scheduled 的 SpringIO 不能在 scala 中工作?
- python - 有没有办法将小时 '' 1-5-6 '' 变成 '' 01-05-06 " ?(只是一个例子)