Advertisement
Guest User

Untitled

a guest
Mar 28th, 2020
109
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.73 KB | None | 0 0
  1. from __future__ import absolute_import, division, print_function
  2. from tensorflow.keras.datasets import mnist
  3. from tensorflow.keras import Model, layers
  4. import tensorflow as tf
  5. import numpy as np
  6. import matplotlib.pyplot as plt
  7.  
  8. num_classes = 10
  9. num_features = 784
  10. learning_rate = 0.5
  11. training_steps = 4000
  12. batch_size = 256
  13. n_hidden_1 = 256
  14. n_hidden_2 = 512
  15.  
  16. (x_train, y_train), (x_test, y_test) = mnist.load_data()
  17. x_train, x_test = np.array(x_train, np.float32), np.array(x_test, np.float32)
  18. x_train, x_test = x_train.reshape([-1, num_features]), x_test.reshape([-1, num_features])
  19. x_train, x_test = x_train / 255., x_test / 255.
  20. train_data = tf.data.Dataset.from_tensor_slices((x_train, y_train))
  21. train_data = train_data.repeat().shuffle(5000).batch(batch_size).prefetch(1)
  22.  
  23. class NeuralNet(Model):
  24.     def __init__(self):
  25.         super(NeuralNet, self).__init__()
  26.         self.fc1 = layers.Dense(n_hidden_1, activation=tf.nn.relu)
  27.         self.fc2 = layers.Dense(n_hidden_2, activation=tf.nn.relu)
  28.         self.out = layers.Dense(num_classes, activation=tf.nn.softmax)
  29.  
  30.     def call(self, x, is_training=False):
  31.         x = self.fc1(x)
  32.         x = self.out(x)
  33.         if not is_training:
  34.             x = tf.nn.softmax(x)
  35.         return x
  36.  
  37. neural_net = NeuralNet()
  38. def cross_entropy_loss(x, y):
  39.     y = tf.cast(y, tf.int64)
  40.     loss = tf.nn.sparse_softmax_cross_entropy_with_logits(labels=y, logits=x)
  41.     return tf.reduce_mean(loss)
  42.  
  43. def accuracy(y_pred, y_true):
  44.     correct_prediction = tf.equal(tf.argmax(y_pred, 1), tf.cast(y_true, tf.int64))
  45.     return tf.reduce_mean(tf.cast(correct_prediction, tf.float32), axis=-1)
  46.  
  47. optimizer = tf.optimizers.SGD(learning_rate)
  48. def run_optimization(x, y):
  49.     with tf.GradientTape() as g:
  50.         pred = neural_net(x, is_training=True)
  51.         loss = cross_entropy_loss(pred, y)
  52.     trainable_variables = neural_net.trainable_variables
  53.     gradients = g.gradient(loss, trainable_variables)
  54.     optimizer.apply_gradients(zip(gradients, trainable_variables))
  55. for step, (batch_x, batch_y) in enumerate(train_data.take(training_steps), 1):
  56.     run_optimization(batch_x, batch_y)
  57.    
  58.     if step % display_step == 0:
  59.         pred = neural_net(batch_x, is_training=True)
  60.         loss = cross_entropy_loss(pred, batch_y)
  61.         acc = accuracy(pred, batch_y)
  62.         print("step: %i, loss: %f, accuracy: %f" % (step, loss, acc))
  63. pred = neural_net(x_test, is_training=False)
  64. print("Test Accuracy: %f" % accuracy(pred, y_test))
  65. n_images = 10
  66. test_images = x_test[:n_images]
  67. predictions = neural_net(test_images)
  68. for i in range(n_images):
  69.     plt.imshow(np.reshape(test_images[i], [28, 28]), cmap='gray')
  70.     plt.show()
  71.     print("Model prediction: %i" % np.argmax(predictions.numpy()[i]))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement