Data2Model / model_pipeline.py
Nausad's picture
Upload 25 files
facf506 verified
Raw History Blame Contribute Delete
88.1 kB
""" Data2Model - Automated Machine Learning Pipeline Fully updated with all fixes: 1. Imputation instead of deletion for null values 2. Per-column null strategy support 3. Optional target column for unsupervised 4. Flexible train-test and train-test-validation splits 5. Dynamic encoding (only when categorical columns exist) 6. Per-column scaling 7. Per-column encoding 8. Proper data type detection (numeric vs categorical) 9. Dashboard with visualizations 10. Target column excluded from preprocessing 11. Download preprocessing components """ import numpy as np import pandas as pd import pickle import os import json import base64 from io import BytesIO from datetime import datetime import matplotlib matplotlib.use('Agg') # Non-interactive backend import matplotlib.pyplot as plt import seaborn as sns from sklearn.model_selection import train_test_split from sklearn.preprocessing import ( StandardScaler, MinMaxScaler, RobustScaler, Normalizer, LabelEncoder, OneHotEncoder, OrdinalEncoder, LabelBinarizer ) from sklearn.impute import SimpleImputer from sklearn.metrics import ( accuracy_score, precision_score, recall_score, f1_score, mean_squared_error, r2_score, mean_absolute_error, classification_report, confusion_matrix ) import warnings warnings.filterwarnings('ignore') import sys, io if sys.stdout.encoding != 'utf-8': sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8', errors='replace') if sys.stderr.encoding != 'utf-8': sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding='utf-8', errors='replace') # Supervised - Classification from sklearn.linear_model import LogisticRegression from sklearn.tree import DecisionTreeClassifier from sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier, AdaBoostClassifier from sklearn.svm import SVC from sklearn.neighbors import KNeighborsClassifier from sklearn.naive_bayes import GaussianNB # Supervised - Regression from sklearn.linear_model import LinearRegression from sklearn.tree import DecisionTreeRegressor from sklearn.ensemble import RandomForestRegressor, GradientBoostingRegressor, AdaBoostRegressor from sklearn.svm import SVR from sklearn.neighbors import KNeighborsRegressor # Unsupervised from sklearn.cluster import KMeans, DBSCAN, AgglomerativeClustering from sklearn.decomposition import PCA # Advanced Models try: import xgboost as xgb XGBOOST_AVAILABLE = True except ImportError: XGBOOST_AVAILABLE = False try: import lightgbm as lgb LIGHTGBM_AVAILABLE = True except ImportError: LIGHTGBM_AVAILABLE = False # ───────────────────────────────────────────────────────────────────────────── # FIX 8: Strict data-type detector # ───────────────────────────────────────────────────────────────────────────── def detect_column_types(data, categorical_overrides=None): """ Detect numeric vs categorical columns relying purely on dataframe dtypes, not heuristics like low cardinality or unique value count, unless explicitly overridden. """ if categorical_overrides is None: categorical_overrides = [] numeric_cols = [] categorical_cols = [] for col in data.columns: if col in categorical_overrides: categorical_cols.append(col) continue dtype_str = str(data[col].dtype).lower() # Check for numeric types (int, float, double, etc.) if 'int' in dtype_str or 'float' in dtype_str or 'double' in dtype_str or 'number' in dtype_str: numeric_cols.append(col) # Check for object, category, boolean, string elif 'object' in dtype_str or 'category' in dtype_str or 'bool' in dtype_str or 'str' in dtype_str: categorical_cols.append(col) else: # default fallback categorical_cols.append(col) return numeric_cols, categorical_cols class AutoMLPipeline: """ Automated Machine Learning Pipeline All 8 system limitations addressed. """ def __init__(self): self.model = None self.scalers = {} # per-column scalers self.encoders = {} # per-column encoders self.imputers = {} # per-column imputers self.feature_names = None self.target_name = None self.problem_type = None self.model_name = None self.preprocessing_steps = [] self.results = {} self.numeric_cols = [] self.categorical_cols = [] # ───────────────────────────────────────────────────────────────────────── # Data Loading # ───────────────────────────────────────────────────────────────────────── def load_data(self, file_path, file_type='csv'): try: if file_type.lower() == 'csv': data = pd.read_csv(file_path) elif file_type.lower() in ['xlsx', 'excel', 'xls']: data = pd.read_excel(file_path) elif file_type.lower() == 'json': data = pd.read_json(file_path) else: raise ValueError(f"Unsupported file type: {file_type}") # Strip leading/trailing whitespaces from string columns for col in data.columns: if str(data[col].dtype) in ('object', 'string'): data[col] = data[col].apply(lambda x: str(x).strip() if pd.notnull(x) else x) # Standardize and replace common string null placeholders with actual np.nan placeholders = ['null', 'NULL', 'Null', 'n/a', 'N/A', 'na', 'NA', 'nan', 'NaN', 'NAN', '-', '?', ''] data = data.replace(placeholders, np.nan) print(f"βœ“ Dataset loaded: {data.shape[0]} rows Γ— {data.shape[1]} columns") return data except Exception as e: raise Exception(f"Error loading data: {str(e)}") # ───────────────────────────────────────────────────────────────────────── # Data Analysis # ───────────────────────────────────────────────────────────────────────── def analyze_data(self, data, categorical_overrides=None, target_column=None): """Analyze dataset and return summary including smart type detection.""" # Ensure numeric-looking columns accidentally read as strings are safely converted before detection data = data.copy() for col in data.columns: if col == target_column: continue if str(data[col].dtype) in ('object', 'string'): # Try to convert to numeric converted = pd.to_numeric(data[col], errors='coerce') non_null_original = data[col].dropna().shape[0] non_null_converted = converted.dropna().shape[0] if non_null_original > 0 and non_null_converted >= 0.9 * non_null_original: data[col] = converted numeric_cols, categorical_cols = detect_column_types(data, categorical_overrides) # FIX 3: Exclude target column from preprocessing lists if target_column and target_column in numeric_cols: numeric_cols.remove(target_column) if target_column and target_column in categorical_cols: categorical_cols.remove(target_column) # Column-level stats col_stats = {} for col in data.columns: col_stats[col] = { 'dtype': str(data[col].dtype), 'missing': int(data[col].isnull().sum()), 'unique': int(data[col].nunique()), 'detected_type': 'categorical' if col in categorical_cols else 'numeric' } # Visualization data viz_data = self._generate_visualization_data(data, numeric_cols, categorical_cols) return { 'shape': data.shape, 'columns': list(data.columns), 'dtypes': {c: str(t) for c, t in data.dtypes.items()}, 'missing_values': data.isnull().sum().to_dict(), 'numeric_columns': numeric_cols, 'categorical_columns': categorical_cols, 'statistics': data.describe().to_dict(), 'duplicates': int(data.duplicated().sum()), 'col_stats': col_stats, 'viz_data': viz_data } def _generate_visualization_data(self, data, numeric_cols, categorical_cols): """Generate data for charts""" viz = {} # Missing values chart missing = data.isnull().sum() missing = missing[missing > 0].sort_values(ascending=False) viz['missing_labels'] = missing.index.tolist() viz['missing_values'] = missing.values.tolist() # Data types distribution type_counts = {'Numeric': len(numeric_cols), 'Categorical': len(categorical_cols)} viz['type_labels'] = list(type_counts.keys()) viz['type_counts'] = list(type_counts.values()) # Numeric distributions (first 6 only) viz['numeric_distributions'] = [] for col in numeric_cols[:6]: try: hist, bins = np.histogram(data[col].dropna(), bins=20) viz['numeric_distributions'].append({ 'column': col, 'bins': bins[:-1].tolist(), 'counts': hist.tolist() }) except: pass # Categorical value counts (top 5 columns, top 10 values each) viz['categorical_distributions'] = [] for col in categorical_cols[:5]: try: vc = data[col].value_counts().head(10) viz['categorical_distributions'].append({ 'column': col, 'labels': vc.index.astype(str).tolist(), 'counts': vc.values.tolist() }) except: pass # Correlation matrix (numeric only, max 10 cols) if len(numeric_cols) > 1: corr_cols = numeric_cols[:10] try: corr = data[corr_cols].corr() viz['correlation'] = { 'columns': corr_cols, 'matrix': corr.values.tolist() } except: viz['correlation'] = None else: viz['correlation'] = None return viz # ───────────────────────────────────────────────────────────────────────── # ENHANCEMENT 1: Dashboard Visualizations # ───────────────────────────────────────────────────────────────────────── def generate_visualizations(self, data, numeric_cols, categorical_cols, max_plots=6): """ Generate dashboard visualizations and return as base64 encoded images. Returns dict with encoded plot images. """ plots = {} # Set style sns.set_style("whitegrid") plt.rcParams['figure.facecolor'] = 'white' # 1. Missing Values Heatmap if data.isnull().sum().sum() > 0: fig, ax = plt.subplots(figsize=(10, 6)) missing_data = data.isnull().sum() missing_data = missing_data[missing_data > 0].sort_values(ascending=False) if len(missing_data) > 0: ax.barh(range(len(missing_data)), missing_data.values, color='#e74c3c') ax.set_yticks(range(len(missing_data))) ax.set_yticklabels(missing_data.index) ax.set_xlabel('Missing Values Count', fontsize=12) ax.set_title('Missing Values by Column', fontsize=14, fontweight='bold') ax.grid(axis='x', alpha=0.3) for i, v in enumerate(missing_data.values): ax.text(v + 0.5, i, str(int(v)), va='center', fontsize=10) plt.tight_layout() plots['missing_values'] = self._fig_to_base64(fig) plt.close(fig) # 2. Numeric Features - Histograms (first 6) if numeric_cols: num_to_plot = min(len(numeric_cols), max_plots) fig, axes = plt.subplots(2, 3, figsize=(15, 8)) axes = axes.flatten() for idx, col in enumerate(numeric_cols[:num_to_plot]): data[col].dropna().hist(bins=30, ax=axes[idx], color='#3498db', edgecolor='black') axes[idx].set_title(f'{col}', fontsize=11, fontweight='bold') axes[idx].set_xlabel('Value', fontsize=9) axes[idx].set_ylabel('Frequency', fontsize=9) axes[idx].grid(axis='y', alpha=0.3) # Hide unused subplots for idx in range(num_to_plot, 6): axes[idx].axis('off') plt.suptitle('Numeric Features Distribution', fontsize=14, fontweight='bold', y=1.00) plt.tight_layout() plots['numeric_histograms'] = self._fig_to_base64(fig) plt.close(fig) # 3. Numeric Features - Box Plots (first 6) if numeric_cols: num_to_plot = min(len(numeric_cols), max_plots) fig, axes = plt.subplots(2, 3, figsize=(15, 8)) axes = axes.flatten() for idx, col in enumerate(numeric_cols[:num_to_plot]): axes[idx].boxplot(data[col].dropna(), vert=True, patch_artist=True, boxprops=dict(facecolor='#2ecc71', alpha=0.7), medianprops=dict(color='red', linewidth=2)) axes[idx].set_title(f'{col}', fontsize=11, fontweight='bold') axes[idx].set_ylabel('Value', fontsize=9) axes[idx].grid(axis='y', alpha=0.3) for idx in range(num_to_plot, 6): axes[idx].axis('off') plt.suptitle('Numeric Features - Outlier Detection', fontsize=14, fontweight='bold', y=1.00) plt.tight_layout() plots['numeric_boxplots'] = self._fig_to_base64(fig) plt.close(fig) # 4. Correlation Heatmap (if more than 2 numeric columns) if len(numeric_cols) >= 2: fig, ax = plt.subplots(figsize=(10, 8)) numeric_data = data[numeric_cols].dropna() if len(numeric_data) > 0: corr = numeric_data.corr() mask = np.triu(np.ones_like(corr, dtype=bool)) sns.heatmap(corr, mask=mask, annot=True, fmt='.2f', cmap='coolwarm', center=0, square=True, linewidths=1, cbar_kws={"shrink": 0.8}, ax=ax, vmin=-1, vmax=1) ax.set_title('Correlation Matrix - Numeric Features', fontsize=14, fontweight='bold') plt.tight_layout() plots['correlation_heatmap'] = self._fig_to_base64(fig) plt.close(fig) # 5. Categorical Features - Bar Charts (first 6, top 10 values each) if categorical_cols: cat_to_plot = min(len(categorical_cols), max_plots) fig, axes = plt.subplots(2, 3, figsize=(15, 8)) axes = axes.flatten() for idx, col in enumerate(categorical_cols[:cat_to_plot]): value_counts = data[col].value_counts().head(10) axes[idx].barh(range(len(value_counts)), value_counts.values, color='#9b59b6') axes[idx].set_yticks(range(len(value_counts))) axes[idx].set_yticklabels(value_counts.index, fontsize=9) axes[idx].set_xlabel('Count', fontsize=9) axes[idx].set_title(f'{col} (Top 10)', fontsize=11, fontweight='bold') axes[idx].grid(axis='x', alpha=0.3) for i, v in enumerate(value_counts.values): axes[idx].text(v + 0.5, i, str(int(v)), va='center', fontsize=8) for idx in range(cat_to_plot, 6): axes[idx].axis('off') plt.suptitle('Categorical Features Distribution', fontsize=14, fontweight='bold', y=1.00) plt.tight_layout() plots['categorical_distributions'] = self._fig_to_base64(fig) plt.close(fig) # 6. Data Quality Overview fig, axes = plt.subplots(1, 2, figsize=(12, 5)) # Column types pie chart type_counts = pd.Series({ 'Numeric': len(numeric_cols), 'Categorical': len(categorical_cols) }) axes[0].pie(type_counts.values, labels=type_counts.index, autopct='%1.1f%%', colors=['#3498db', '#e67e22'], startangle=90) axes[0].set_title('Column Types', fontsize=12, fontweight='bold') # Missing vs Complete data total_cells = data.shape[0] * data.shape[1] missing_cells = data.isnull().sum().sum() complete_cells = total_cells - missing_cells completeness = pd.Series({ 'Complete': complete_cells, 'Missing': missing_cells }) axes[1].pie(completeness.values, labels=completeness.index, autopct='%1.1f%%', colors=['#2ecc71', '#e74c3c'], startangle=90) axes[1].set_title('Data Completeness', fontsize=12, fontweight='bold') plt.suptitle('Dataset Quality Overview', fontsize=14, fontweight='bold', y=1.02) plt.tight_layout() plots['data_quality'] = self._fig_to_base64(fig) plt.close(fig) return plots def _fig_to_base64(self, fig): """Convert matplotlib figure to base64 encoded string for HTML embedding.""" buffer = BytesIO() fig.savefig(buffer, format='png', dpi=100, bbox_inches='tight') buffer.seek(0) image_base64 = base64.b64encode(buffer.read()).decode('utf-8') buffer.close() return f"data:image/png;base64,{image_base64}" # ───────────────────────────────────────────────────────────────────────── # FIX 1 & 2: Null value imputation per column (no auto-deletion) # ───────────────────────────────────────────────────────────────────────── # ───────────────────────────────────────────────────────────────────────── # FIX 1 & 2: Null value imputation per column (no auto-deletion) # ───────────────────────────────────────────────────────────────────────── def handle_missing_values(self, data, null_strategies=None, target_column=None): """ Handle missing values using imputation. null_strategies: dict {col_name: 'mean'|'median'|'mode'|'drop'|'zero'|'custom_[val]'} or None (auto: median for numeric, mode for categorical) """ if null_strategies is None: null_strategies = {} # If it's a supervised problem and the target has missing values, drop those rows immediately to avoid training issues if target_column and target_column in data.columns: if data[target_column].isnull().any(): before = len(data) data = data.dropna(subset=[target_column]) print(f" Dropped {before - len(data)} rows with missing target '{target_column}'") self.preprocessing_steps.append(f"Null handling '{target_column}' (Target): drop rows") # Set up a list to track zero-filled or custom-filled constant columns for predict if not hasattr(self, 'custom_impute_values'): self.custom_impute_values = {} # Impute all columns (excluding target if present) so that if they have missing values in predict, we can impute them cols_to_impute = [col for col in data.columns if col != target_column] for col in cols_to_impute: strategy = null_strategies.get(col, 'auto') # If strategy is auto: if strategy == 'auto': # Determine fallback based on datatype if data[col].dtype in ['object', 'category', 'bool']: strategy = 'most_frequent' else: strategy = 'median' if strategy == 'drop': if data[col].isnull().any(): before = len(data) data = data.dropna(subset=[col]) print(f" Dropped {before - len(data)} rows with missing '{col}'") self.preprocessing_steps.append(f"Null handling '{col}': drop rows") # Store drop strategy in imputers so predict can handle it self.imputers[col] = 'drop' continue if strategy == 'mode': strategy = 'most_frequent' # Custom constant value replacement: if strategy == 'zero': val = 0 if data[col].dtype not in ['object', 'category', 'bool'] else '0' self.custom_impute_values[col] = val data[col] = data[col].fillna(val) self.preprocessing_steps.append(f"Null handling '{col}': fill with custom constant (0)") # Fit a constant imputer to be Scikit-learn native imputer = SimpleImputer(strategy='constant', fill_value=val) imputer.fit(data[[col]]) self.imputers[col] = imputer continue elif strategy.startswith('custom_'): val = strategy[7:] # extract the value after "custom_" # Try to convert to float/int if numeric if data[col].dtype not in ['object', 'category', 'bool']: try: if '.' in val: val = float(val) else: val = int(val) except ValueError: pass self.custom_impute_values[col] = val data[col] = data[col].fillna(val) self.preprocessing_steps.append(f"Null handling '{col}': fill with custom constant ({val})") imputer = SimpleImputer(strategy='constant', fill_value=val) imputer.fit(data[[col]]) self.imputers[col] = imputer continue if strategy == 'mean': if data[col].dtype in ['object', 'category', 'bool']: strategy = 'most_frequent' # fallback for categorical # Fit standard SimpleImputer (mean, median, most_frequent) try: imputer = SimpleImputer(strategy=strategy) # Fit on data data[[col]] = imputer.fit_transform(data[[col]]) self.imputers[col] = imputer self.preprocessing_steps.append(f"Null handling '{col}': {strategy}") except Exception as e: print(f" βœ— Could not impute '{col}' using {strategy}: {e}") return data # ───────────────────────────────────────────────────────────────────────── # FIX 6 & 7: Per-column scaling and encoding # ───────────────────────────────────────────────────────────────────────── def _get_scaler(self, method): if method == 'standard': return StandardScaler() elif method == 'minmax': return MinMaxScaler() elif method == 'robust': return RobustScaler() elif method == 'normalizer': return Normalizer() return None def scale_features(self, X_train, X_test, X_val=None, scaling_config=None, numeric_cols=None): """ Per-column scaling. scaling_config: dict {col: method} e.g. {'age': 'standard', 'income': 'minmax'} or single string 'standard' applied to all numeric cols. """ if numeric_cols is None: numeric_cols = list(X_train.select_dtypes(include=['int64', 'float64']).columns) if not numeric_cols: print(" No numeric columns to scale") return (X_train, X_test, X_val) if X_val is not None else (X_train, X_test) # Normalise config to dict if scaling_config is None or scaling_config == 'none' or scaling_config == 'auto': # FIX 2: auto defaults to standard default_method = 'standard' if scaling_config == 'auto' else 'none' if default_method == 'none': if X_val is not None: return X_train, X_test, X_val return X_train, X_test scaling_config = {col: default_method for col in numeric_cols} if isinstance(scaling_config, str): scaling_config = {col: scaling_config for col in numeric_cols} for col in numeric_cols: method = scaling_config.get(col, 'standard') # FIX 2: handle auto per-column if method == 'auto': method = 'standard' if method == 'none': continue scaler = self._get_scaler(method) if scaler is None: continue X_train[col] = scaler.fit_transform(X_train[[col]]) X_test[col] = scaler.transform(X_test[[col]]) if X_val is not None: X_val[col] = scaler.transform(X_val[[col]]) self.scalers[col] = scaler self.preprocessing_steps.append(f"Scale '{col}': {method}") print(f"βœ“ Scaling applied to {len(self.scalers)} columns") if X_val is not None: return X_train, X_test, X_val return X_train, X_test def encode_features(self, X_train, X_test, X_val=None, encoding_config=None, categorical_cols=None): """ Per-column categorical encoding. encoding_config: dict {col: method} e.g. {'color': 'onehot', 'grade': 'label'} or single string applied to all categorical cols. """ if categorical_cols is None: categorical_cols = list(X_train.select_dtypes(include=['object', 'category']).columns) if not categorical_cols: print(" No categorical columns to encode") if X_val is not None: return X_train, X_test, X_val return X_train, X_test # FIX 5: Only encode if categorical cols actually exist if isinstance(encoding_config, str): encoding_config = {col: encoding_config for col in categorical_cols} if encoding_config is None: encoding_config = {} onehot_cols = [] for col in categorical_cols: if col not in X_train.columns: continue method = encoding_config.get(col, 'auto') # Auto: one-hot for ≀10 unique, label for higher if method == 'auto': method = 'onehot' if X_train[col].nunique() <= 10 else 'label' if method == 'onehot': onehot_cols.append(col) elif method == 'label': le = LabelEncoder() X_train[col] = le.fit_transform(X_train[col].astype(str)) X_test[col] = le.transform(X_test[col].astype(str)) if X_val is not None: X_val[col] = le.transform(X_val[col].astype(str)) self.encoders[col] = le self.preprocessing_steps.append(f"Encode '{col}': Label") elif method == 'ordinal': oe = OrdinalEncoder(handle_unknown='use_encoded_value', unknown_value=-1) X_train[col] = oe.fit_transform(X_train[[col]]) X_test[col] = oe.transform(X_test[[col]]) if X_val is not None: X_val[col] = oe.transform(X_val[[col]]) self.encoders[col] = oe self.preprocessing_steps.append(f"Encode '{col}': Ordinal") elif method == 'binary': lb = LabelBinarizer() encoded_train = lb.fit_transform(X_train[col].astype(str)) if encoded_train.shape[1] == 1: X_train[col] = encoded_train.ravel() X_test[col] = lb.transform(X_test[col].astype(str)).ravel() if X_val is not None: X_val[col] = lb.transform(X_val[col].astype(str)).ravel() else: new_cols = [f"{col}_{c}" for c in lb.classes_] X_train[new_cols] = encoded_train X_test[new_cols] = lb.transform(X_test[col].astype(str)) if X_val is not None: X_val[new_cols] = lb.transform(X_val[col].astype(str)) X_train.drop(columns=[col], inplace=True) X_test.drop(columns=[col], inplace=True) if X_val is not None: X_val.drop(columns=[col], inplace=True) self.encoders[col] = lb self.preprocessing_steps.append(f"Encode '{col}': Binary") elif method == 'target': le = LabelEncoder() X_train[col] = le.fit_transform(X_train[col].astype(str)) X_test[col] = le.transform(X_test[col].astype(str)) if X_val is not None: X_val[col] = le.transform(X_val[col].astype(str)) self.encoders[col] = le self.preprocessing_steps.append(f"Encode '{col}': Target (Label)") # Batch one-hot encoding self.onehot_cols = onehot_cols if onehot_cols: X_train = pd.get_dummies(X_train, columns=onehot_cols, drop_first=True) X_test = pd.get_dummies(X_test, columns=onehot_cols, drop_first=True) if X_val is not None: X_val = pd.get_dummies(X_val, columns=onehot_cols, drop_first=True) # Align columns X_test = X_test.reindex(columns=X_train.columns, fill_value=0) if X_val is not None: X_val = X_val.reindex(columns=X_train.columns, fill_value=0) for col in onehot_cols: self.preprocessing_steps.append(f"Encode '{col}': One-Hot") print(f"βœ“ Encoding applied to {len(categorical_cols)} categorical columns") if X_val is not None: return X_train, X_test, X_val return X_train, X_test # ───────────────────────────────────────────────────────────────────────── # Model Definitions # ───────────────────────────────────────────────────────────────────────── def _classification_models(self): models = { 'Logistic Regression': LogisticRegression(max_iter=1000, random_state=42), 'Random Forest': RandomForestClassifier(n_estimators=100, random_state=42), 'Gradient Boosting': GradientBoostingClassifier(n_estimators=100, random_state=42), 'Decision Tree': DecisionTreeClassifier(random_state=42), 'KNN': KNeighborsClassifier(), 'Naive Bayes': GaussianNB(), 'SVM': SVC(random_state=42), 'AdaBoost': AdaBoostClassifier(random_state=42), } if XGBOOST_AVAILABLE: models['XGBoost'] = xgb.XGBClassifier(n_estimators=100, random_state=42, use_label_encoder=False, verbosity=0, eval_metric='logloss') if LIGHTGBM_AVAILABLE: models['LightGBM'] = lgb.LGBMClassifier(n_estimators=100, random_state=42, verbosity=-1) return models def _regression_models(self): models = { 'Linear Regression': LinearRegression(), 'Random Forest': RandomForestRegressor(n_estimators=100, random_state=42), 'Gradient Boosting': GradientBoostingRegressor(n_estimators=100, random_state=42), 'Decision Tree': DecisionTreeRegressor(random_state=42), 'KNN': KNeighborsRegressor(), 'SVR': SVR(), 'AdaBoost': AdaBoostRegressor(random_state=42), } if XGBOOST_AVAILABLE: models['XGBoost'] = xgb.XGBRegressor(n_estimators=100, random_state=42, verbosity=0) if LIGHTGBM_AVAILABLE: models['LightGBM'] = lgb.LGBMRegressor(n_estimators=100, random_state=42, verbosity=-1) return models # ───────────────────────────────────────────────────────────────────────── # Train Models # ───────────────────────────────────────────────────────────────────────── def train_model(self, X_train, y_train, X_test, y_test, problem_type='auto'): if problem_type == 'auto': problem_type = 'classification' if ( y_train.dtype == 'object' or y_train.nunique() < 20 ) else 'regression' self.problem_type = problem_type models = (self._classification_models() if problem_type == 'classification' else self._regression_models()) print(f"\n{'='*55}") print(f"πŸ€– Training {problem_type.upper()} models...") print(f"{'='*55}\n") best_model = None best_score = -np.inf if problem_type == 'classification' else np.inf best_name = None rows = [] for name, model in models.items(): try: print(f" Training {name}...", end=" ") model.fit(X_train, y_train) y_pred = model.predict(X_test) if problem_type == 'classification': score = accuracy_score(y_test, y_pred) rows.append({'Model': name, 'Accuracy': round(score, 4), 'Precision': round(precision_score(y_test, y_pred, average='weighted', zero_division=0), 4), 'Recall': round(recall_score(y_test, y_pred, average='weighted', zero_division=0), 4), 'F1': round(f1_score(y_test, y_pred, average='weighted', zero_division=0), 4)}) print(f"Accuracy: {score:.4f}") if score > best_score: best_score, best_model, best_name = score, model, name else: rmse = np.sqrt(mean_squared_error(y_test, y_pred)) r2 = r2_score(y_test, y_pred) rows.append({'Model': name, 'RMSE': round(rmse, 4), 'MAE': round(mean_absolute_error(y_test, y_pred), 4), 'R2': round(r2, 4)}) print(f"RMSE: {rmse:.4f} RΒ²: {r2:.4f}") if rmse < best_score: best_score, best_model, best_name = rmse, model, name except Exception as e: print(f"βœ— {e}") self.model = best_model self.model_name = best_name self.comparison_table = pd.DataFrame(rows) print(f"\nπŸ† Best: {best_name}") # Final evaluation metrics y_pred = best_model.predict(X_test) if problem_type == 'classification': self.results = { 'model_name': best_name, 'problem_type': problem_type, 'accuracy': accuracy_score(y_test, y_pred), 'precision': precision_score(y_test, y_pred, average='weighted', zero_division=0), 'recall': recall_score(y_test, y_pred, average='weighted', zero_division=0), 'f1_score': f1_score(y_test, y_pred, average='weighted', zero_division=0), 'preprocessing_steps': self.preprocessing_steps, } else: mse = mean_squared_error(y_test, y_pred) self.results = { 'model_name': best_name, 'problem_type': problem_type, 'mse': mse, 'rmse': np.sqrt(mse), 'mae': mean_absolute_error(y_test, y_pred), 'r2_score': r2_score(y_test, y_pred), 'preprocessing_steps': self.preprocessing_steps, } def train_unsupervised(self, X, problem_type='clustering'): """Train unsupervised model (no target needed).""" print(f"\n{'='*55}") print(f"πŸ€– Training UNSUPERVISED model: {problem_type}") print(f"{'='*55}\n") self.problem_type = problem_type if problem_type == 'clustering': model = KMeans(n_clusters=3, random_state=42) model.fit(X) labels = model.labels_ self.model = model self.model_name = 'K-Means (k=3)' self.results = { 'model_name': 'K-Means (k=3)', 'problem_type': 'clustering', 'inertia': float(model.inertia_), 'n_clusters': 3, 'preprocessing_steps': self.preprocessing_steps, } print(f"βœ“ KMeans trained. Inertia: {model.inertia_:.2f}") elif problem_type == 'dimensionality_reduction': model = PCA(n_components=2) model.fit(X) self.model = model self.model_name = 'PCA (2 components)' self.results = { 'model_name': 'PCA (2 components)', 'problem_type': 'dimensionality_reduction', 'explained_variance': float(model.explained_variance_ratio_.sum()), 'preprocessing_steps': self.preprocessing_steps, } print(f"βœ“ PCA trained. Explained variance: {model.explained_variance_ratio_.sum():.2%}") else: print(f"β„Ή Association rule learning – pass through") self.model = None self.model_name = 'Association Analysis' self.results = { 'model_name': 'Association Analysis', 'problem_type': 'association', 'preprocessing_steps': self.preprocessing_steps, } # ───────────────────────────────────────────────────────────────────────── # Save / Load # ───────────────────────────────────────────────────────────────────────── def save_model(self, save_dir='saved_models', filename=None): os.makedirs(save_dir, exist_ok=True) if filename is None: ts = datetime.now().strftime('%Y%m%d_%H%M%S') filename = f"model_{self.problem_type}_{ts}.pkl" path = os.path.join(save_dir, filename) payload = { 'model': self.model, 'scalers': self.scalers, 'encoders': self.encoders, 'imputers': self.imputers, 'feature_names': self.feature_names, 'trained_features': getattr(self, 'trained_features', None), 'onehot_cols': getattr(self, 'onehot_cols', None), 'custom_impute_values': getattr(self, 'custom_impute_values', {}), 'drop_columns': getattr(self, 'drop_columns', []), 'model_name': self.model_name, 'problem_type': self.problem_type, 'preprocessing_steps': self.preprocessing_steps, 'results': self.results, } with open(path, 'wb') as f: pickle.dump(payload, f) print(f"βœ“ Model saved: {path}") return path def load_model(self, path): with open(path, 'rb') as f: d = pickle.load(f) self.model = d['model'] self.scalers = d.get('scalers', {}) self.encoders = d.get('encoders', {}) self.imputers = d.get('imputers', {}) self.feature_names = d.get('feature_names') self.trained_features = d.get('trained_features', None) self.onehot_cols = d.get('onehot_cols', None) self.custom_impute_values = d.get('custom_impute_values', {}) self.drop_columns = d.get('drop_columns', []) self.model_name = d.get('model_name') self.problem_type = d.get('problem_type') self.preprocessing_steps = d.get('preprocessing_steps', []) self.results = d.get('results', {}) return self def predict(self, X): if self.model is None: raise Exception("No model trained yet.") # Copy to avoid side effects X = X.copy() # Strip whitespaces from string columns for col in X.columns: if str(X[col].dtype) in ('object', 'string'): X[col] = X[col].apply(lambda x: str(x).strip() if pd.notnull(x) else x) # Standardize and replace common string null placeholders with actual np.nan placeholders = ['null', 'NULL', 'Null', 'n/a', 'N/A', 'na', 'NA', 'nan', 'NaN', 'NAN', '-', '?', ''] X = X.replace(placeholders, np.nan) # Drop columns that were excluded during training if hasattr(self, 'drop_columns') and self.drop_columns: cols_to_drop = [c for c in self.drop_columns if c in X.columns] if cols_to_drop: X = X.drop(columns=cols_to_drop) # Safely convert numeric-looking columns read as strings for col in X.columns: if str(X[col].dtype) in ('object', 'string'): converted = pd.to_numeric(X[col], errors='coerce') non_null_original = X[col].dropna().shape[0] non_null_converted = converted.dropna().shape[0] if non_null_original > 0 and non_null_converted >= 0.9 * non_null_original: X[col] = converted # 1. Apply Imputers / Null strategies for col in X.columns: # Handle drop strategy in predict (dropping rows with missing values for that col) if col in self.imputers: imputer = self.imputers[col] if imputer == 'drop': X = X.dropna(subset=[col]) elif hasattr(imputer, 'transform'): try: X[[col]] = imputer.transform(X[[col]]) except Exception as e: print(f" Warning: Imputer transform failed for '{col}': {e}") # Fallback custom imputations registered if hasattr(self, 'custom_impute_values') and self.custom_impute_values and col in self.custom_impute_values: val = self.custom_impute_values[col] X[col] = X[col].fillna(val) # 2. Apply Encoders for col, encoder in self.encoders.items(): if col in X.columns: try: if isinstance(encoder, LabelEncoder): # Handle unseen categories gracefully classes = set(encoder.classes_) X[col] = X[col].astype(str).map(lambda s: s if s in classes else encoder.classes_[0]) X[col] = encoder.transform(X[col]) elif isinstance(encoder, OrdinalEncoder): X[[col]] = encoder.transform(X[[col]]) elif isinstance(encoder, LabelBinarizer): encoded = encoder.transform(X[col].astype(str)) if encoded.shape[1] == 1: X[col] = encoded.ravel() else: new_cols = [f"{col}_{c}" for c in encoder.classes_] X[new_cols] = encoded X.drop(columns=[col], inplace=True) except Exception as e: print(f" Warning: Encoding failed for '{col}': {e}") # 3. Apply One-Hot dummy encoding if hasattr(self, 'onehot_cols') and self.onehot_cols: existing_onehot_cols = [col for col in self.onehot_cols if col in X.columns] if existing_onehot_cols: X = pd.get_dummies(X, columns=existing_onehot_cols, drop_first=True) # 4. Apply Scalers for col, scaler in self.scalers.items(): if col in X.columns: try: X[[col]] = scaler.transform(X[[col]]) except Exception as e: print(f" Warning: Scaler transform failed for '{col}': {e}") # 5. Column Alignment with Model Structure if hasattr(self, 'trained_features') and self.trained_features: # Reindex to match trained features exactly (fills missing dummy columns with 0, discards extra ones) X = X.reindex(columns=self.trained_features, fill_value=0) return self.model.predict(X) # ───────────────────────────────────────────────────────────────────────── # ENHANCEMENT 3: Save Preprocessing Components Separately # ───────────────────────────────────────────────────────────────────────── def save_encoders(self, save_dir='saved_models', filename=None): """Save encoders as a separate file.""" os.makedirs(save_dir, exist_ok=True) if filename is None: ts = datetime.now().strftime('%Y%m%d_%H%M%S') filename = f"encoders_{self.problem_type}_{ts}.pkl" path = os.path.join(save_dir, filename) payload = { 'encoders': self.encoders, 'categorical_columns': [col for col in self.feature_names if col in self.encoders] if self.feature_names else [], 'timestamp': datetime.now().isoformat(), 'problem_type': self.problem_type, } with open(path, 'wb') as f: pickle.dump(payload, f) print(f"βœ“ Encoders saved: {path}") return path def save_scalers(self, save_dir='saved_models', filename=None): """Save scalers as a separate file.""" os.makedirs(save_dir, exist_ok=True) if filename is None: ts = datetime.now().strftime('%Y%m%d_%H%M%S') filename = f"scalers_{self.problem_type}_{ts}.pkl" path = os.path.join(save_dir, filename) payload = { 'scalers': self.scalers, 'numeric_columns': [col for col in self.feature_names if col in self.scalers] if self.feature_names else [], 'timestamp': datetime.now().isoformat(), 'problem_type': self.problem_type, } with open(path, 'wb') as f: pickle.dump(payload, f) print(f"βœ“ Scalers saved: {path}") return path def save_preprocessing_bundle(self, save_dir='saved_models', filename=None): """Save all preprocessing components as a bundle with metadata.""" os.makedirs(save_dir, exist_ok=True) if filename is None: ts = datetime.now().strftime('%Y%m%d_%H%M%S') filename = f"preprocessing_bundle_{self.problem_type}_{ts}.pkl" path = os.path.join(save_dir, filename) payload = { 'scalers': self.scalers, 'encoders': self.encoders, 'imputers': self.imputers, 'metadata': { 'feature_names': self.feature_names, 'trained_features': getattr(self, 'trained_features', None), 'onehot_cols': getattr(self, 'onehot_cols', None), 'custom_impute_values': getattr(self, 'custom_impute_values', {}), 'drop_columns': getattr(self, 'drop_columns', []), 'numeric_columns': [col for col in self.feature_names if col in self.scalers] if self.feature_names else [], 'categorical_columns': [col for col in self.feature_names if col in self.encoders] if self.feature_names else [], 'preprocessing_steps': self.preprocessing_steps, 'problem_type': self.problem_type, 'model_name': self.model_name, 'timestamp': datetime.now().isoformat(), } } with open(path, 'wb') as f: pickle.dump(payload, f) print(f"βœ“ Preprocessing bundle saved: {path}") return path # ───────────────────────────────────────────────────────────────────────── # ENHANCEMENT: Generate Deployable Web Application # ───────────────────────────────────────────────────────────────────────── def generate_deployable_app(self, model_path, scaler_path=None, encoder_path=None, save_dir='saved_models'): """ Generate a complete, self-contained Flask web application as a ZIP file. The ZIP contains app.py, templates/index.html, model artifacts, requirements.txt, and README.md. """ import zipfile os.makedirs(save_dir, exist_ok=True) ts = datetime.now().strftime('%Y%m%d_%H%M%S') zip_filename = f"deployable_app_{ts}.zip" zip_path = os.path.join(save_dir, zip_filename) feature_names = self.feature_names or [] numeric_cols = self.numeric_cols or [] categorical_cols = self.categorical_cols or [] categorical_values = getattr(self, 'categorical_values', {}) target_name = self.target_name or 'target' model_name = self.model_name or 'Unknown' problem_type = self.problem_type or 'Unknown' # ── Generate app.py ────────────────────────────────────────────── app_py = self._gen_app_py(feature_names, numeric_cols, categorical_cols, target_name, model_name, problem_type) # ── Generate index.html ────────────────────────────────────────── index_html = self._gen_index_html(feature_names, numeric_cols, categorical_cols, categorical_values, target_name, model_name, problem_type) # ── Generate requirements.txt ──────────────────────────────────── requirements_txt = "flask>=2.3.0\npandas>=1.5.0\nnumpy>=1.23.0\nscikit-learn>=1.2.0\n" # ── Generate README.md ─────────────────────────────────────────── readme_md = f"""# {model_name} β€” Prediction Web App This is an auto-generated, self-contained Flask web application for making predictions using the **{model_name}** model trained by Data2Model. ## Quick Start ```bash pip install -r requirements.txt python app.py ``` Then open **http://localhost:5000** in your browser. ## Model Details | Property | Value | |----------------|----------------------| | Algorithm | {model_name} | | Problem Type | {problem_type.title()} | | Target Column | {target_name} | | Features Used | {len(feature_names)} | ## Project Structure ``` β”œβ”€β”€ app.py # Flask application β”œβ”€β”€ templates/ β”‚ └── index.html # Web interface β”œβ”€β”€ model/ β”‚ β”œβ”€β”€ model.pkl # Trained model β”‚ β”œβ”€β”€ scaler.pkl # Fitted scaler (if applicable) β”‚ └── encoder.pkl # Fitted encoder (if applicable) β”œβ”€β”€ requirements.txt # Python dependencies └── README.md # This file ``` --- *Generated by Data2Model β€” Automated Machine Learning Platform* """ # ── Bundle into ZIP ────────────────────────────────────────────── with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zf: zf.writestr('app.py', app_py) zf.writestr('templates/index.html', index_html) zf.writestr('requirements.txt', requirements_txt) zf.writestr('README.md', readme_md) # Add model pickle if model_path and os.path.exists(model_path): zf.write(model_path, 'model/model.pkl') # Add scaler pickle if scaler_path and os.path.exists(scaler_path): zf.write(scaler_path, 'model/scaler.pkl') # Add encoder pickle if encoder_path and os.path.exists(encoder_path): zf.write(encoder_path, 'model/encoder.pkl') print(f"βœ“ Deployable app saved: {zip_path}") return zip_path def _gen_app_py(self, feature_names, numeric_cols, categorical_cols, target_name, model_name, problem_type): """Generate the app.py source code string.""" return '''""" Auto-generated Prediction Web App β€” ''' + model_name + ''' Generated by Data2Model """ from flask import Flask, render_template, request, jsonify import pandas as pd import numpy as np import pickle import os app = Flask(__name__) # ── Load model & artifacts ───────────────────────────────────────────────── MODEL_DIR = os.path.join(os.path.dirname(__file__), 'model') MODEL_PATH = os.path.join(MODEL_DIR, 'model.pkl') SCALER_PATH = os.path.join(MODEL_DIR, 'scaler.pkl') ENCODER_PATH = os.path.join(MODEL_DIR, 'encoder.pkl') with open(MODEL_PATH, 'rb') as f: bundle = pickle.load(f) model = bundle['model'] imputers = bundle.get('imputers', {}) feature_names = bundle.get('feature_names', []) trained_features = bundle.get('trained_features', []) onehot_cols = bundle.get('onehot_cols', []) custom_impute = bundle.get('custom_impute_values', {}) drop_columns = bundle.get('drop_columns', []) model_name = bundle.get('model_name', 'Unknown') problem_type = bundle.get('problem_type', 'Unknown') # Explicitly load separate scaler and encoder files if they exist scalers = {} if os.path.exists(SCALER_PATH): with open(SCALER_PATH, 'rb') as f: scaler_payload = pickle.load(f) scalers = scaler_payload.get('scalers', {}) encoders = {} if os.path.exists(ENCODER_PATH): with open(ENCODER_PATH, 'rb') as f: encoder_payload = pickle.load(f) encoders = encoder_payload.get('encoders', {}) from sklearn.preprocessing import LabelEncoder, OrdinalEncoder, LabelBinarizer @app.route('/') def index(): return render_template('index.html') @app.route('/predict', methods=['POST']) def predict(): try: data = {} for feat in feature_names: val = request.form.get(feat, '') if val.strip() == '': data[feat] = np.nan else: try: data[feat] = float(val) except ValueError: data[feat] = val df = pd.DataFrame([data]) # Drop excluded columns if drop_columns: cols_to_drop = [c for c in drop_columns if c in df.columns] if cols_to_drop: df = df.drop(columns=cols_to_drop) # 1. Imputation for col in df.columns: if col in imputers: imp = imputers[col] if imp == 'drop': pass elif hasattr(imp, 'transform'): try: df[[col]] = imp.transform(df[[col]]) except: pass if col in custom_impute: df[col] = df[col].fillna(custom_impute[col]) # 2. Encoding for col, encoder in encoders.items(): if col in df.columns: try: if isinstance(encoder, LabelEncoder): classes = set(encoder.classes_) df[col] = df[col].astype(str).map(lambda s: s if s in classes else encoder.classes_[0]) df[col] = encoder.transform(df[col]) elif isinstance(encoder, OrdinalEncoder): df[[col]] = encoder.transform(df[[col]]) elif isinstance(encoder, LabelBinarizer): encoded = encoder.transform(df[col].astype(str)) if encoded.shape[1] == 1: df[col] = encoded.ravel() else: new_cols = [f"{col}_{c}" for c in encoder.classes_] df[new_cols] = encoded df.drop(columns=[col], inplace=True) except: pass # 3. One-hot if onehot_cols: existing = [c for c in onehot_cols if c in df.columns] if existing: df = pd.get_dummies(df, columns=existing, drop_first=True) # 4. Scaling for col, scaler in scalers.items(): if col in df.columns: try: df[[col]] = scaler.transform(df[[col]]) except: pass # 5. Align columns if trained_features: df = df.reindex(columns=trained_features, fill_value=0) prediction = model.predict(df) result = str(prediction[0]) return jsonify({'prediction': result, 'success': True}) except Exception as e: return jsonify({'error': str(e), 'success': False}) if __name__ == '__main__': print(f"\\n Model: {model_name}") print(f" Type: {problem_type}") print(f" Open http://localhost:5000 in your browser\\n") app.run(debug=True, host='0.0.0.0', port=5000) ''' def _gen_index_html(self, feature_names, numeric_cols, categorical_cols, categorical_values, target_name, model_name, problem_type): """Generate a beautiful, self-contained index.html.""" # Build form fields HTML form_fields = '' for feat in feature_names: if feat in categorical_cols and feat in categorical_values: options = categorical_values[feat] opts_html = ''.join([f'<option value="{v}">{v}</option>' for v in sorted(str(o) for o in options)]) form_fields += f''' <div class="col-md-6 mb-4"> <label class="form-label" for="field_{feat}">{feat}</label> <select class="form-select" id="field_{feat}" name="{feat}"> <option value="" selected>Select {feat}...</option> {opts_html} </select> <div class="form-text">Categorical</div> </div>''' else: form_fields += f''' <div class="col-md-6 mb-4"> <label class="form-label" for="field_{feat}">{feat}</label> <input type="number" step="any" class="form-control" id="field_{feat}" name="{feat}" placeholder="Enter {feat}"> <div class="form-text">Numeric</div> </div>''' return '''<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>''' + model_name + ''' β€” Prediction App</title> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css"> <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&display=swap" rel="stylesheet"> <style> :root { --primary: #6366f1; --primary-dark: #4f46e5; --accent: #06b6d4; --bg-dark: #0f172a; --bg-card: #1e293b; --bg-input: #334155; --text-primary: #f1f5f9; --text-muted: #94a3b8; --border: #475569; --success: #22c55e; --danger: #ef4444; } * { box-sizing: border-box; margin: 0; padding: 0; } body { font-family: 'Inter', sans-serif; background: var(--bg-dark); color: var(--text-primary); min-height: 100vh; } /* ── Background animation ─────────────────────────── */ body::before { content: ''; position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: radial-gradient(ellipse at 20% 50%, rgba(99, 102, 241, 0.12) 0%, transparent 50%), radial-gradient(ellipse at 80% 20%, rgba(6, 182, 212, 0.1) 0%, transparent 50%), radial-gradient(ellipse at 50% 80%, rgba(168, 85, 247, 0.08) 0%, transparent 50%); z-index: -1; animation: bgPulse 8s ease-in-out infinite alternate; } @keyframes bgPulse { 0% { opacity: 0.7; } 100% { opacity: 1; } } /* ── Navbar ───────────────────────────────────────── */ .navbar-custom { background: rgba(15, 23, 42, 0.85); backdrop-filter: blur(20px); border-bottom: 1px solid rgba(99, 102, 241, 0.2); padding: 1rem 0; } .navbar-custom .brand { font-weight: 800; font-size: 1.4rem; color: var(--text-primary); text-decoration: none; display: flex; align-items: center; gap: 0.6rem; } .navbar-custom .brand i { background: linear-gradient(135deg, var(--primary), var(--accent)); -webkit-background-clip: text; -webkit-text-fill-color: transparent; font-size: 1.6rem; } .badge-model { background: linear-gradient(135deg, var(--primary), var(--accent)); color: white; padding: 6px 14px; border-radius: 20px; font-size: 0.75rem; font-weight: 600; letter-spacing: 0.5px; } /* ── Hero ─────────────────────────────────────────── */ .hero { text-align: center; padding: 3rem 0 2rem; } .hero h1 { font-size: 2.6rem; font-weight: 800; margin-bottom: 0.6rem; background: linear-gradient(135deg, #f1f5f9, #cbd5e1); -webkit-background-clip: text; -webkit-text-fill-color: transparent; } .hero p { color: var(--text-muted); font-size: 1.1rem; max-width: 520px; margin: 0 auto; } .hero-badge { display: inline-flex; align-items: center; gap: 0.5rem; background: rgba(99, 102, 241, 0.15); border: 1px solid rgba(99, 102, 241, 0.3); padding: 8px 18px; border-radius: 30px; font-size: 0.85rem; color: var(--accent); margin-top: 1rem; } /* ── Glass Card ───────────────────────────────────── */ .glass-card { background: rgba(30, 41, 59, 0.7); backdrop-filter: blur(16px); border: 1px solid rgba(71, 85, 105, 0.4); border-radius: 20px; padding: 2.5rem; margin-bottom: 2rem; box-shadow: 0 25px 50px rgba(0, 0, 0, 0.3); transition: border-color 0.3s; } .glass-card:hover { border-color: rgba(99, 102, 241, 0.4); } .card-title { font-weight: 700; font-size: 1.3rem; margin-bottom: 1.5rem; display: flex; align-items: center; gap: 0.6rem; } .card-title i { color: var(--accent); } /* ── Form ─────────────────────────────────────────── */ .form-label { font-weight: 600; font-size: 0.85rem; color: var(--text-muted); text-transform: uppercase; letter-spacing: 0.7px; margin-bottom: 0.4rem; } .form-control, .form-select { background: var(--bg-input); border: 1px solid var(--border); color: var(--text-primary); border-radius: 12px; padding: 12px 16px; font-size: 0.95rem; transition: all 0.3s; } .form-control:focus, .form-select:focus { background: rgba(51, 65, 85, 0.9); border-color: var(--primary); box-shadow: 0 0 0 3px rgba(99, 102, 241, 0.15); color: var(--text-primary); } .form-control::placeholder { color: var(--text-muted); opacity: 0.6; } .form-text { color: var(--text-muted); font-size: 0.75rem; margin-top: 4px; } .form-select option { background: var(--bg-card); color: var(--text-primary); } /* ── Buttons ──────────────────────────────────────── */ .btn-predict { background: linear-gradient(135deg, var(--primary), var(--primary-dark)); border: none; color: white; padding: 14px 40px; border-radius: 14px; font-weight: 700; font-size: 1.05rem; transition: all 0.3s; width: 100%; position: relative; overflow: hidden; } .btn-predict:hover { transform: translateY(-2px); box-shadow: 0 12px 30px rgba(99, 102, 241, 0.35); color: white; } .btn-predict:active { transform: translateY(0); } .btn-reset { background: transparent; border: 1px solid var(--border); color: var(--text-muted); padding: 14px 40px; border-radius: 14px; font-weight: 600; font-size: 1rem; transition: all 0.3s; width: 100%; } .btn-reset:hover { border-color: var(--danger); color: var(--danger); } /* ── Result ───────────────────────────────────────── */ #resultSection { display: none; animation: slideUp 0.5s ease; } @keyframes slideUp { from { opacity: 0; transform: translateY(20px); } to { opacity: 1; transform: translateY(0); } } .result-value { font-size: 3rem; font-weight: 800; background: linear-gradient(135deg, var(--success), var(--accent)); -webkit-background-clip: text; -webkit-text-fill-color: transparent; word-break: break-all; } .result-label { color: var(--text-muted); font-size: 0.9rem; font-weight: 500; text-transform: uppercase; letter-spacing: 1px; } .error-value { background: linear-gradient(135deg, var(--danger), #f97316); -webkit-background-clip: text; -webkit-text-fill-color: transparent; } /* ── Loading Spinner ──────────────────────────────── */ .spinner-overlay { display: none; position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(15, 23, 42, 0.85); backdrop-filter: blur(8px); z-index: 9999; justify-content: center; align-items: center; flex-direction: column; gap: 1rem; } .spinner-ring { width: 50px; height: 50px; border: 4px solid rgba(99, 102, 241, 0.2); border-top-color: var(--primary); border-radius: 50%; animation: spin 0.8s linear infinite; } @keyframes spin { to { transform: rotate(360deg); } } /* ── Footer ───────────────────────────────────────── */ .footer { text-align: center; padding: 2rem 0; color: var(--text-muted); font-size: 0.8rem; border-top: 1px solid rgba(71, 85, 105, 0.3); margin-top: 3rem; } /* ── Stats Bar ────────────────────────────────────── */ .stats-bar { display: flex; gap: 2rem; justify-content: center; flex-wrap: wrap; margin: 1.5rem 0; } .stat-item { text-align: center; } .stat-item .stat-val { font-size: 1.6rem; font-weight: 700; color: var(--accent); } .stat-item .stat-lbl { font-size: 0.75rem; color: var(--text-muted); text-transform: uppercase; letter-spacing: 0.5px; } </style> </head> <body> <!-- Navbar --> <nav class="navbar-custom"> <div class="container d-flex justify-content-between align-items-center"> <a class="brand" href="#"> <i class="fas fa-brain"></i> ''' + model_name + ''' </a> <span class="badge-model"> <i class="fas fa-microchip"></i> ''' + problem_type.title() + ''' </span> </div> </nav> <!-- Hero --> <div class="container"> <div class="hero"> <h1><i class="fas fa-wand-magic-sparkles"></i> Prediction Engine</h1> <p>Enter your data below and get instant predictions powered by machine learning</p> <div class="hero-badge"> <i class="fas fa-bullseye"></i> Predicting: <strong>''' + target_name + '''</strong> </div> </div> <!-- Stats --> <div class="stats-bar"> <div class="stat-item"> <div class="stat-val">''' + str(len(feature_names)) + '''</div> <div class="stat-lbl">Features</div> </div> <div class="stat-item"> <div class="stat-val">''' + str(len(numeric_cols)) + '''</div> <div class="stat-lbl">Numeric</div> </div> <div class="stat-item"> <div class="stat-val">''' + str(len(categorical_cols)) + '''</div> <div class="stat-lbl">Categorical</div> </div> </div> <!-- Form Card --> <div class="row justify-content-center"> <div class="col-lg-10"> <form id="predictForm" class="glass-card"> <div class="card-title"> <i class="fas fa-sliders"></i> Input Features </div> <div class="row">''' + form_fields + ''' </div> <div class="row mt-3"> <div class="col-md-8 mb-2"> <button type="submit" class="btn-predict" id="predictBtn"> <i class="fas fa-bolt"></i> Get Prediction </button> </div> <div class="col-md-4 mb-2"> <button type="reset" class="btn-reset" id="resetBtn"> <i class="fas fa-rotate-left"></i> Reset </button> </div> </div> </form> <!-- Result --> <div id="resultSection" class="glass-card text-center"> <div class="card-title justify-content-center"> <i class="fas fa-sparkles"></i> Prediction Result </div> <div class="result-label mb-2">''' + target_name + '''</div> <div id="resultValue" class="result-value">β€”</div> </div> </div> </div> </div> <!-- Loading --> <div class="spinner-overlay" id="spinner"> <div class="spinner-ring"></div> <div style="color: var(--text-muted);">Analyzing...</div> </div> <!-- Footer --> <div class="footer"> <i class="fas fa-robot"></i> Powered by Data2Model β€” Automated Machine Learning Platform </div> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script> <script> const form = document.getElementById('predictForm'); const resultSection = document.getElementById('resultSection'); const resultValue = document.getElementById('resultValue'); const spinner = document.getElementById('spinner'); form.addEventListener('submit', async (e) => { e.preventDefault(); spinner.style.display = 'flex'; resultSection.style.display = 'none'; const formData = new FormData(form); try { const resp = await fetch('/predict', { method: 'POST', body: formData }); const data = await resp.json(); spinner.style.display = 'none'; resultSection.style.display = 'block'; resultSection.style.animation = 'none'; void resultSection.offsetHeight; // trigger reflow resultSection.style.animation = 'slideUp 0.5s ease'; if (data.success) { resultValue.textContent = data.prediction; resultValue.className = 'result-value'; } else { resultValue.textContent = data.error || 'Prediction failed'; resultValue.className = 'result-value error-value'; } } catch (err) { spinner.style.display = 'none'; resultSection.style.display = 'block'; resultValue.textContent = 'Connection error'; resultValue.className = 'result-value error-value'; } }); document.getElementById('resetBtn').addEventListener('click', () => { resultSection.style.display = 'none'; }); </script> </body> </html>''' # ───────────────────────────────────────────────────────────────────────── # Main Pipeline # ───────────────────────────────────────────────────────────────────────── def run_complete_pipeline(self, file_path, target_column=None, file_type='csv', problem_type='auto', split_type='train_test', # FIX 4 test_size=0.2, val_size=0.2, null_strategies=None, # FIX 1 & 2 scaling_config='standard', # FIX 6 encoding_config='auto', # FIX 7 categorical_overrides=None, # FIX 8 drop_columns=None): # NEW: Delete Columns feature print("\n" + "="*55) print("πŸš€ DATA2MODEL - AUTOMATED ML PIPELINE") print("="*55 + "\n") # 1. Load data = self.load_data(file_path, file_type) # Apply column dropping self.drop_columns = drop_columns or [] if self.drop_columns: # Ensure target column is not dropped if target_column in self.drop_columns: self.drop_columns.remove(target_column) print(f" Warning: Target column '{target_column}' cannot be dropped. It was removed from drop list.") existing_to_drop = [c for c in self.drop_columns if c in data.columns] if existing_to_drop: data = data.drop(columns=existing_to_drop) self.preprocessing_steps.append(f"Dropped columns: {', '.join(existing_to_drop)}") print(f" Dropped {len(existing_to_drop)} columns specified by user.") # Ensure numeric-looking columns accidentally read as strings are safely converted before detection/training for col in data.columns: if col == target_column: continue if str(data[col].dtype) in ('object', 'string'): converted = pd.to_numeric(data[col], errors='coerce') non_null_original = data[col].dropna().shape[0] non_null_converted = converted.dropna().shape[0] if non_null_original > 0 and non_null_converted >= 0.9 * non_null_original: data[col] = converted print(f" Safely converted numeric-looking column '{col}' to numeric.") # 2. Analyse with smart type detection (FIX 8) analysis = self.analyze_data(data, categorical_overrides, target_column=target_column) self.numeric_cols = analysis['numeric_columns'] self.categorical_cols = analysis['categorical_columns'] print(f" Numeric cols: {len(self.numeric_cols)} | Categorical cols: {len(self.categorical_cols)}") # 3. Null handling with imputation (FIX 1 & 2) print("\nπŸ”§ Handling missing values...") data = self.handle_missing_values(data, null_strategies, target_column=target_column) # 4. Remove duplicates before = len(data) data = data.drop_duplicates() if len(data) < before: print(f" Removed {before - len(data)} duplicate rows") # ── Unsupervised path (FIX 3: target column not needed) ────────────── is_unsupervised = problem_type in ('clustering', 'dimensionality_reduction', 'association') if is_unsupervised: X = data.copy() self.feature_names = list(X.columns) # Encode + Scale dummy_test = X.copy() X, dummy_test = self.encode_features(X, dummy_test, encoding_config=encoding_config, categorical_cols=self.categorical_cols) X, dummy_test = self.scale_features(X, dummy_test, scaling_config=scaling_config, numeric_cols=self.numeric_cols) self.trained_features = list(X.columns) self.train_unsupervised(X, problem_type) model_path = self.save_model() return { 'model_path': model_path, 'results': self.results, 'analysis': analysis, 'model_name': self.model_name, 'problem_type': self.problem_type, 'split_info': 'No split (unsupervised)', } # ── Supervised path ────────────────────────────────────────────────── if target_column is None or target_column not in data.columns: raise ValueError(f"Target column '{target_column}' not found.") X = data.drop(columns=[target_column]) y = data[target_column] self.feature_names = list(X.columns) self.target_name = target_column # Remove target from col lists if it was included num_cols = [c for c in self.numeric_cols if c != target_column] cat_cols = [c for c in self.categorical_cols if c != target_column] # Store categorical unique values for deployable app generation self.categorical_values = {} for col in cat_cols: if col in X.columns: self.categorical_values[col] = X[col].dropna().unique().tolist()[:50] # 5. Split (FIX 4) use_val = (split_type == 'train_test_val') if use_val: X_tr, X_tmp, y_tr, y_tmp = train_test_split(X, y, test_size=(test_size + val_size), random_state=42) ratio = val_size / (test_size + val_size) X_te, X_val, y_te, y_val = train_test_split(X_tmp, y_tmp, test_size=ratio, random_state=42) split_info = f"Train {int((1-test_size-val_size)*100)}% / Test {int(test_size*100)}% / Val {int(val_size*100)}%" print(f"\nβœ‚ Split: {split_info}") print(f" Train: {len(X_tr)} | Test: {len(X_te)} | Val: {len(X_val)}") else: X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=test_size, random_state=42) X_val, y_val = None, None split_info = f"Train {int((1-test_size)*100)}% / Test {int(test_size*100)}%" print(f"\nβœ‚ Split: {split_info}") print(f" Train: {len(X_tr)} | Test: {len(X_te)}") # 6. Encode categorical (FIX 5 & 7: only if cat cols exist, per-column) print("\nπŸ”€ Encoding categorical features...") if use_val: X_tr, X_te, X_val = self.encode_features( X_tr, X_te, X_val, encoding_config=encoding_config, categorical_cols=cat_cols) else: X_tr, X_te = self.encode_features( X_tr, X_te, encoding_config=encoding_config, categorical_cols=cat_cols) # 7. Scale numeric (FIX 6: per-column) print("βš– Scaling numeric features...") # Update numeric_cols after encoding (some may have been one-hot expanded) current_num_cols = [c for c in X_tr.columns if c in num_cols] if use_val: X_tr, X_te, X_val = self.scale_features( X_tr, X_te, X_val, scaling_config=scaling_config, numeric_cols=current_num_cols) else: X_tr, X_te = self.scale_features( X_tr, X_te, scaling_config=scaling_config, numeric_cols=current_num_cols) # 8. Train print("\nπŸ€– Training models...") self.trained_features = list(X_tr.columns) self.train_model(X_tr, y_tr, X_te, y_te, problem_type=problem_type) # 9. Validation metrics (if val split used) if use_val and self.model: y_val_pred = self.model.predict(X_val) if self.problem_type == 'classification': val_acc = accuracy_score(y_val, y_val_pred) self.results['validation_accuracy'] = val_acc print(f" Validation Accuracy: {val_acc:.4f}") else: self.results['validation_rmse'] = np.sqrt(mean_squared_error(y_val, y_val_pred)) self.results['validation_r2'] = r2_score(y_val, y_val_pred) print(f" Validation RΒ²: {self.results['validation_r2']:.4f}") # 10. Save model_path = self.save_model() # Save preprocessing artifacts only when they were applied scaler_path = None encoder_path = None if self.scalers: scaler_path = self.save_scalers() if self.encoders or (hasattr(self, 'onehot_cols') and self.onehot_cols): encoder_path = self.save_encoders() # Generate the deployable app bundle deployable_app_path = self.generate_deployable_app(model_path, scaler_path, encoder_path) print("\n" + "="*55) print("βœ… PIPELINE COMPLETED!") print("="*55 + "\n") return { 'model_path': model_path, 'scaler_path': scaler_path, 'encoder_path': encoder_path, 'deployable_app_path': deployable_app_path, 'scaling_applied': bool(self.scalers), 'encoding_applied': bool(self.encoders) or (hasattr(self, 'onehot_cols') and bool(self.onehot_cols)), 'results': self.results, 'analysis': analysis, 'model_name': self.model_name, 'problem_type': self.problem_type, 'split_info': split_info, 'use_val': use_val, }
"""
Data2Model - Automated Machine Learning Pipeline
Fully updated with all fixes:
1. Imputation instead of deletion for null values
2. Per-column null strategy support
3. Optional target column for unsupervised
4. Flexible train-test and train-test-validation splits
5. Dynamic encoding (only when categorical columns exist)
6. Per-column scaling
7. Per-column encoding
8. Proper data type detection (numeric vs categorical)
9. Dashboard with visualizations
10. Target column excluded from preprocessing
11. Download preprocessing components
"""
import numpy as np
import pandas as pd
import pickle
import os
import json
import base64
from io import BytesIO
from datetime import datetime
import matplotlib
matplotlib.use('Agg') # Non-interactive backend
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import (
StandardScaler, MinMaxScaler, RobustScaler, Normalizer,
LabelEncoder, OneHotEncoder, OrdinalEncoder, LabelBinarizer
)
from sklearn.impute import SimpleImputer
from sklearn.metrics import (
accuracy_score, precision_score, recall_score, f1_score,
mean_squared_error, r2_score, mean_absolute_error,
classification_report, confusion_matrix
)
import warnings
warnings.filterwarnings('ignore')
import sys, io
if sys.stdout.encoding != 'utf-8':
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8', errors='replace')
if sys.stderr.encoding != 'utf-8':
sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding='utf-8', errors='replace')
# Supervised - Classification
from sklearn.linear_model import LogisticRegression
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier, AdaBoostClassifier
from sklearn.svm import SVC
from sklearn.neighbors import KNeighborsClassifier
from sklearn.naive_bayes import GaussianNB
# Supervised - Regression
from sklearn.linear_model import LinearRegression
from sklearn.tree import DecisionTreeRegressor
from sklearn.ensemble import RandomForestRegressor, GradientBoostingRegressor, AdaBoostRegressor
from sklearn.svm import SVR
from sklearn.neighbors import KNeighborsRegressor
# Unsupervised
from sklearn.cluster import KMeans, DBSCAN, AgglomerativeClustering
from sklearn.decomposition import PCA
# Advanced Models
try:
import xgboost as xgb
XGBOOST_AVAILABLE = True
except ImportError:
XGBOOST_AVAILABLE = False
try:
import lightgbm as lgb
LIGHTGBM_AVAILABLE = True
except ImportError:
LIGHTGBM_AVAILABLE = False
# ─────────────────────────────────────────────────────────────────────────────
# FIX 8: Strict data-type detector
# ─────────────────────────────────────────────────────────────────────────────
def detect_column_types(data, categorical_overrides=None):
"""
Detect numeric vs categorical columns relying purely on dataframe dtypes,
not heuristics like low cardinality or unique value count, unless explicitly overridden.
"""
if categorical_overrides is None:
categorical_overrides = []
numeric_cols = []
categorical_cols = []
for col in data.columns:
if col in categorical_overrides:
categorical_cols.append(col)
continue