问题描述
在初次尝试tensorflow 的时候遇到类似下面的问题:
module ‘tensorflow’ has no attribute ‘placeholder’
module ‘tensorflow’ has no attribute 'Session’
问题解决
导致该问题的原因是:
tensorflow的 V1 版本和V2版本不能直接兼容,需要在其前置中加入些代码设置环境:
import tensorflow.compat.v1 as tf
这个时候,如果你使用了placeholder的话,他又会报出错误:
RuntimeError: tf.placeholder() is not compatible with eager execution.
兼容问题又出现,那么再加入下述代码进行兼容设置:
tf.compat.v1.disable_eager_execution()
此外,在我的代码中还出现了 :ModuleNotFoundError: No module named ‘tensorflow.examples.tutorials’ 的错误。
这是由于我使用了一个MNIST的网络数据集,(from tensorflow.examples.tutorials.mnist import input_data)
这个数据集的即时下载方式已经改变,因此,如果想要拿到tutorials内部的函数,需要将该文件下载到本地,然后放在项目的根目录下。但是tutorials文件夹的下载在github上已经不再支持,因此在这里提供一个下载源,在我的优快云账号的资源里。
下面附上当时测试的代码,用来实现数字的图像识别的深度学习训练。
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
import tensorflow.compat.v1 as tf
print (tf.__path__)
tf.compat.v1.disable_eager_execution()
from tensorflow.examples.tutorials.mnist import input_data
DATA_DIR = '/data'
NUM_STEPS = 1000
MINIBATCH_SIZE = 100
# 直接使用内置方法即时检索数据集,ready_data_sets()方法将MNIST数据集下载到本地,第二个参数为读取标签的方式
data = input_data.read_data_sets(DATA_DIR, one_hot = True)
# 占位符和变量的定义, 图像本身x是一个占位符,none表示不指定每次使用的图片数量,784是图像的像素点个数,我们所提取的图像为 28×28
x = tf.placeholder(tf.float32, [None, 784])
print(x)
w = tf.Variable(tf.zeros([784, 10]))
print(w)
# y_true 和y_pred 分别表示真实和预测的标签
y_true = tf.placeholder(tf.float32, [None, 10])
y_pred = tf.matmul(x, w)
# 使用测量相似度的方法:交叉熵,也叫损失函数
cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=y_pred, labels=y_true))
# 通过最小化损失函数的方式使得整体损失下降,得到最优化结果(梯度下降法)
gd_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)
# 定义评估步骤来测试模型的准确率
correct_mask = tf.equal(tf.argmax(y_pred,1), tf.argmax(y_true, 1))
accuracy = tf.reduce_mean(tf.cast(correct_mask, tf.float32))
with tf.Session() as sess:
# Train
# 初始化所有参数
sess.run(tf.global_variables_initializer())
for _ in range(NUM_STEPS):
# 使用 MINIBATCH_SIZE常量控制每一步的样本数量
batch_xs, batch_ys = data.train.next_batch(MINIBATCH_SIZE)
# 模型学习过程
sess.run(gd_step, feed_dict = {x:batch_xs, y_true: batch_ys})
# Test 测试准确率
ans = sess.run(accuracy, feed_dict = {x: data.test.images, y_true: data.test.labels})
print ("Accuracy: {:.4}".format(ans*100))