Usage Examples¶
This page provides practical examples of using the interpylate-fls Python package.
Example 1: Basic Training and Prediction¶
Step 1: Import Required Modules
from interpylate_fls.data import DataLoader
from interpylate_fls.neuralnetwork import NeuralNetwork
import numpy as np
Step 2: Load and Preprocess Dataset
# Initialize DataLoader with path to your pickle file
data_loader = DataLoader("path/to/your/dataset.pkl")
# Load the dataset
df = data_loader.load_dataset()
# Inspect and preprocess the data (splits into train/val/test and standardizes)
X_train, X_test, X_val, y_train, y_test, y_val, num_features, num_samples, target_range = data_loader.inspect_data(df)
print(f"Dataset loaded: {num_samples} samples, {num_features} features")
print(f"Target range: {target_range}")
Step 3: Initialize and Train Neural Network
# Initialize neural network with default settings
model = NeuralNetwork(
X_train=X_train,
y_train=y_train,
X_val=X_val,
y_val=y_val,
X_test=X_test,
y_test=y_test,
input_size=5,
num_hidden_layers=2,
hidden_layer_sizes=[64, 32],
learning_rate=0.001,
epochs=100,
seed=42
)
# Train the model
model.train(verbose=True)
Step 4: Make Predictions
# Make a prediction for a single input
input_features = [0.5, 0.3, 0.7, 0.2, 0.6]
prediction = model.predict(input_features)
print(f"Prediction for {input_features}: {prediction}")
Expected Outcome:
The model will train for 100 epochs and display progress every 10% of epochs. After training, you can make predictions for any 5-dimensional input. The prediction will be a single float value representing the interpolated output.
Example 2: Custom Hyperparameter Tuning¶
This example demonstrates how to experiment with different hyperparameters to improve model performance.
from interpylate_fls.data import DataLoader
from interpylate_fls.neuralnetwork import NeuralNetwork
# Load and preprocess data (same as Example 1)
data_loader = DataLoader("path/to/your/dataset.pkl")
df = data_loader.load_dataset()
X_train, X_test, X_val, y_train, y_test, y_val, _, _, _ = data_loader.inspect_data(df)
# Initialize neural network with custom architecture
model = NeuralNetwork(
X_train=X_train,
y_train=y_train,
X_val=X_val,
y_val=y_val,
X_test=X_test,
y_test=y_test,
input_size=5,
num_hidden_layers=5,
hidden_layer_sizes=[64, 64, 64, 64, 64],
learning_rate=0.001,
epochs=150,
seed=42
)
# Train the model
model.train(verbose=True)
# Evaluate model performance
mse, r2 = model.evaluate()
print(f"Test MSE: {mse:.4f}")
print(f"Test R²: {r2:.4f}")
Expected Outcome:
The model will train for 150 epochs with a deeper architecture. After training, you can evaluate the model’s performance using the evaluate() method, which returns the Mean Squared Error (MSE) and R² score on the test set. Compare these metrics with simpler architectures to find the best configuration for your dataset.
Example 3: Complete Workflow with Visualization¶
This example shows a complete workflow including data loading, training, evaluation, and generating visualisations.
from interpylate_fls.data import DataLoader
from interpylate_fls.neuralnetwork import NeuralNetwork
from interpylate_fls.plotter import Plotter
import numpy as np
# Step 1: Load and preprocess data
data_loader = DataLoader("path/to/your/dataset.pkl")
df = data_loader.load_dataset()
X_train, X_test, X_val, y_train, y_test, y_val, num_features, num_samples, target_range = data_loader.inspect_data(df)
print(f"Loaded dataset: {num_samples} samples")
# Step 2: Initialize and train model
model = NeuralNetwork(
X_train=X_train,
y_train=y_train,
X_val=X_val,
y_val=y_val,
X_test=X_test,
y_test=y_test,
input_size=5,
num_hidden_layers=3,
hidden_layer_sizes=[32, 64, 32],
learning_rate=0.001,
epochs=100,
seed=42
)
# Train the model
model.train(verbose=True)
# Step 3: Evaluate model
mse, r2 = model.evaluate()
print(f"\nModel Performance:")
print(f" MSE: {mse:.4f}")
print(f" R²: {r2:.4f}")
# Step 4: Generate learning curve plot
Plotter.save_learning_curve(
training_history=model.train_losses,
val_history=model.val_losses,
save_path="learning_curve.png"
)
print("\nLearning curve saved to 'learning_curve.png'")
# Step 5: Generate predictions vs actual plot
# Convert test predictions to numpy array
y_pred_np = model.y_pred_test.cpu().detach().numpy()
y_test_np = model.y_test.cpu().detach().numpy()
Plotter.save_predictions_vs_actual(
y_true=y_test_np,
y_pred=y_pred_np,
save_path="predictions_vs_actual.png"
)
print("Predictions vs actual plot saved to 'predictions_vs_actual.png'")
# Step 6: Make predictions for new inputs
new_inputs = [
[0.1, 0.2, 0.3, 0.4, 0.5],
[0.6, 0.7, 0.8, 0.9, 1.0],
[0.5, 0.5, 0.5, 0.5, 0.5]
]
print("\nPredictions for new inputs:")
for input_features in new_inputs:
prediction = model.predict(input_features)
print(f" Input {input_features} -> Prediction: {prediction}")
Expected Outcome:
This complete workflow will:
Load and preprocess your dataset
Train a neural network with a custom architecture
Evaluate the model and display performance metrics
Generate and save a learning curve visualization
Generate and save a predictions vs actual values plot
Make predictions for multiple new input samples
The visualisation plots will be saved as PNG files that you can use to analyse model performance.
Tips for Using the Package¶
Always ensure your dataset pickle file contains the required structure (
X,y, andmetadatakeys)Experiment with different architectures and hyperparameters to find the best configuration for your data
Use the validation set performance to monitor for overfitting during training
The learning curve plots help visualise training progress and identify if more epochs are needed
Frontend Usage Examples¶
This section provides examples of using the web application frontend to train neural networks and make predictions.
Example 1: Basic Neural Network Training and Prediction¶
This example demonstrates how to use the web interface to create a basic neural network and make predictions.
Step 1: Access the Application
Open your web browser and navigate to http://localhost:3000.
Step 2: Upload Your Dataset
Click the “Choose .pkl File” button
Select a pickle file containing your 5D dataset
The file must contain: -
X: numpy array of features with shape (n_samples, 5) -y: numpy array of target values with shape (n_samples,) -metadata: dictionary withfeature_namesandtarget_nameOnce uploaded, the dataset name will be displayed on the page
Step 3: Configure Neural Network Architecture
Set the number of hidden layers to 3 (using the slider)
Configure neuron counts for each layer: - Layer 1: 16 neurons - Layer 2: 32 neurons - Layer 3: 64 neurons
Step 4: Configure Training Parameters
Set the number of epochs to 100 (using the slider, range: 5-200)
Set the learning rate to 0.001 (using the slider, range: 0.0001-0.001)
Step 5: Train the Model
Click the “Start Training” button
Wait for training to complete
View training statistics: - Training time - Mean Squared Error (MSE) - Dataset size information
Step 6: Analyse Model Performance
Click the “Analyse Model Performance” button
View the plot showing training and validation loss over epochs
View the predictions vs actual values scatter plot
Step 7: Make Predictions
Adjust the input sliders for x1, x2, x3, x4, x5 (values range from 0.0 to 1.0)
For example, set: - x1 = 0.5 - x2 = 0.3 - x3 = 0.7 - x4 = 0.2 - x5 = 0.6
Click the “Predict” button
View the predicted value displayed on the page
Example 2: Hyperparameter Tuning¶
This example demonstrates how to use the web application to experiment with different hyperparameters and find the optimal configuration for your dataset.
Step 1: Upload Your Dataset
Follow the same steps as Example 1 to upload your dataset.
Step 2: Initial Training with Default Settings
Start with default settings: - Number of layers: 3 - Neuron counts: [16, 32, 64] - Epochs: 100 - Learning rate: 0.001
Click “Start Training” and note the training time and MSE
Click “Analyse Model Performance” to view the learning curve
Step 3: Experiment with Deeper Architecture
Reset your application by clicking the “Reset” button.
Follow step 1.
Increase the number of hidden layers to 5
Set neuron counts to [64, 64, 64, 64, 64] for all layers
Keep epochs at 100 and learning rate at 0.001
Click “Start Training”
Compare the results with the previous configuration
Repeat these steps with different architectures and hyperparameters to find the optimal configuration for your dataset.
Step 4: Make Predictions with Optimised Model
Use the prediction sliders to test various input combinations
Verify that predictions are reasonable for your use case
Expected Outcome:
Through experimentation, you will identify the best combination of: - Number of hidden layers - Neuron counts per layer - Number of epochs - Learning rate