Examples Gallery
Comprehensive collection of examples demonstrating the power and flexibility of the AI/ML Framework. From basic preprocessing to advanced deep learning and deployment.
Quick Start Examples
Get started immediately with these simple yet powerful examples.
Classification
BeginnerBuild a classification model with automatic preprocessing and model selection.
from ai_ml_framework import PipelineCreator
import pandas as pd
# Load data
df = pd.read_csv('classification_data.csv')
# Create automated pipeline
pipeline = PipelineCreator()
model = pipeline.create_auto_pipeline(df, target='target')
# Evaluate
accuracy = model.score(df.drop('target', axis=1), df['target'])
print(f"Accuracy: {accuracy:.3f}")
Regression
BeginnerPredict continuous values with automated regression models and feature engineering.
from ai_ml_framework.auto_ml import AutoMLSelector
# Auto-select regression model
automl = AutoMLSelector(problem_type='regression')
best_model = automl.auto_select_and_train(X, y)
# Make predictions
predictions = best_model.predict(X_test)
print(f"RMSE: {np.sqrt(mean_squared_error(y_test, predictions)):.3f}")
Data Preprocessing Examples
Advanced data preprocessing techniques with automated analysis and recommendations.
from ai_ml_framework.preprocessing import DataAnalyzer
# Comprehensive data analysis
analyzer = DataAnalyzer()
analysis = analyzer.analyze_dataset(df, target_column='target')
# Get insights
print(f"Data quality score: {analysis['data_quality_score']:.2f}")
print(f"Feature types: {analysis['feature_types']}")
print(f"Missing values: {analysis['missing_values_summary']}")
print(f"Outliers detected: {analysis['outlier_summary']}")
# Get recommendations
recommendations = analyzer.get_preprocessing_recommendations(df)
for rec in recommendations:
print(f"Recommendation: {rec['action']} - {rec['reason']}")
from ai_ml_framework.preprocessing import AutoPreprocessor
# Handle missing values automatically
preprocessor = AutoPreprocessor(
target_column='target',
config={
'missing_values': {
'numeric_strategy': 'knn',
'categorical_strategy': 'mode'
}
}
)
# Fit and transform
X_processed, y_processed = preprocessor.fit_transform(df)
print(f"Missing values before: {df.isnull().sum().sum()}")
print(f"Missing values after: {X_processed.isnull().sum().sum()}")
# Advanced feature engineering
preprocessor = AutoPreprocessor(
target_column='target',
config={
'feature_engineering': {
'polynomial_features': True,
'interaction_features': True,
'feature_selection': True,
'selection_method': 'selectkbest',
'k': 50
}
}
)
X_processed, y_processed = preprocessor.fit_transform(df)
print(f"Original features: {df.shape[1]}")
print(f"Engineered features: {X_processed.shape[1]}")
AutoML Examples
Intelligent model selection, hyperparameter optimization, and ensemble creation.
Model Selection
IntermediateAutomatically select the best models for your dataset.
from ai_ml_framework.auto_ml import AutoMLSelector
# Initialize AutoML
automl = AutoMLSelector(
problem_type='classification',
models=['rf', 'xgb', 'lgb', 'catboost'],
cv_folds=5
)
# Auto-select and train multiple models
models = automl.auto_select_models(X_train, y_train)
print(f"Selected {len(models)} models")
# Compare performance
results = automl.evaluate_models(models, X_test, y_test)
for name, metrics in results.items():
print(f"{name}: {metrics['accuracy']:.3f}")
Hyperparameter Optimization
AdvancedOptimize model hyperparameters using advanced optimization algorithms.
from ai_ml_framework.auto_ml import HyperparameterOptimizer
# Optimize hyperparameters
optimizer = HyperparameterOptimizer(problem_type='classification')
# Define search space
search_space = {
'n_estimators': (100, 1000),
'max_depth': (3, 20),
'learning_rate': (0.01, 0.3)
}
# Run optimization
best_model, best_params = optimizer.optimize_model(
base_model, X_train, y_train,
search_space=search_space,
n_trials=100
)
print(f"Best parameters: {best_params}")
print(f"Best score: {best_model.score(X_test, y_test):.3f}")
Deep Learning Examples
Neural network architecture design, training, and visualization.
from ai_ml_framework.deep_learning import NeuralNetworkDesigner
# Design CNN architecture
designer = NeuralNetworkDesigner()
recommendations = designer.get_ai_recommendations(
input_shape=(28, 28, 1),
problem_type='classification',
num_classes=10
)
# Create CNN model
cnn_layers = [
{'type': 'Conv2D', 'filters': 32, 'kernel_size': (3, 3)},
{'type': 'MaxPooling2D', 'pool_size': (2, 2)},
{'type': 'Conv2D', 'filters': 64, 'kernel_size': (3, 3)},
{'type': 'Flatten'},
{'type': 'Dense', 'units': 128, 'activation': 'relu'},
{'type': 'Dense', 'units': 10, 'activation': 'softmax'}
]
model = designer.create_network((28, 28, 1), cnn_layers, 'classification', 10)
# LSTM for sequential data
lstm_layers = [
{'type': 'LSTM', 'units': 50, 'return_sequences': True},
{'type': 'Dropout', 'rate': 0.2},
{'type': 'LSTM', 'units': 50},
{'type': 'Dropout', 'rate': 0.2},
{'type': 'Dense', 'units': 1, 'activation': 'sigmoid'}
]
lstm_model = designer.create_network(
input_shape=(10, 1), # 10 timesteps, 1 feature
layers=lstm_layers,
problem_type='regression'
)
# Train LSTM
trainer = DeepLearningTrainer(lstm_model, 'regression')
trainer.compile_model('adam', 'mse')
history = trainer.train(X_train, y_train, validation_data=(X_test, y_test))
# Custom architecture with AI recommendations
recommendations = designer.get_ai_recommendations(
input_shape=(64, 64, 3),
problem_type='classification',
num_classes=100
)
print("AI Recommended Architecture:")
for layer in recommendations['layers']:
print(f" {layer['type']}: {layer.get('params', {})}")
# Create model with recommendations
model = designer.create_network(
input_shape=(64, 64, 3),
layers=recommendations['layers'],
problem_type='classification',
num_classes=100
)
# Visualize architecture
visualizer = NetworkVisualizer()
visualizer.plot_model_architecture(model, save_path='architecture.png')
Real World Use Cases
Practical examples from real-world applications and industries.
Credit Scoring
FinanceBuild a credit scoring model with automated feature engineering and explainable AI.
# Credit scoring pipeline
from ai_ml_framework import PipelineCreator
from ai_ml_framework.utils import ExplainabilityAnalyzer
# Create pipeline with explainability
pipeline = PipelineCreator()
model = pipeline.create_auto_pipeline(
credit_data,
target='credit_risk',
config={'explainability': True}
)
# Explain predictions
explainer = ExplainabilityAnalyzer(model)
shap_values = explainer.explain_predictions(X_test)
explainer.plot_feature_importance(shap_values)
Fraud Detection
SecurityReal-time fraud detection with anomaly detection and ensemble methods.
# Fraud detection with ensemble
from ai_ml_framework.auto_ml import AutoMLSelector
# Handle imbalanced data
automl = AutoMLSelector(
problem_type='classification',
handle_imbalance=True,
ensemble_method='stacking'
)
# Train ensemble model
ensemble_model = automl.auto_select_and_train(
X_train, y_train,
sample_weight='balanced'
)
# Real-time prediction
def detect_fraud(transaction):
prediction = ensemble_model.predict_proba([transaction])
return prediction[0][1] > 0.95
Customer Churn
MarketingPredict customer churn with survival analysis and targeted recommendations.
# Customer churn prediction
from ai_ml_framework.auto_ml import AutoMLSelector
from ai_ml_framework.utils import SurvivalAnalyzer
# Train churn model
automl = AutoMLSelector(
problem_type='classification',
time_to_event='churn_time',
event_indicator='churned'
)
churn_model = automl.auto_select_and_train(customer_data, y)
# Survival analysis
survival_analyzer = SurvivalAnalyzer(churn_model)
survival_curves = survival_analyzer.predict_survival(X_test)
survival_analyzer.plot_survival_curves(survival_curves)