Keras MNIST Classification Function

  • Share this:

Code introduction


This code defines a function that uses the Keras library to classify the MNIST dataset. It first loads the dataset, then preprocesses the data, then constructs a simple neural network model, compiles and trains the model, and finally evaluates the model performance.


Technology Stack : Keras, MNIST dataset, neural network, model training, model evaluation

Code Type : The type of code

Code Difficulty :


                
                    
def random_mnist_classification(input_shape, num_classes):
    from keras.models import Sequential
    from keras.layers import Dense, Flatten
    from keras.datasets import mnist
    from keras.utils import to_categorical

    # Load MNIST dataset
    (x_train, y_train), (x_test, y_test) = mnist.load_data()

    # Preprocess data
    x_train = x_train.reshape((x_train.shape[0], *input_shape))
    x_test = x_test.reshape((x_test.shape[0], *input_shape))
    y_train = to_categorical(y_train, num_classes)
    y_test = to_categorical(y_test, num_classes)

    # Create model
    model = Sequential()
    model.add(Flatten(input_shape=input_shape))
    model.add(Dense(128, activation='relu'))
    model.add(Dense(num_classes, activation='softmax'))

    # Compile model
    model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])

    # Train model
    model.fit(x_train, y_train, epochs=5, batch_size=32, validation_data=(x_test, y_test))

    # Evaluate model
    loss, accuracy = model.evaluate(x_test, y_test)
    return loss, accuracy