python-kerasHow can I use Python Keras to create a machine learning model for the MNIST dataset?
To use Python Keras to create a machine learning model for the MNIST dataset, you can follow the steps below:
- Import the necessary libraries:
import keras
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers import Dense
- Load the data:
(x_train, y_train), (x_test, y_test) = mnist.load_data()
- Preprocess the data:
x_train = x_train.reshape(60000, 784)
x_test = x_test.reshape(10000, 784)
x_train = x_train.astype('float32')
x_test = x_test.astype('float32')
x_train /= 255
x_test /= 255
- Create the model:
model = Sequential()
model.add(Dense(512, activation='relu', input_shape=(784,)))
model.add(Dense(10, activation='softmax'))
- Compile the model:
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
- Fit the model:
model.fit(x_train, y_train, batch_size=128, epochs=10, verbose=1)
- Evaluate the model:
score = model.evaluate(x_test, y_test, verbose=0)
print('Test loss:', score[0])
print('Test accuracy:', score[1])
Output example
Test loss: 0.07912476190745235
Test accuracy: 0.9776
Helpful links
More of Python Keras
- How do I use Python Keras to zip a file?
- How can I use Python Keras to develop a reinforcement learning model?
- How do I save weights in a Python Keras model?
- How do I create a simple example using Python and Keras?
- How to load a model in Python Keras?
- How do I use zero padding in Python Keras?
- How can I resolve the issue of Python module Tensorflow.keras not being found?
- How can I use YOLO with Python and Keras?
- How can I use XGBoost, Python and Keras together to build a machine learning model?
- How can I use word2vec and Keras to develop a machine learning model in Python?
See more codes...