TensorFlow module ‘tensorflow‘ has no attribute ‘Session‘ 问题解决

问题描述

在初次尝试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上已经不再支持,因此在这里提供一个下载源,在我的CSDN账号的资源里。
下面附上当时测试的代码,用来实现数字的图像识别的深度学习训练。

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))
  • 4
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Volavion

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值