我们使用tensorflow完成mnist数据集的分类,文章使用了简单的全连接完成,后期会将全连接替换成卷积和池化结构。tensorflow最初理解为先对网络的总体进行设计,构造整体的网络图,然后对图注入数据执行。**
import tensorflow as tf
import numpy as np
from tf_utils import *
import tensorflow.examples.tutorials.mnist.input_data as input_data
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True) #下载数据集
#图像的维度 28*28
image_dim = 784
#标签维度
label_dim = 10
#构造图开始
input_image = tf.placeholder(tf.float32, [None, image_dim])
input_label = tf.placeholder(tf.float32, [None, label_dim])
#设置权重和偏置
W = tf.Variable(tf.zeros([image_dim, label_dim]))
b = tf.Variable(tf.zeros([label_dim]))
output = tf.nn.softmax(tf.matmul(input_image, W) + b)
#交叉熵作为损失函数
cross_entropy = -tf.reduce_sum(input_label * tf.log(output))
#梯度下降法求解
train_loss = tf.train.GradientDescentOptimizer(0.01).minimize(cross_entropy)
prediction = tf.equal(tf.argmax(input_label, 1), tf.argmax(output, 1))
accuary = tf.reduce_sum(tf.cast(prediction, "float"))
init = tf.initialize_all_variables()
#构造图结束
#执行图
with tf.Session() as sess:
sess.run(init)
for i in range(1000):
batch_x, batch_y = mnist.train.next_batch(100)
sess.run(train_loss, feed_dict = {input_image : batch_x, input_label: batch_y})
if i%10==0:
print(sess.run(accuary, feed_dict = {input_image : batch_x, input_label: batch_y}))
#执行图