TensorFlow在MNIST中的应用-Softmax回归分类

2023-11-04

参考:

《TensorFlow技术解析与实战》

http://wiki.jikexueyuan.com/project/tensorflow-zh/tutorials/mnist_beginners.html

http://www.jianshu.com/p/4195577585e6

http://blog.csdn.net/u014422406/article/details/52805924

#########################################################################################################

MNIST分类问题-Softmax回归

# -*- coding:utf-8 -*-

# ==============================================================================
# 20171114
# HelloZEX
# ==============================================================================

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import argparse
import sys

#使用input_data.py文件来加载数据
from tensorflow.examples.tutorials.mnist import input_data
import tensorflow as tf

FLAGS = None


def main(_):
  # 导入数据
  mnist = input_data.read_data_sets("MNIST_Labels_Images", one_hot=True)

  # 构建回归模型
  x = tf.placeholder(tf.float32, [None, 784])
  W = tf.Variable(tf.zeros([784, 10]))
  b = tf.Variable(tf.zeros([10]))
  y = tf.matmul(x, W) + b #预测值

  # 定义损失函数和优化器
  y_ = tf.placeholder(tf.float32, [None, 10])

  # 交叉熵的原始公式,
  # tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(tf.nn.softmax(y)),reduction_indices=[1]))
  # 数值上不稳定
  # 这里我们使用的是 tf.nn.softmax_cross_entropy_with_logits
  # 输出y后求均值
  cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=y))
  #采用SGD(随机梯度下降法)作为优化器
  train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)

  #训练模型
  #创建交互式的TF会话
  sess = tf.InteractiveSession()
  tf.global_variables_initializer().run()
  # 训练数据
  for _ in range(1000):
    batch_xs, batch_ys = mnist.train.next_batch(100)
    sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})

  # 评估模型
  #tf.argmax(y_, 1)返回的是模型对任意一输入x的预测到的标记值
  correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))
  accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
  print("正确率:", sess.run(accuracy, feed_dict={x: mnist.test.images, y_: mnist.test.labels}))

if __name__ == '__main__':
  parser = argparse.ArgumentParser()
  parser.add_argument('--data_dir', type=str, default='/tmp/tensorflow/mnist/input_data',
                      help='Directory for storing input data')
  FLAGS, unparsed = parser.parse_known_args()
  tf.app.run(main=main, argv=[sys.argv[0]] + unparsed)
  
console:

/usr/bin/python2.7 /home/zhengxinxin/Desktop/PyCharm/pycharm-community-2017.2/helpers/pydev/pydevd.py --multiproc --qt-support=auto --client 127.0.0.1 --port 34763 --file /home/zhengxinxin/Desktop/PyCharm/Spark/SparkMNIST/mnist_softmax.py
pydev debugger: process 3248 is connecting

Connected to pydev debugger (build 172.3544.44)
Extracting MNIST_Labels_Images/train-images-idx3-ubyte.gz
Extracting MNIST_Labels_Images/train-labels-idx1-ubyte.gz
Extracting MNIST_Labels_Images/t10k-images-idx3-ubyte.gz
Extracting MNIST_Labels_Images/t10k-labels-idx1-ubyte.gz
2017-11-14 19:53:24.149759: W tensorflow/core/platform/cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use SSE4.1 instructions, but these are available on your machine and could speed up CPU computations.
2017-11-14 19:53:24.149807: W tensorflow/core/platform/cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use SSE4.2 instructions, but these are available on your machine and could speed up CPU computations.
2017-11-14 19:53:24.149812: W tensorflow/core/platform/cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use AVX instructions, but these are available on your machine and could speed up CPU computations.
2017-11-14 19:53:24.149815: W tensorflow/core/platform/cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use AVX2 instructions, but these are available on your machine and could speed up CPU computations.
2017-11-14 19:53:24.149819: W tensorflow/core/platform/cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use FMA instructions, but these are available on your machine and could speed up CPU computations.
正确率: 0.9172

Process finished with exit code 0

#########################################################################################################



本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

TensorFlow在MNIST中的应用-Softmax回归分类 的相关文章

随机推荐