To convert the given functions into a class, we encapsulate the model-related operations within a class structure. The class MLPModel handles initialization, training, evaluation, and weight management. Here's the implementation:
import numpy as np
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
from tensorflow.keras.optimizers import Adam
class MLPModel:
def __init__(self, input_shape, initial_weights=None):
"""
Initialize the MLP model.
Args:
input_shape (tuple): Shape of the input data (excluding batch size).
initial_weights (list, optional): Initial weights to set for the model.
If None, default random initialization is used.
"""
self.input_shape = input_shape
self.model = self._build_model(initial_weights)
def _build_model(self, initial_weights):
"""
Construct the Sequential model and compile it.
Args:
initial_weights: Initial weights for the model.
Returns:
Compiled Keras model.
"""
model = Sequential([
Dense(5, input_shape=self.input_shape, activation='relu', name='layer1'),
Dense(5, activation='relu', name='layer2'),
Dense(1, activation='linear', name='layer3')
])
if initial_weights is not None:
model.set_weights(initial_weights)
model.compile(optimizer=Adam(0.01), loss='mse')
return model
@staticmethod
def get_initial_weights():
"""
Generate predefined initial weights for the model.
Returns:
list: List of numpy arrays representing the weights.
"""
weights = [
# Layer 1 weights (2x5) and bias (5,)
np.array([[0.5, -0.5, 0.2, -0.6, 0.1],
[0.5, -0.5, 0.2, -0.6, 0.1]], dtype=np.float32),
np.array([0.0, 0.0, 0.0, 0.0, 0.0], dtype=np.float32),
# Layer 2 weights (5x5) and bias (5,)
np.array([[0.5, -0.5, 0.2, -0.6, 0.1],
[0.5, -0.5, 0.2, -0.6, 0.1],
[0.5, -0.5, 0.2, -0.6, 0.1],
[0.5, -0.5, 0.2, -0.6, 0.1],
[0.5, -0.5, 0.2, -0.6, 0.1]], dtype=np.float32),
np.array([0.0, 0.0, 0.0, 0.0, 0.0], dtype=np.float32),
# Layer 3 weights (5x1) and bias (1,)
np.array([[0.5], [-0.5], [0.2], [-0.6], [0.1]], dtype=np.float32),
np.array([0.0], dtype=np.float32)
]
return weights
def train(self, x_train, y_train, epochs=100, batch_size=32, verbose=0):
"""
Train the model on the given data.
Args:
x_train (np.array): Training input data.
y_train (np.array): Training target data.
epochs (int): Number of training epochs.
batch_size (int): Batch size for training.
verbose (int): Verbosity mode (0, 1, or 2).
Returns:
History: Training history object.
"""
history = self.model.fit(
x_train, y_train,
epochs=epochs,
batch_size=batch_size,
verbose=verbose
)
return history
def evaluate(self, x_test, y_test, verbose=0):
"""
Evaluate the model on test data.
Args:
x_test (np.array): Test input data.
y_test (np.array): Test target data.
verbose (int): Verbosity mode.
Returns:
float: Test loss.
"""
loss = self.model.evaluate(
x_test, y_test,
verbose=verbose
)
return loss
Key Changes and Improvements:
-
Encapsulation:
- The model construction (
_build_model), weight initialization (get_initial_weights), training (train), and evaluation (evaluate) are now methods of the class.
- Internal implementation details (like model compilation) are hidden within the class.
-
Initialization:
- The
__init__ method accepts input_shape and optional initial_weights, setting up the model immediately upon instantiation.
-
Static Method:
get_initial_weights is a static method since it doesn't depend on instance-specific data.
-
Training and Evaluation:
- Parameters like
epochs, batch_size, and verbose are configurable in the train and evaluate methods.
Usage Example:
# Initialize model with predefined weights
initial_weights = MLPModel.get_initial_weights()
model = MLPModel(input_shape=(2,), initial_weights=initial_weights)
# Train the model
history = model.train(x_train, y_train, epochs=100, verbose=1)
# Evaluate the model
loss = model.evaluate(x_test, y_test)
print(f"Test Loss: {loss}")
This class-based approach enhances modularity, reusability, and maintains the original functionality while providing a cleaner interface.