MNIST handwritten digital classification simple version (03-2)

simple version nn model training handwritten digital processing

import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data

# Load data sets
mnist=input_data.read_data_sets("MNIST_data", one_hot=True)

# Each batch size
batch_size=100
# Calculate a total number of batches
n_batch=mnist.train.num_examples // batch_size

# Define two placeholder
x=tf.placeholder(tf.float32,[None,784])
y=tf.placeholder(tf.float32,[None,10])

# Create a simple neural network
W=tf.Variable(tf.zeros([784,10]))
b=tf.Variable(tf.zeros([1,10]))
prediction=tf.nn.softmax(tf.matmul(x,W)+b)

# Quadratic cost function
loss=tf.reduce_mean(tf.square(y-prediction))
# Use ordained descent method
train_step=tf.train.GradientDescentOptimizer(0.2).minimize(loss)

#Initialize variables
init=tf.global_variables_initializer()

# Store the result in a Boolean list
correct_prediction = tf.equal (tf.argmax (y, 1), tf.argmax (prediction, 1)) #argmax a return position dimensional tensor maximum value where
# Seek accuracy
accuracy=tf.reduce_mean(tf.cast(correct_prediction,tf.float32))

with tf.Session() as sess:
    sess.run(init)
    for epoch in range(20):
        for batch in range(n_batch):
            batch_xs,batch_ys=mnist.train.next_batch(batch_size)
            sess.run(train_step,feed_dict={x:batch_xs, y:batch_ys})

        acc=sess.run(accuracy,feed_dict={x:mnist.test.images, y:mnist.test.labels})
        print("Iter"+str(epoch)+",Testing Accuracy "+str(acc))

 

Guess you like

Origin www.cnblogs.com/go-ahead-wsg/p/12310309.html