How to Build a Simple Neural Network with Keras: A Step-by-Step Tutorial
Keras, now part of TensorFlow, is one of the easiest deep learning frameworks to get started with. In this tutorial, you’ll build a feedforward neural network for classifying handwritten digits from the MNIST dataset. You only need basic Python knowledge and a few lines of code.
First, install TensorFlow (which includes Keras) using pip: pip install tensorflow. Then import the required modules and load the MNIST data.

1. Load and Preprocess the Data
Keras provides built-in datasets. Use keras.datasets.mnist.load_data() to get training and test images (28×28 pixels). Normalize pixel values to the range [0,1] by dividing by 255.0. Then flatten the 2D images into 1D vectors of 784 features.
from tensorflow import keras
(x_train, y_train), (x_test, y_test) = keras.datasets.mnist.load_data()
x_train = x_train.reshape(-1, 784).astype('float32') / 255.0
x_test = x_test.reshape(-1, 784).astype('float32') / 255.0
2. Build the Model with the Sequential API
Create a sequential model by stacking layers. Use a hidden layer with 128 neurons and ReLU activation, then an output layer with 10 neurons (one per digit) and softmax activation.
model = keras.Sequential([
keras.layers.Dense(128, activation='relu', input_shape=(784,)),
keras.layers.Dense(10, activation='softmax')
])
3. Compile and Train the Model
Compile the model with the Adam optimizer, sparse categorical crossentropy loss (for integer labels), and accuracy metric. Train for 5 epochs with a batch size of 32.
model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
history = model.fit(x_train, y_train, epochs=5, batch_size=32, validation_split=0.2)
4. Evaluate on Test Data
After training, evaluate the model on the test set to measure real-world performance.
test_loss, test_acc = model.evaluate(x_test, y_test)
print(f"Test accuracy: {test_acc:.4f}")
Conclusion
You’ve built and trained a simple neural network with Keras in just a few lines. From here, experiment with more layers, different activation functions, or try a convolutional network for image data. Keras makes deep learning accessible—happy coding!