AttributeError: module ‘tensorflow‘ has no attribute ‘Session‘

本文介绍如何解决在TensorFlow 2.x中使用Session时出现的AttributeError,并提供两种解决方案:一是通过兼容模式调整代码,二是选择回退到1.x版本。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在执行下面代码时,报错:AttributeError: module 'tensorflow' has no attribute 'Session'

原因:tensorflow为2.0以上版本,不支持Session

import tensorflow as tf
a = tf.constant(11.0)
b = tf.constant(20.0)
c = tf.add(a, b)

#指定一个会话运行tensorflow程序
with tf.Session() as sess:
    c_res = sess.run(c)
    print(c_res)

修改代码如下:

import tensorflow as tf
tf.compat.v1.disable_eager_execution()

a = tf.constant(11.0)
b = tf.constant(20.0)
c = tf.add(a, b)

#指定一个会话运行tensorflow程序
with tf.compat.v1.Session() as sess:
    c_res = sess.run(c)
    print(c_res)

或者可以选择卸载重装1.几版本的tensorflow。

更新:

我发现这样改不太好,因为这样下面要调用的不匹配代码就都得改。可以直接开头的代码import tensorflow as tf  改成 

import tensorflow.compat.v1 as tf

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值