<jupyter_start><jupyter_text>How to train a simple neural network for the MNIST dataset (digit classification)<jupyter_code>import numpy as np

from keras.datasets import mnist
from keras import models
from keras import layers
from keras.utils import to_categorical
# Download the MNIST dataset
(train_images, train_labels), (test_images, test_labels) = mnist.load_data()
# The training data has 60000 samples (28x28 images)
print train_images.shape
# Each image has a label (0 to 9)
print len(train_labels)
train_labels
# The test data has 10000 samples (28x28 images)
print test_images.shape
# Each image has a label (0 to 9)
print len(test_labels)
test_labels
# Define the network (one layer of 512 units and an output of 10 units)
network = models.Sequential()
network.add(layers.Dense(512, activation='relu', input_shape=(28 * 28,)))
network.add(layers.Dense(10, activation='softmax'))
# Compile the network and define the optimizer, loss and performance metric
network.compile(optimizer='rmsprop',loss='categorical_crossentropy',metrics=['accuracy'])
# Reshape the samples (each sample has 28*28 'features') and normalize between 0-1
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
# Convert the 0-9 labels to arrays of 0s and 1s of size 10
train_labels = to_categorical(train_labels)
test_labels = to_categorical(test_labels)

print train_labels
# Perform the training of the network
network.fit(train_images, train_labels, epochs=10, batch_size=128)
# Evaluate the performance of the model on the test data
test_loss, test_acc = network.evaluate(test_images, test_labels)
print('test_acc:', test_acc)<jupyter_output>10000/10000 [==============================] - 1s 52us/step
('test_acc:', 0.9826)
{'fraction_non_alphanumeric': 0.10831099195710456, 'fraction_numerical': 0.05308310991957105, 'mean_word_length': 6.585365853658536, 'pattern_counts': {'":': 0, '<': 4, '<?xml version=': 0, '>': 4, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 1, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '1', 'dir': 'jupyter-structured-clean-dedup', 'id': '53108', 'license': 'MIT', 'n_tokens_mistral': 662, 'n_tokens_neox': 576, 'n_words': 192, 'path': '02_MNIST_digit_classification_with_Keras.ipynb', 'repo_name': 'alzaia/keras_projects', 'size': '1865'}