tensorflow-单层网络mnist数字识别问题

前言:mnis数字识别问题以及其中碰到的问题
第一步:源码
import os
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
from tensorflow.python.saved_model.model_utils.mode_keys import is_train

os.environ["TF_CPP_MIN_LOG_LEVEL"] = '2'

tf.app.flags.DEFINE_integer("is_train", 2, "指定模型是训练还是预测")
FLAGS = tf.app.flags.FLAGS


def full_connected():

    # 获取真实的数据,one_hot 独热编码
    # 也叫一位有效编码。在任意时候只有一位为1,其他位都是0
    mnist = input_data.read_data_sets("./data", one_hot=True)

    # 1.建立数据的占位符 x [None, 784]  y_true [None, 10]
    with tf.variable_scope("data"):
        x = tf.placeholder(tf.float32, [None, 784])
        y_true = tf.placeholder(tf.int32, [None, 10])

    # 2.建立全连接层神经网络, w [784, 10] b[10]
    with tf.variable_scope("fc_model"):
        # 随机初始化权重和偏置
        weight = tf.Variable(tf.random_normal([784, 10], mean=0, stddev=1.0, name="w"))
        bias = tf.Variable(tf.constant(0.0, shape=[10]), name="b")

        # 预测None个样本的输出结果matrix [None, 784]*[784, 10]+[10] = [None, 10]
        y_predict = tf.matmul(x, weight) + bias

    # 3.计算交叉熵损失,其中参数labels表示真实值,logits表示预测值
    with tf.variable_scope("soft_cross"):
        # 求平均交叉熵损失
        loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y_true, logits=y_predict))

    # 4.梯度下降求出损失
    with tf.variable_scope("optimizer"):
        train_op = tf.train.GradientDescentOptimizer(0.1).minimize(loss)

    # 5.计算准确率
    with tf.variable_scope("accuracy"):
        equal_list = tf.equal(tf.argmax(y_true, 1), tf.argmax(y_predict, 1))
        # equal_list None个样本   [1, 1, 1, 0, ..............1]]
        accuracy = tf.reduce_mean(tf.cast(equal_list, tf.float32))

    # 收集变量,单个数字值收集
    # loss = tf.reduce_mean(loss, name='loss'),最开始没有将loss从张量转化为标量,出现错误
    tf.summary.scalar("losses", loss)
    tf.summary.scalar("acc", accuracy)

    # 高纬度变量收集
    tf.summary.histogram("weights", weight)
    tf.summary.histogram("biases", bias)

    # 定义一个初始化变量的op
    init_op = tf.global_variables_initializer()

    # 定义一个合并变量的op
    merged = tf.summary.merge_all()

    # 定义一个保存模型的实例op
    saver = tf.train.Saver()

    # 开启会话去训练
    with tf.Session() as sess:
        sess.run(init_op)
        # 建立events文件,然后写入
        fw = tf.summary.FileWriter("./tmp/summary/test", graph=sess.graph)
        if FLAGS.is_train == 1:

            # 迭代步数去训练,更新参数预测
            for i in range(2000):
                # 每一次给100个数据进行训练,取出真实存在的特征值和目标值
                mnist_x, mnist_y = mnist.train.next_batch(50)

                # 运行train_op训练
                sess.run(train_op, feed_dict={x: mnist_x, y_true: mnist_y})

                # 写入每步训练的值
                summary = sess.run(merged, feed_dict={x: mnist_x, y_true: mnist_y})
                # 添加到写入的文件当中
                fw.add_summary(summary, i)

                print("训练第%d步,准确率为:%f" % (i, sess.run(accuracy, feed_dict={x: mnist_x, y_true: mnist_y})))
                # 保存模型
            saver.save(sess, "./tmp/summary/smodl/fc_model")
        else:
            # if FLAGS.is_train == 2:
            # 加载模型,因为前面我们保存了模型,故不再判断有没有模型
            saver.restore(sess, "./tmp/summary/smodl/fc_model")

            # 如果是0,进行预测,每次测试一张图片
            for i in range(100):
                x_test, y_test = mnist.test.next_batch(1)
                print("第%d张图片,手写图片数字目标是:%d,预测结果是:%d" % (
                    i,
                    tf.argmax(y_test, 1).eval(),
                    tf.argmax(sess.run(y_predict, feed_dict={x: x_test, y_true: y_test}), 1).eval()
                ))

    return None


if __name__ == "__main__":
    full_connected()

第二部:做的过程中问题

1.在做的过程中tf.reduce_mean个代码没有加到去求loss的代码上,导致loss是张量无法转化为标量

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值