--- title: "MNIST Example Python" author: "Prof. Eric A. Suess" format: html: embed-resources: true --- ## MNIST Feedforward neural network with **one** hidden layer Load the packages ```{r} library(tensorflow) library(keras) ``` ```{python} import tensorflow as tf from tensorflow import keras import numpy as np import matplotlib.pyplot as plt ``` Load the MNIST dataset. ```{python} mnist = keras.datasets.mnist (train_images, train_labels), (test_images, test_labels) = mnist.load_data() ``` Examine the data. ```{python} print(train_images.shape) print(train_labels) print(test_images.shape) print(test_labels) ``` Preprocess the data. ```{python} train_images = train_images.reshape((60000, 28 * 28)) train_images = train_images.astype('float32') / 255 test_images = test_images.reshape((10000, 28 * 28)) test_images = test_images.astype('float32') / 255 ``` Specify a neural network model. ```{python} model = keras.Sequential([ keras.layers.Dense(512, activation='relu'), keras.layers.Dense(10, activation='softmax') ]) ``` ```{python} model.compile(optimizer='rmsprop', loss='sparse_categorical_crossentropy', metrics=['accuracy']) ``` Train the model. ```{python} model.fit(train_images, train_labels, epochs=5, batch_size=128) ``` Evaluate the model. ```{python} test_loss, test_acc = model.evaluate(test_images, test_labels) print('Test accuracy:', test_acc) ``` Make predictions. ```{python} predictions = model.predict(test_images) print(predictions[0]) print(np.argmax(predictions[0])) ```