Advertisement
Felanpro

tensorflow mnist classification

Dec 21st, 2022
929
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.93 KB | None | 0 0
  1. import tensorflow as tf
  2. import numpy as np
  3.  
  4. # Import training data
  5. mnist = tf.keras.datasets.mnist
  6.  
  7. # Initialize training data
  8. (x_train, y_train), (x_test, y_test) = mnist.load_data()
  9. x_train, x_test = x_train / 255.0, x_test / 255.0
  10.  
  11. # Create the neural network
  12. model = tf.keras.models.Sequential([
  13.   tf.keras.layers.Flatten(input_shape=(28, 28)),
  14.   tf.keras.layers.Dense(128, activation='relu'),
  15.   tf.keras.layers.Dropout(0.2),
  16.   tf.keras.layers.Dense(10)
  17. ])
  18.  
  19. loss_fn = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True)
  20.  
  21. predictions = model(x_train[:1]).numpy()
  22.  
  23. loss_fn(y_train[:1], predictions).numpy()
  24.  
  25. # Prepare for training the network
  26. model.compile(optimizer='adam',
  27.               loss=loss_fn,
  28.               metrics=['accuracy'])
  29.  
  30. predictions = model(x_train[:1]).numpy()
  31.  
  32. # Train the network
  33. model.fit(x_train, y_train, epochs=5)
  34.  
  35. #Evaluate the network
  36. model.evaluate(x_test,  y_test, verbose=2)
  37.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement