Today we are going to build a script in using the popular library TensorFlow to train a simple artificial neural network to classify images of clothing.
This script loads the Fashion MNIST dataset, which consists of 60,000 28×28 grayscale images of clothing and accessories, along with their corresponding labels. It then scales the input data, builds a model with a single fully-connected hidden layer and an output layer with 10 units (one for each class), compiles the model with the Adam optimizer and the categorical cross-entropy loss function, trains the model for 5 epochs, and finally evaluates the model on the test data.
import tensorflow as tf
# Load the dataset
(x_train, y_train), (x_test, y_test) = tf.keras.datasets.fashion_mnist.load_data()
# Scale the input data
x_train = x_train / 255.0
x_test = x_test / 255.0
# Build the model
model = tf.keras.Sequential([
tf.keras.layers.Flatten(input_shape=(28, 28)),
tf.keras.layers.Dense(128, activation='relu'),
tf.keras.layers.Dense(10, activation='softmax')
])
# Compile the model
model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
# Train the model
model.fit(x_train, y_train, epochs=5)
# Evaluate the model
test_loss, test_acc = model.evaluate(x_test, y_test)
print('Test accuracy:', test_acc)
Output:
As can be seen above, we have achieved an accuracy of almost 90% which is pretty good.