简体   繁体   中英

MNIST neural network : Accuracy is pretty low

I am using MNIST data set to learn tensorflow and neural network. Below is my code in python.

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

mnist = input_data.read_data_sets("data/",one_hot=True) 

features = 28*28
classes = 10
batch_size = 100
m_train = mnist.train.num_examples
m_test = mnist.test.num_examples

print(" The neural network will be trained on ",m_train, " examples")

H_L_1_nodes = 500
H_L_2_nodes = 500
H_L_3_nodes = 500

x = tf.placeholder('float',[None,features])
y = tf.placeholder('float',[None,classes])

def neural_net(data):
    hidden_layer_1 = {'weights' : tf.Variable(tf.random_normal([features, H_L_1_nodes]) ),
                      'biases'  : tf.Variable(tf.random_normal([H_L_1_nodes]) )}

    hidden_layer_2 = {'weights' : tf.Variable(tf.random_normal([H_L_1_nodes, H_L_2_nodes]) ),
                      'biases'  : tf.Variable(tf.random_normal([H_L_2_nodes]))}

    hidden_layer_3 = {'weights' : tf.Variable(tf.random_normal([H_L_2_nodes, H_L_3_nodes]) ),
                      'biases'  : tf.Variable(tf.random_normal([H_L_3_nodes]))}

    output_layer   = {'weights' : tf.Variable(tf.random_normal([H_L_3_nodes, classes]) ),
                      'biases'  : tf.Variable(tf.random_normal([classes]) )}

    l1 = tf.add( tf.matmul( data, hidden_layer_1['weights'] ), hidden_layer_1['biases'])
    l1 = tf.nn.relu(l1)

    l2 = tf.add( tf.matmul( l1, hidden_layer_2['weights'] ), hidden_layer_2['biases'])
    l2 = tf.nn.relu(l2)

    l3 = tf.add( tf.matmul( l2, hidden_layer_3['weights'] ), hidden_layer_3['biases'])
    l3 = tf.nn.relu(l3)

    output = tf.add(tf.matmul( l3, output_layer['weights']), output_layer['biases'])
    output = tf.nn.relu(output)

    return output

def train_neural_network(x):
    prediction = neural_net(x)
    cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(prediction, y))
    optimizer = tf.train.AdamOptimizer(0.0001).minimize(cost)

    epochs = 5
    with tf.Session() as session:
        session.run(tf.global_variables_initializer())
        for epoch in range(epochs):
            epoch_loss = 0 
            for _ in range(int(m_train/batch_size)):
                _x, _y = mnist.train.next_batch(batch_size)
                _, c = session.run( [optimizer,cost], feed_dict={x : _x, y : _y} )
                epoch_loss += c
            print(" Loss in ",epoch," iteration is ", epoch_loss)
        correct = tf.equal(tf.argmax(prediction,1), tf.argmax(y,1))
        accuracy = tf.reduce_mean(tf.cast(correct,'float'))

        print("-------------------------------------------------------------------------")
        print(session.run(tf.cast(correct[:10],'float'), feed_dict= { x:mnist.test.images, y: mnist.test.labels } ))
        print("-------------------------------------------------------------------------")

        print(" The neural network will be tested on ",m_test, " examples")
        print(" Accuracy = ", accuracy.eval(feed_dict= { x:mnist.test.images, y: mnist.test.labels } )*100,"%")

print("Initializing training...")

train_neural_network(x)

print("Success!")

I am getting the accuracy of 9% to 13% and not more than that. I think I have implemented the code correctly but not able to figure out what is wrong. One thing I figured out is that the accuracy is because the model is predicting only 0s correctly.

I have done mistake in calculating the output of the network,

Wrong:

output = tf.add(tf.matmul( l3, output_layer['weights']), output_layer['biases'])
output = tf.nn.relu(output)

Correct:

output = tf.add(tf.matmul( l3, output_layer['weights']), output_layer['biases'])

I was normalizing the output again which was messing up all the network. Posting this answer as it may be helpful to someone in future. Thanks!

PS : Borrowed code from sentdex

EDIT:

I have found that the accuracy can be further improved by using CNN and even further more by using RNN . Probably someone will find this useful.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM