首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >tf.identity在赋值前不复制值

tf.identity在赋值前不复制值
EN

Stack Overflow用户
提问于 2019-09-19 14:49:38
回答 1查看 57关注 0票数 2

我希望这个程序

  1. x的旧值复制到tf.identity
  2. 将新值y赋给x

但是tf.identity没有保留x的旧值。

tf.control_dependencies应该要求在步骤2之前执行步骤1。

结果:

代码语言:javascript
运行
复制
version: 1.14.1-dev20190531
x_before_: 0.0
x_ident_: 1.0
x_after_: 1.0

测试:

代码语言:javascript
运行
复制
import numpy as np
import tensorflow as tf

dtype = np.float32
x = tf.get_variable('x', shape=(), dtype=dtype,
                    initializer=tf.zeros_initializer)
y = tf.constant(1, dtype=dtype)

# Copy value of x before assigning new value y to x
x_ident = tf.identity(x)
with tf.control_dependencies([x_ident]):
    assign_op = tf.assign(x, y)

# Run
init_op = x.initializer
with tf.Session() as sess:
    sess.run(init_op)
    x_before_ = sess.run(x)
    x_ident_ = sess.run([x_ident, assign_op])[0]
    x_after_ = sess.run(x)

# Check
print("version:", tf.__version__)
print("x_before_:", x_before_)
print("x_ident_:", x_ident_)
print("x_after_:", x_after_)
assert np.allclose(x_ident_, 0)
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-09-19 15:02:24

我在过去发现过这个问题,我认为你是对的,它应该如你所期望的那样起作用。也许它值得提出问题。我没有这样的解决方案,但我的解决办法是有一个无用的操作,比如添加零:

代码语言:javascript
运行
复制
import numpy as np
import tensorflow as tf

dtype = np.float32
x = tf.get_variable('x', shape=(), dtype=dtype,
                    initializer=tf.zeros_initializer)
y = tf.constant(1, dtype=dtype)

# Force snapshot of x with zero addition
x_ident = x + 0
with tf.control_dependencies([x_ident]):
    assign_op = tf.assign(x, y)

# Run
init_op = x.initializer
with tf.Session() as sess:
    sess.run(init_op)
    x_before_ = sess.run(x)
    x_ident_ = sess.run([x_ident, assign_op])[0]
    x_after_ = sess.run(x)

# Check
print("version:", tf.__version__)
print("x_before_:", x_before_)
print("x_ident_:", x_ident_)
print("x_after_:", x_after_)
assert np.allclose(x_ident_, 0)

输出:

代码语言:javascript
运行
复制
version: 1.14.0
x_before_: 0.0
x_ident_: 0.0
x_after_: 1.0
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58013710

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档