首页 > 解决方案 > Tensorflow 2.0 - AttributeError:模块'tensorflow'没有属性'Session'

问题描述

当我sess = tf.Session()在 Tensorflow 2.0 环境中执行命令时,我收到如下错误消息:

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: module 'tensorflow' has no attribute 'Session'

系统信息:

重现步骤:

安装:

  1. 点安装——升级点
  2. pip install tensorflow==2.0.0-alpha0
  3. 点安装 keras
  4. pip install numpy==1.16.2

执行:

  1. 执行命令:import tensorflow as tf
  2. 执行命令:sess = tf.Session()

标签: pythontensorflowkerastensorflow2.0

解决方案


根据TF 1:1 Symbols Map,在 TF 2.0 中,您应该使用tf.compat.v1.Session()而不是tf.Session()

https://docs.google.com/spreadsheets/d/1FLFJLzg7WNP6JHODX5q8BDgptKafq_slHpnHVbJIteQ/edit#gid=0

要在 TF 2.0 中获得类似 TF 1.x 的行为,可以运行

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

但随后无法从 TF 2.0 中的许多改进中受益。有关更多详细信息,请参阅迁移指南 https://www.tensorflow.org/guide/migrate


推荐阅读