###开篇
算起凌晨的那一篇词袋模型,这是今天的第三篇TensorFlow博客,我们也要开始跑一点真实的数据集啦。不能总是拿着自己随便捏造的一点数据来描述我们的算法,可能会有点老套,但是我还是决定选择一个比较常被用用到的数据集,手写数字的数据集。找了一大圈数据集的下载,发现在csdn上还需要积分下载,这种本来就应该是免费下载使用的数据集还要积分就有点过分啦。这里放上我的下载链接链接:https://pan.baidu.com/s/1TXvTbX59OF_rAi-ye6wYQQ 密码:6fu6。大家下载的时候记得修改一些数据集的名字,我直接用的temp为名的,但是下面的代码中使用的是MNIST_data命名的。OK,废话不多说,下面马上开始我们的正式内容。
###任务
简单的说一下我们今天要处理的任务,我会分别使用softmax和nn来处理我们的任务,会有两个完整的代码,后期我们还会使用cnn来处理我们的任务。使用的数据集是手写数字,那么我们要做的任务就是手写数字识别,说白了也就是我们的多分类任务,给一张手写的数字图片,我们给出它正确的数字类别。首先我们使用单纯的softmax去实现,也弥补一下我们上篇博客没有使用真实的数据集的遗憾。
###代码
扯了半天该上我们的代码了,首先是softmax的完整代码
# Lab 7 Learning rate and Evaluation
import tensorflow as tf
import random
# import matplotlib.pyplot as plt
from tensorflow.examples.tutorials.mnist import input_data
tf.set_random_seed(777) # reproducibility
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
# Check out https://www.tensorflow.org/get_started/mnist/beginners for
# more information about the mnist dataset
# parameters
learning_rate = 0.001
training_epochs = 15
batch_size = 100
# input place holders
X = tf.placeholder(tf.float32, [None, 784])
Y = tf.placeholder(tf.float32, [None, 10])
# weights & bias for nn layers
W = tf.Variable(tf.random_normal([784, 10]))
b = tf.Variable(tf.random_normal([10]))
hypothesis = tf.matmul(X, W) + b
# define cost/loss & optimizer
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(
logits=hypothesis, labels=Y))
optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost)
# initialize
sess = tf.Session()
sess.run(tf.global_variables_initializer())
# train my model
for epoch in range(training_epochs):
avg_cost = 0
total_batch = int(mnist.train.num_examples / batch_size)
for i in range(total_bat