首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >将tensorflow代码包装为python函数时出现的“未初始化值”错误

将tensorflow代码包装为python函数时出现的“未初始化值”错误
EN

Stack Overflow用户
提问于 2017-10-10 15:56:48
回答 1查看 47关注 0票数 1

错误是“试图使用未初始化的值state_variable”。但是我认为这个代码应该初始化这个值。

这是我的代码,谢谢:

代码语言:javascript
复制
import tensorflow as tf

def index():
    state = tf.Variable(0, name="state_variable")
    new_value = tf.add(state, tf.constant(1))
    update = tf.assign(state, new_value)
    return update

if __name__ == "__main__":
    with tf.Session() as sess:
        init_op = tf.group(tf.local_variables_initializer(),
                           tf.global_variables_initializer())
        op = index()
        sess.run(init_op)
        for _ in range(4):
            print(sess.run(op))
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-10-10 16:02:37

您需要将op = index()行放在使用tf.group定义init_op的行前面。目前,当您调用tf.group时,还没有调用tf.Variable(0, name="state_variable"),因此tf.group不知道如何将其初始化放入init_op中。以下版本在我的机器上运行良好:

代码语言:javascript
复制
import tensorflow as tf

def index():
    state = tf.Variable(0, name="state_variable")
    new_value = tf.add(state, tf.constant(1))
    update = tf.assign(state, new_value)
    return update

if __name__ == "__main__":
    with tf.Session() as sess:
        op = index()
        init_op = tf.group(tf.local_variables_initializer(),
                           tf.global_variables_initializer())
        sess.run(init_op)
        for _ in range(4):
            print(sess.run(op))
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46671009

复制
相关文章

相似问题

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