Certainly! Below is a comprehensive implementation of a Fractal Neural Network using TensorFlow's Keras API. This code is designed to run seamlessly on Google Colab without requiring any additional downloads beyond standard library installations.
What is a Fractal Neural Network?
A Fractal Neural Network (FractalNet) is a type of deep neural network architecture that leverages fractal structures to enable very deep models without the vanishing gradient problem typically associated with increasing depth. The fractal architecture recursively constructs subnetworks, allowing for efficient gradient flow and promoting feature reuse across different scales of the network.
Features of This Implementation:
- Recursive Fractal Blocks: The network is built using fractal modules that recursively stack convolutional layers.
- Residual Connections: Incorporates residual connections to facilitate better gradient flow.
- Flexibility: Easily adjustable depth and complexity by changing the number of fractal levels.
- Standard Dataset: Demonstrated on the CIFAR-10 dataset for image classification.
Complete Code Implementation
You can copy and paste this entire code into a Google Colab notebook and run it directly.
# Fractal Neural Network Implementation in TensorFlow Keras
# Designed to run on Google Colab without the need for additional downloads.
import tensorflow as tf
from tensorflow.keras import layers, models, regularizers
from tensorflow.keras.datasets import cifar10
from tensorflow.keras.utils import to_categorical
import numpy as np
# Set random seeds for reproducibility
tf.random.set_seed(42)
np.random.seed(42)
def residual_block(x, filters, kernel_size=3, stride=1, activation='relu'):
"""
Defines a residual block with two convolutional layers and a skip connection.
"""
shortcut = x
x = layers.Conv2D(filters, kernel_size, strides=stride, padding='same',
kernel_initializer='he_normal',
kernel_regularizer=regularizers.l2(1e-4))(x)
x = layers.BatchNormalization()(x)
x = layers.Activation(activation)(x)
x = layers.Conv2D(filters, kernel_size, strides=1, padding='same',
kernel_initializer='he_normal',
kernel_regularizer=regularizers.l2(1e-4))(x)
x = layers.BatchNormalization()(x)
# If the input and output shapes are different, adjust the shortcut
if shortcut.shape[-1] != filters or stride != 1:
shortcut = layers.Conv2D(filters, 1, strides=stride, padding='same',
kernel_initializer='he_normal',
kernel_regularizer=regularizers.l2(1e-4))(shortcut)
shortcut = layers.BatchNormalization()(shortcut)
x = layers.add([x, shortcut])
x = layers.Activation(activation)(x)
return x
def fractal_module(x, filters, depth):
"""
Recursively constructs a fractal module.
"""
if depth == 1:
return residual_block(x, filters)
else:
# Split into two paths with depth-1
path1 = fractal_module(x, filters, depth-1)
path2 = fractal_module(x, filters, depth-1)
# Concatenate the outputs of the two paths
x = layers.concatenate([path1, path2])
# Apply a 1x1 convolution to merge the paths
x = layers.Conv2D(filters, 1, padding='same',
kernel_initializer='he_normal',
kernel_regularizer=regularizers.l2(1e-4))(x)
x = layers.BatchNormalization()(x)
x = layers.Activation('relu')(x)
return x
def build_fractal_model(input_shape, num_classes, num_filters=64, fractal_depth=3):
"""
Builds the Fractal Neural Network model.
"""
inputs = layers.Input(shape=input_shape)
x = layers.Conv2D(num_filters, 3, padding='same',
kernel_initializer='he_normal',
kernel_regularizer=regularizers.l2(1e-4))(inputs)
x = layers.BatchNormalization()(x)
x = layers.Activation('relu')(x)
# Apply multiple fractal modules
for _ in range(3):
x = fractal_module(x, num_filters, fractal_depth)
x = layers.MaxPooling2D(pool_size=2)(x)
num_filters *= 2 # Double the number of filters at each stage
x = layers.GlobalAveragePooling2D()(x)
x = layers.Dense(num_classes, activation='softmax',
kernel_initializer='he_normal')(x)
model = models.Model(inputs=inputs, outputs=x)
return model
# Load and preprocess CIFAR-10 dataset
def load_preprocess_data():
(x_train, y_train), (x_test, y_test) = cifar10.load_data()
# Normalize pixel values
x_train = x_train.astype('float32') / 255.0
x_test = x_test.astype('float32') / 255.0
# One-hot encode labels
y_train = to_categorical(y_train, 10)
y_test = to_categorical(y_test, 10)
return x_train, y_train, x_test, y_test
# Define training parameters
batch_size = 128
epochs = 50
learning_rate = 0.001
# Prepare the data
x_train, y_train, x_test, y_test = load_preprocess_data()
# Build the model
input_shape = x_train.shape[1:]
num_classes = 10
model = build_fractal_model(input_shape, num_classes, fractal_depth=3)
# Compile the model
optimizer = tf.keras.optimizers.Adam(learning_rate=learning_rate)
model.compile(optimizer=optimizer,
loss='categorical_crossentropy',
metrics=['accuracy'])
# Print the model summary
model.summary()
# Define callbacks
callbacks = [
tf.keras.callbacks.ReduceLROnPlateau(monitor='val_loss', factor=0.5,
patience=5, min_lr=1e-6, verbose=1),
tf.keras.callbacks.EarlyStopping(monitor='val_loss', patience=15,
restore_best_weights=True, verbose=1)
]
# Train the model
history = model.fit(x_train, y_train,
batch_size=batch_size,
epochs=epochs,
validation_split=0.1,
callbacks=callbacks,
verbose=1)
# Evaluate the model on test data
test_loss, test_accuracy = model.evaluate(x_test, y_test, verbose=2)
print(f'\nTest accuracy: {test_accuracy * 100:.2f}%')
Code Explanation
-
Imports and Setup:
- TensorFlow and Keras: Core libraries for building and training the neural network.
- CIFAR-10 Dataset: A standard dataset for image classification tasks.
- Utilities: For data preprocessing and ensuring reproducibility.
-
Residual Blocks:
- Implements the concept of residual connections, allowing the network to learn identity mappings which help in training deeper networks.
-
Fractal Modules:
- Uses recursion to build a fractal structure. Each fractal module splits into multiple paths, processes them, and then merges them back. This design promotes feature reuse and efficient gradient flow.
-
Model Building:
- The
build_fractal_model function constructs the overall network architecture by stacking convolutional layers and fractal modules. The number of filters doubles after each fractal module to capture more complex features at deeper layers.
-
Data Loading and Preprocessing:
- Loads the CIFAR-10 dataset, normalizes the pixel values, and one-hot encodes the labels for training.
-
Training Configuration:
- Defines training parameters such as batch size, number of epochs, and learning rate.
- Uses callbacks like
ReduceLROnPlateau to adjust the learning rate during training and EarlyStopping to prevent overfitting.
-
Model Compilation and Training:
- Compiles the model with the Adam optimizer and categorical cross-entropy loss.
- Trains the model on the training set while validating on a subset of data.
-
Evaluation:
- After training, the model is evaluated on the test set to determine its accuracy.
Running the Code on Google Colab
-
Open Google Colab:
-
Copy and Paste the Code:
- Insert a new code cell and paste the entire code provided above.
-
Run the Cell:
- Execute the cell by pressing
Shift + Enter or clicking the run button.
-
Monitor Training:
- The model summary, training progress, and final test accuracy will be displayed as the code runs.
Notes:
-
Training Time: Fractal neural networks can be computationally intensive due to their recursive architecture. Ensure that you have sufficient GPU resources enabled in Colab (Runtime > Change runtime type > Hardware accelerator > GPU).
-
Adjusting Complexity: You can modify the fractal_depth parameter to increase or decrease the complexity of the fractal modules. Higher depth results in more complex and deeper networks.
-
Further Enhancements: Consider implementing data augmentation, regularization techniques, or more advanced optimization algorithms to potentially improve performance.
Feel free to experiment with the architecture and training parameters to suit your specific needs!