Creating a Deep Neural Network (DNN) from scratch in Python involves several steps. For simplicity, I will use the popular library TensorFlow with Keras, which provides a higher-level, user-friendly API to build and train neural networks. Below is a simple example of a DNN using Keras for a classification task. We'll use the popular MNIST dataset, which contains handwritten digits.
First, ensure you have TensorFlow installed in your environment. If not, you can install it using pip:
pip install tensorflow
Then, you can create a Python script as follows:
import tensorflow as tf
from tensorflow.keras import layers, models
from tensorflow.keras.datasets import mnist
from tensorflow.keras.utils import to_categorical
# Load the MNIST dataset
(train_images, train_labels), (test_images, test_labels) = mnist.load_data()
# Preprocess the data
train_images = train_images.reshape((60000, 28, 28, 1)).astype('float32') / 255
test_images = test_images.reshape((10000, 28, 28, 1)).astype('float32') / 255
# Convert labels to one-hot encoding
train_labels = to_categorical(train_labels)
test_labels = to_categorical(test_labels)
# Build the DNN model
model = models.Sequential()
model.add(layers.Flatten(input_shape=(28, 28, 1)))
model.add(layers.Dense(512, activation='relu'))
model.add(layers.Dense(256, activation='relu'))
model.add(layers.Dense(10, activation='softmax'))
# Compile the model
model.compile(optimizer='adam',
loss='categorical_crossentropy',
metrics=['accuracy'])
# Train the model
model.fit(train_images, train_labels, epochs=5, batch_size=128, validation_split=0.2)
# Evaluate the model
test_loss, test_acc = model.evaluate(test_images, test_labels)
print(f'Test accuracy: {test_acc}')
Explanation:
-
Data Loading and Preprocessing:
- MNIST data is loaded using
mnist.load_data().
- Images are normalized to values between 0 and 1.
- Labels are converted to one-hot encoded vectors.
-
Model Construction:
- A sequential model is created using Keras.
- The first layer flattens the 28x28 image into a 784-dimensional vector.
- Two Dense (fully connected) layers with 512 and 256 neurons respectively, using ReLU as the activation function.
- The last Dense layer has 10 neurons (for 10 classes) with a softmax activation function, which outputs a probability distribution.
-
Compilation:
- The model is compiled with the Adam optimizer and categorical cross-entropy loss function.
- Accuracy is used as the metric for evaluation.
-
Training:
- The model is trained with a batch size of 128 over 5 epochs.
- Validation split of 0.2 is used to assess the model's performance during training.
-
Evaluation:
- The model's accuracy is evaluated on the test dataset.
This script should give you a good starting point for implementing a DNN using TensorFlow and Keras. You can further experiment with the architecture by adding more layers, changing the number of neurons, or using different activation functions.