tensorflow基本计算单元变量

按照视频讲解的源代码在现在装的环境下跑不起来,汇报一系列的错误,造成他们的愿意都是因为版本不对,无法兼容之前的版本1.0的内容。

import tensorflow as tf
a=3
w = tf.Variable([[0.5,1.0]])
x = tf.Variable([[2.0],[1.0]])
y=tf.matmul(w,x)
init = tf.global_variables_initializer()
with tf.Session() as sess:
    sess.run(init)
    print(y.eval())

 

 所以我们需要在声明变量的时候在原本的基础上改为:

init = tf.compat.v1.global_variables_initializer()

 在对session做了同样的操作之后,又出现了错误:

RuntimeError: The Session graph is empty. Add operations to the graph before calling run().

 我从网上搜集了两个方法,都可以很好的解决问题:

1.添加代码:tf.compat.v1.disable_eager_execution()

在运行session之前,添加代码tf.compat.v1.disable_eager_execution()保证run()可以正常运行

2.清理开始的会话session

引入keras来清理考试会话的session

改为符合版本的代码为:

import tensorflow as tf
tf.compat.v1.disable_eager_execution()#保证sess.run()能够正常运行
a=3
w = tf.Variable([[0.5,1.0]])
x = tf.Variable([[2.0],[1.0]])
y=tf.matmul(w,x)
init = tf.compat.v1.global_variables_initializer()
with tf.compat.v1.Session() as sess:
    sess.run(init)
    print(y.eval())

 

posted @ 2021-01-10 11:09  doublebest1  阅读(146)  评论(0编辑  收藏  举报