刚开始学习使用tensorflow,遇到的一个问题
前言
<
刚开始学习使用tensorflow,遇到的一个问题,通过tensorflow实现加法
一、原本代码
import tensorflow as tf
a = tf.constant(11.0)
b = tf.constant(12.0)
c = tf.add(a, b)
with tf.Session() as sess:
c_res = sess.run(c)
print(c_res)
结果出现下面错误
Traceback (most recent call last):
File "C:/Users/lbb/Desktop/demo/demo.py", line 7, in <module>
with tf.Session() as sess:
AttributeError: module 'tensorflow' has no attribute 'Session'
二更改后代码
在网上查询得知是tensorflow2对之前的tensorflow1不兼容,tensorflow2中没有session这个模块,需要将其中的
with tf.Session() as sess:
改为
with tf.compat.v1.Session() as sess:
运行之后还是报错,解决方法,在前面加一行代码
tf.compat.v1.disable_eager_execution()#保证sess.run能够运行
完整代码
import tensorflow as tf
tf.compat.v1.disable_eager_execution()#保证sess.run能够运行
a = tf.constant(11.0)
b = tf.constant(12.0)
c = tf.add(a, b)
with tf.compat.v1.Session() as sess:
c_res = sess.run(c)
print(c_res)
程序运行结果:
23.0
总结
参考这个博主的[https://blog.csdn.net/weixin_38410551/article/details/103631977]
有时运行时会出现一堆警告,虽然不影响程序运行,但是影响心情。在代码最上方加上
import os
os.environ['TF_CPP_MIN_LOG_LEVEL']='2'
就能获得清爽的界面了