【深度学习-1】tensorflow实现最简单的MNIST图像分类

包含输入层,网络结构只有两层,如下图:

tensorflow 代码如下:

# encoding: utf-8

from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)

print(mnist.train.images.shape, mnist.train.labels.shape)
print(mnist.test.images.shape, mnist.test.labels.shape)
print(mnist.validation.images.shape, mnist.validation.labels.shape)

import tensorflow as tf

sess = tf.InteractiveSession()
x = tf.placeholder(tf.float32, [None, 784])  # 1,输入数据: feature
W = tf.Variable(tf.zeros([784, 10]))  # 2,两个参数w,b
b = tf.Variable(tf.zeros([10]))

y = tf.nn.softmax(tf.matmul(x, W)+b)  # 3,网络结构,预测值y = w*x + b,得到的是10维向量

y_ = tf.placeholder(tf.float32, [None, 10])  # 输入数据: label
cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y), reduction_indices=[1]))  # 4,损失函数: J = - y_ * log y

train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)  # 5,优化函数: 梯度下降

tf.global_variables_initializer().run()

for i in range(1000):
    batch_xs, batch_ys = mnist.train.next_batch(100)
    train_step.run({x: batch_xs, y_: batch_ys})  # 训练

correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))  # 预测值10向量,与label比较,看是否相等

accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))

print(accuracy.eval({x: mnist.test.images, y_: mnist.test.labels}))

猜你喜欢

转载自blog.csdn.net/jizhidexiaoming/article/details/81088926
今日推荐