tensorflow1.0和2.0的使用区别
[深度学习] tensorflow1.x和tensorflow2.x对比与总结_tensorflow2 与 1_茫茫人海一粒沙的博客-CSDN博客
1.ImportError: cannot import name 'device_spec' from 'tensorflow.python.framework' (D:\Anaconda3\envs\tensorflow\lib\site-packages\tensorflow\python\framework\__init__.py)
在安装tf_slim以后,运行程序出现以上错误,这是由于tf的版本是1.0原因,要升级tf到2.0版本。
先卸载tf_slim
pip uninstall tf_slim
安装2.0版本的tf
pip install tensorflow==2.0.0
再安装tf_slim
pip install tf_slim
2.AttributeError: module 'tensorflow' has no attribute 'Session'
①如果是在tf2.0 中使用旧版1.0的会话方式的话,tf2.0版本和1.0版本的命名方式不同,将
import tensorflow as tf
替换为:
import tensorflow.compat.v1 as tf
② 如果直接使用新版 2.0的模式的话,使用 Eager Execution 模式,不再需要使用 tf.Session()
。因此,你可以直接运行 TensorFlow 2.x 中的代码,而不需要创建会话
import tensorflow as tf
3. from tensorflow.examples.tutorials.mnist import input_data
ModuleNotFoundError: No module named 'tensorflow.examples.tutorials'
这个问题是由于使用tensorflow2.x从而无法导入mninst。tensorflow2.x将数据集集成在Keras中。tensorflow2.0,更新删除了input_data的函数。
import tensorflow as tf
# tf.__version__
mint=tf.keras.datasets.mnist
(x_,y_),(x_1,y_1)=mint.load_data()
import matplotlib.pyplot as plt
plt.imshow(x_[0], cmap="binary")
plt.show()
4.image=mnist.train.image[0]
AttributeError: module 'tensorflow_core.keras.datasets.mnist' has no attribute 'train'
在 TensorFlow 2.0的 Keras 库中,mnist
模块没有名为 train
的属性。
import tensorflow as tf
# 加载 MNIST 数据集
(train_images, train_labels), (test_images, test_labels) = tf.keras.datasets.mnist.load_data()
# 访问第一张图像
image = train_images[0]
# 打印图像形状
print(image.shape)
5.RuntimeError: Attempting to capture an EagerTensor without building a function.
在 TensorFlow 2.x 版本中,使用 Eager Execution 模式,不再需要使用 tf.Session()
。因此,你可以直接运行 TensorFlow 2.x 中的代码,而不需要创建会话。
import tensorflow as tf
# 加载 MNIST 数据集
(train_images, train_labels), (test_images, test_labels) = tf.keras.datasets.mnist.load_data()
# 转换标签为 one-hot 编码
num_classes = 10
train_labels = tf.one_hot(train_labels, num_classes)
print(train_labels[0])
6.AttributeError: module 'tensorflow' has no attribute 'placeholder'
在 TensorFlow 2.x 中,不再使用 tf.placeholder
来创建占位符。取而代之的是使用普通的 Python 张量或使用 tf.data.Dataset
来加载数据。