Certainly! Below is the complete, ready-to-run Python code that incorporates multiple real datasets accessible without paid APIs or subscriptions. The code includes functionality to load various datasets from sources like the UCI Machine Learning Repository, sklearn.datasets, and online CSV files. This will allow you to easily switch between different datasets for building predictive models.
Key Features:
- Multiple Dataset Support: Load datasets such as Iris, Wine, Breast Cancer, Titanic, and more.
- Easy Dataset Selection: Choose the dataset you want to use by specifying its name.
- Self-Optimizing Model: Utilize the
SelfOptimizingModel class for automated hyperparameter tuning and model optimization.
- Extensible Structure: Easily add more datasets by following the provided examples.
import numpy as np
import pandas as pd
import random
import requests
from io import StringIO
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score, mean_squared_error, f1_score
from sklearn.preprocessing import StandardScaler, LabelEncoder
from sklearn.utils import shuffle
class SelfOptimizingModel:
def __init__(self, X, y, model_type='classification', algorithm='random_forest', random_state=42):
"""
Initializes the self-optimizing model.
Parameters:
- X: Features dataset (numpy array or pandas DataFrame).
- y: Target variable (numpy array or pandas Series).
- model_type: 'classification' or 'regression'.
- algorithm: Algorithm to use ('random_forest', 'neural_network', 'svm').
- random_state: Seed for reproducibility.
"""
self.X = X
self.y = y
self.model_type = model_type
self.algorithm = algorithm
self.random_state = random_state
self.best_params = None
self.best_score = float('-inf') if model_type == 'classification' else float('inf')
self.best_model = None
self._prepare_data()
def _prepare_data(self):
"""
Prepares training and validation datasets.
"""
# Shuffle and split the data
self.X, self.y = shuffle(self.X, self.y, random_state=self.random_state)
self.X_train, self.X_valid, self.y_train, self.y_valid = train_test_split(
self.X, self.y, test_size=0.2, random_state=self.random_state
)
# Feature scaling for certain models
if self.algorithm in ['neural_network', 'svm']:
scaler = StandardScaler()
self.X_train = scaler.fit_transform(self.X_train)
self.X_valid = scaler.transform(self.X_valid)
def _generate_hyperparameters(self):
"""
Generates random hyperparameters based on the algorithm.
"""
if self.algorithm == 'random_forest':
params = {
'n_estimators': random.choice([50, 100, 150, 200]),
'max_depth': random.choice([None, 5, 10, 20]),
'min_samples_split': random.choice([2, 5, 10]),
'min_samples_leaf': random.choice([1, 2, 4]),
'bootstrap': random.choice([True, False]),
}
elif self.algorithm == 'neural_network':
params = {
'hidden_layer_sizes': random.choice([(50,), (100,), (50, 50)]),
'activation': random.choice(['relu', 'tanh', 'logistic']),
'solver': random.choice(['adam', 'sgd']),
'learning_rate': random.choice(['constant', 'adaptive']),
'max_iter': 200,
}
elif self.algorithm == 'svm':
params = {
'C': random.uniform(0.1, 10.0),
'kernel': random.choice(['linear', 'rbf', 'poly']),
'gamma': random.choice(['scale', 'auto']),
}
else:
raise ValueError("Unsupported algorithm specified.")
return params
def _initialize_model(self, params):
"""
Initializes the machine learning model with given parameters.
"""
if self.algorithm == 'random_forest':
if self.model_type == 'classification':
from sklearn.ensemble import RandomForestClassifier
model = RandomForestClassifier(random_state=self.random_state, **params)
else:
from sklearn.ensemble import RandomForestRegressor
model = RandomForestRegressor(random_state=self.random_state, **params)
elif self.algorithm == 'neural_network':
if self.model_type == 'classification':
from sklearn.neural_network import MLPClassifier
model = MLPClassifier(random_state=self.random_state, **params)
else:
from sklearn.neural_network import MLPRegressor
model = MLPRegressor(random_state=self.random_state, **params)
elif self.algorithm == 'svm':
if self.model_type == 'classification':
from sklearn.svm import SVC
model = SVC(random_state=self.random_state, **params)
else:
from sklearn.svm import SVR
model = SVR(**params)
else:
raise ValueError("Unsupported algorithm specified.")
return model
def train_and_optimize(self, iterations=10):
"""
Trains the model and optimizes hyperparameters over a number of iterations.
Parameters:
- iterations: Number of optimization iterations to perform.
"""
for i in range(iterations):
print(f"\nIteration {i+1}/{iterations}")
# Randomly adjust hyperparameters
params = self._generate_hyperparameters()
print(f"Testing hyperparameters: {params}")
# Initialize and train model
model = self._initialize_model(params)
model.fit(self.X_train, self.y_train)
# Validate model
score = self._validate_model(model)
# Update best model if improvement is seen
if self._is_improvement(score):
self.best_score = score
self.best_params = params
self.best_model = model
print(f"New best score: {self.best_score}")
else:
print(f"No improvement. Best score remains: {self.best_score}")
def _validate_model(self, model):
"""
Validates the model and returns the performance score.
"""
y_pred = model.predict(self.X_valid)
if self.model_type == 'classification':
score = accuracy_score(self.y_valid, y_pred)
print(f"Validation Accuracy: {score}")
else:
score = -mean_squared_error(self.y_valid, y_pred)
print(f"Validation Negative MSE: {score}")
return score
def _is_improvement(self, score):
"""
Checks if the new score is an improvement over the best score.
"""
if self.model_type == 'classification':
return score > self.best_score
else:
return score > self.best_score # Since score is negative MSE
def evaluate(self):
"""
Evaluates the best model on the validation set.
"""
if self.best_model is None:
raise Exception("No model has been trained yet.")
print("\nEvaluating the best model on validation data...")
y_pred = self.best_model.predict(self.X_valid)
if self.model_type == 'classification':
accuracy = accuracy_score(self.y_valid, y_pred)
f1 = f1_score(self.y_valid, y_pred, average='weighted')
print(f"Final Model Accuracy: {accuracy}")
print(f"Final Model F1 Score: {f1}")
return accuracy, f1
else:
mse = mean_squared_error(self.y_valid, y_pred)
print(f"Final Model MSE: {mse}")
return mse
def load_dataset(name):
"""
Loads a dataset based on the provided name.
Parameters:
- name: Name of the dataset to load.
Returns:
- X: Features as a pandas DataFrame.
- y: Target variable as a pandas Series.
- model_type: 'classification' or 'regression'.
"""
name = name.lower()
if name == 'iris':
from sklearn.datasets import load_iris
data = load_iris()
X = pd.DataFrame(data.data, columns=data.feature_names)
y = pd.Series(data.target)
model_type = 'classification'
elif name == 'wine':
from sklearn.datasets import load_wine
data = load_wine()
X = pd.DataFrame(data.data, columns=data.feature_names)
y = pd.Series(data.target)
model_type = 'classification'
elif name == 'breast_cancer':
from sklearn.datasets import load_breast_cancer
data = load_breast_cancer()
X = pd.DataFrame(data.data, columns=data.feature_names)
y = pd.Series(data.target)
model_type = 'classification'
elif name == 'titanic':
# Titanic dataset from Kaggle (public) via seaborn
import seaborn as sns
data = sns.load_dataset('titanic')
# Preprocessing
data = data.dropna(subset=['embarked', 'age', 'fare', 'sex', 'class', 'survived'])
X = data[['pclass', 'sex', 'age', 'sibsp', 'parch', 'fare', 'embarked']]
y = data['survived']
# Encode categorical variables
X = pd.get_dummies(X, drop_first=True)
y = y.astype(int)
model_type = 'classification'
elif name == 'housing':
# California Housing dataset from sklearn
from sklearn.datasets import fetch_california_housing
data = fetch_california_housing()
X = pd.DataFrame(data.data, columns=data.feature_names)
y = pd.Series(data.target)
model_type = 'regression'
elif name == 'car_evaluation':
# Car Evaluation dataset from UCI
url = "https://archive.ics.uci.edu/ml/machine-learning-databases/car/car.data"
response = requests.get(url)
if response.status_code != 200:
raise Exception("Failed to load the Car Evaluation dataset.")
column_names = ['buying', 'maint', 'doors', 'persons', 'lug_boot', 'safety', 'class']
data = pd.read_csv(StringIO(response.text), header=None, names=column_names)
# Preprocessing
X = data.drop('class', axis=1)
y = data['class']
# Encode categorical variables
X = pd.get_dummies(X, drop_first=True)
le = LabelEncoder()
y = le.fit_transform(y)
model_type = 'classification'
else:
raise ValueError(f"Dataset '{name}' is not supported.")
return X, y, model_type
# Example usage
if __name__ == '__main__':
import argparse
# Define available datasets
available_datasets = [
'iris',
'wine',
'breast_cancer',
'titanic',
'housing',
'car_evaluation'
]
# Parse command-line arguments
parser = argparse.ArgumentParser(description='Self-Optimizing ML Model with Multiple Datasets')
parser.add_argument('--dataset', type=str, default='iris', choices=available_datasets,
help='Name of the dataset to use.')
parser.add_argument('--model_type', type=str, default=None, choices=['classification', 'regression'],
help='Type of model. If not specified, inferred from the dataset.')
parser.add_argument('--algorithm', type=str, default='random_forest', choices=['random_forest', 'neural_network', 'svm'],
help='Machine learning algorithm to use.')
parser.add_argument('--iterations', type=int, default=10,
help='Number of hyperparameter optimization iterations.')
args = parser.parse_args()
# Load the dataset
print(f"Loading dataset '{args.dataset}'...")
X, y, inferred_model_type = load_dataset(args.dataset)
# Determine model type
model_type = args.model_type if args.model_type else inferred_model_type
print(f"Model type: {model_type}")
# Initialize self-optimizing model
model = SelfOptimizingModel(X, y, model_type=model_type, algorithm=args.algorithm)
# Train and optimize
model.train_and_optimize(iterations=args.iterations)
# Evaluate the best model
model.evaluate()
How to Use the Code
-
Prerequisites:
-
Ensure you have Python installed (preferably version 3.6 or higher).
-
Install the required Python libraries if you haven't already:
pip install numpy pandas scikit-learn seaborn requests
-
Save the Code:
- Save the above code in a Python file, e.g.,
self_optimizing_model.py.
-
Run the Code:
-
You can run the script from the command line and specify the dataset you want to use. Here's the general usage:
python self_optimizing_model.py --dataset DATASET_NAME --algorithm ALGORITHM --iterations N
-
Parameters:
--dataset: Name of the dataset to use. Available options:
iris
wine
breast_cancer
titanic
housing
car_evaluation
--model_type: Type of model (classification or regression). If not specified, it will be inferred based on the dataset.
--algorithm: Machine learning algorithm to use. Options:
random_forest (default)
neural_network
svm
--iterations: Number of hyperparameter optimization iterations (default is 10).
-
Examples:
-
Using the Iris Dataset with Random Forest:
python self_optimizing_model.py --dataset iris --algorithm random_forest --iterations 10
-
Using the Titanic Dataset with SVM:
python self_optimizing_model.py --dataset titanic --algorithm svm --iterations 15
-
Using the California Housing Dataset with Neural Network:
python self_optimizing_model.py --dataset housing --algorithm neural_network --iterations 20
-
Adding More Datasets
To add more datasets, follow these steps:
-
Choose a Dataset:
- Ensure the dataset is publicly available and can be accessed via a direct URL or through existing Python libraries.
-
Implement the Loading Function:
- Add an
elif block in the load_dataset function.
- Load the dataset into a pandas DataFrame for
X and a pandas Series for y.
- Perform any necessary preprocessing, such as handling missing values or encoding categorical variables.
- Specify the
model_type based on whether it's a classification or regression problem.
-
Update Available Datasets:
- Add the dataset name to the
available_datasets list.
-
Example: Adding the "Adult" Dataset from UCI:
elif name == 'adult':
# Adult dataset from UCI
url = "https://archive.ics.uci.edu/ml/machine-learning-databases/adult/adult.data"
response = requests.get(url)
if response.status_code != 200:
raise Exception("Failed to load the Adult dataset.")
column_names = [
'age', 'workclass', 'fnlwgt', 'education', 'education_num',
'marital_status', 'occupation', 'relationship', 'race', 'sex',
'capital_gain', 'capital_loss', 'hours_per_week',
'native_country', 'income'
]
data = pd.read_csv(StringIO(response.text), header=None, names=column_names, na_values=' ?')
data = data.dropna()
X = data.drop('income', axis=1)
y = data['income'].apply(lambda x: 1 if x.strip() == '>50K' else 0)
# Encode categorical variables
X = pd.get_dummies(X, drop_first=True)
model_type = 'classification'
- Don't forget to add
'adult' to the available_datasets list.
Notes
This framework provides a flexible starting point for building predictive models with various datasets. Feel free to customize and extend it based on your specific requirements!