In [1]:
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
In [2]:
mnist = input_data.read_data_sets("../Datasets/MNIST/", one_hot=True)
In [3]:
print('MNIST traininig set images:', mnist.train.images.shape)
print('MNIST traininig set labels:', mnist.train.labels.shape)
print('MNIST test set images:', mnist.test.images.shape)
print('MNIST test set labels:', mnist.test.labels.shape)
In [4]:
#define the neural net
n_1 = 100
n_2 = 10
batch_size = 100
In [5]:
X = tf.placeholder('float', [None, 784])
y = tf.placeholder('float')
In [6]:
def neural_net_model(X):
W1 = tf.Variable(tf.random_normal([784, n_1]))
b1 = tf.Variable(tf.random_normal([n_1]))
W2 = tf.Variable(tf.random_normal([n_1, n_2]))
b2 = tf.Variable(tf.random_normal([n_2]))
Z1 = tf.matmul(X, W1) + b1
A1 = tf.nn.relu(Z1)
Z2 = tf.matmul(A1, W2) + b2
return Z2
In [11]:
def train_neural_network(X):
y_ = neural_net_model(X)
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(
logits=y_, labels=y))
optimizer = tf.train.AdamOptimizer(learning_rate=0.001).minimize(
cost)
num_epochs = 50
with tf.Session() as session:
session.run(tf.global_variables_initializer())
for epoch in range(num_epochs):
epoch_loss=0
for i in range(mnist.train.num_examples // batch_size):
ex , ey = mnist.train.next_batch(batch_size)
_, c = session.run([optimizer, cost], feed_dict={
X: ex, y: ey})
epoch_loss += c
print('Epoch', epoch, '/', num_epochs, 'loss', epoch_loss)
correct = tf.equal(tf.argmax(y_, 1), tf.argmax(y, 1))
accuracy = tf.reduce_mean(tf.cast(correct, 'float'))
print('Accuracy:', accuracy.eval({X: mnist.test.images,
y: mnist.test.labels}))
In [12]:
train_neural_network(X)
In [ ]:
In [ ]: