Spaces:
Configuration error
Configuration error
Download scripts/train_maintenance_model.py from Financbase/eagleviz-maintenance-trainer: direct link, hf CLI and curl.
- Browser
- Download file 15.2 kB
-
https://huggingface.co/spaces/Financbase/eagleviz-maintenance-trainer/resolve/main/scripts/train_maintenance_model.py
- Command line
-
hf download hf://spaces/Financbase/eagleviz-maintenance-trainer/scripts/train_maintenance_model.py
-
curl -L -o train_maintenance_model.py https://huggingface.co/spaces/Financbase/eagleviz-maintenance-trainer/resolve/main/scripts/train_maintenance_model.py
15.2 kB
| #!/usr/bin/env python3 | |
| """ | |
| Maintenance Prediction Model Training Script | |
| Trains a predictive maintenance model using the AI4I dataset. | |
| If PyTorch is available, uses Hugging Face Transformers with PEFT. | |
| If PyTorch isn't available (e.g., Intel macOS without wheels), falls back to a | |
| scikit-learn classifier to keep the pipeline runnable everywhere. | |
| """ | |
| import os | |
| from typing import Tuple, Optional | |
| import pandas as pd | |
| import numpy as np | |
| from sklearn.metrics import accuracy_score, precision_recall_fscore_support | |
| # Torch is optional; avoid importing unless explicitly requested | |
| TORCH_AVAILABLE = False | |
| def _try_enable_torch() -> bool: | |
| global TORCH_AVAILABLE | |
| if TORCH_AVAILABLE: | |
| return True | |
| try: | |
| import torch # type: ignore | |
| TORCH_AVAILABLE = True | |
| return True | |
| except Exception: | |
| TORCH_AVAILABLE = False | |
| return False | |
| def load_and_preprocess_data() -> Tuple[Optional[pd.DataFrame], Optional[pd.DataFrame], Optional[pd.DataFrame]]: | |
| """Load and preprocess the AI4I maintenance dataset""" | |
| print("π Loading AI4I maintenance dataset...") | |
| # Check if processed dataset exists | |
| data_dir = "data/maintenance_datasets" | |
| if os.path.exists(f"{data_dir}/train.csv"): | |
| print("β Using preprocessed dataset splits") | |
| train_df = pd.read_csv(f"{data_dir}/train.csv") | |
| val_df = pd.read_csv(f"{data_dir}/validation.csv") | |
| test_df = pd.read_csv(f"{data_dir}/test.csv") | |
| # Ensure binary label column exists | |
| for df in (train_df, val_df, test_df): | |
| if 'label' not in df.columns: | |
| if 'Machine failure' in df.columns: | |
| df['label'] = df['Machine failure'].astype(int) | |
| else: | |
| # Fallback: treat any non "no_maintenance" failure_type as 1 | |
| if 'failure_type' in df.columns: | |
| df['label'] = (df['failure_type'] != 'no_maintenance').astype(int) | |
| else: | |
| raise ValueError("Could not infer labels: expected 'Machine failure' or 'failure_type' column") | |
| else: | |
| print("β οΈ Preprocessed splits not found. Using raw dataset...") | |
| # Fallback to raw dataset | |
| raw_path = f"{data_dir}/ai4i2020.csv" | |
| if not os.path.exists(raw_path): | |
| print(f"β Dataset not found at {raw_path}") | |
| print("Run: python scripts/download_ai4i_dataset.py") | |
| return None, None, None | |
| df = pd.read_csv(raw_path) | |
| # Create maintenance descriptions | |
| df['maintenance_description'] = df.apply(create_description, axis=1) | |
| df['label'] = df['Machine failure'].astype(int) | |
| # Simple split (70/15/15) | |
| n = len(df) | |
| train_df = df[:int(0.7*n)] | |
| val_df = df[int(0.7*n):int(0.85*n)] | |
| test_df = df[int(0.85*n):] | |
| print(f"π Dataset sizes:") | |
| print(f" Train: {len(train_df)} samples") | |
| print(f" Validation: {len(val_df)} samples") | |
| print(f" Test: {len(test_df)} samples") | |
| return train_df, val_df, test_df | |
| def create_description(row): | |
| """Create maintenance description from sensor data""" | |
| return ( | |
| f"Machine with air temperature {row['Air temperature [K]']:.1f}K, " | |
| f"process temperature {row['Process temperature [K]']:.1f}K, " | |
| f"rotational speed {row['Rotational speed [rpm]']} rpm, " | |
| f"torque {row['Torque [Nm]']:.1f} Nm, " | |
| f"tool wear {row['Tool wear [min]']} minutes. " | |
| f"Machine failure: {'Yes' if row['Machine failure'] else 'No'}" | |
| ) | |
| def tokenize_dataset(dataset, tokenizer): | |
| """Tokenize dataset for model training""" | |
| def tokenize_function(examples): | |
| return tokenizer( | |
| examples["maintenance_description"], | |
| padding="max_length", | |
| truncation=True, | |
| max_length=128 | |
| ) | |
| tokenized_dataset = dataset.map(tokenize_function, batched=True) | |
| tokenized_dataset = tokenized_dataset.rename_column("label", "labels") | |
| tokenized_dataset.set_format("torch", columns=["input_ids", "attention_mask", "labels"]) | |
| return tokenized_dataset | |
| def compute_metrics(eval_pred): | |
| """Compute evaluation metrics""" | |
| predictions, labels = eval_pred | |
| predictions = np.argmax(predictions, axis=1) | |
| accuracy = accuracy_score(labels, predictions) | |
| precision, recall, f1, _ = precision_recall_fscore_support(labels, predictions, average='binary') | |
| return { | |
| 'accuracy': accuracy, | |
| 'precision': precision, | |
| 'recall': recall, | |
| 'f1': f1 | |
| } | |
| def train_with_transformers(train_df: pd.DataFrame, val_df: pd.DataFrame, test_df: pd.DataFrame): | |
| """Train a sequence classifier using Transformers + PEFT. | |
| Chooses a model and precision based on CUDA availability to ensure it runs | |
| on CPU-only systems as well. | |
| """ | |
| # Lazy imports to avoid requiring these packages when falling back to sklearn | |
| from datasets import Dataset # type: ignore | |
| from transformers import ( | |
| AutoTokenizer, | |
| AutoModelForSequenceClassification, | |
| TrainingArguments, | |
| Trainer, | |
| EarlyStoppingCallback | |
| ) # type: ignore | |
| from peft import ( | |
| LoraConfig, | |
| get_peft_model, | |
| TaskType | |
| ) # type: ignore | |
| # Enable torch now (lazy) and check CUDA | |
| import torch # type: ignore | |
| is_cuda = torch.cuda.is_available() | |
| # Use a lighter model on CPU-only to keep runtime reasonable | |
| model_name = "facebook/bart-large-mnli" if is_cuda else "distilbert-base-uncased" | |
| fp16 = bool(is_cuda) | |
| print(f"π₯ Loading model: {model_name}") | |
| tokenizer = AutoTokenizer.from_pretrained(model_name) | |
| model = AutoModelForSequenceClassification.from_pretrained( | |
| model_name, | |
| num_labels=2, | |
| problem_type="single_label_classification" | |
| ) | |
| # Configure PEFT | |
| print("β‘ Configuring PEFT (LoRA)...") | |
| try: | |
| peft_config = LoraConfig( | |
| task_type=TaskType.SEQ_CLS, | |
| r=8, | |
| lora_alpha=16, | |
| lora_dropout=0.05, | |
| bias="none", | |
| target_modules=["q_lin", "k_lin", "v_lin", "out_lin", "query", "key", "value", "dense"] | |
| ) | |
| model = get_peft_model(model, peft_config) | |
| except Exception as peft_err: | |
| print(f"β οΈ PEFT configuration failed ({peft_err}). Proceeding without PEFT.") | |
| print(f"π§ Trainable parameters: {sum(p.numel() for p in model.parameters() if p.requires_grad)}") | |
| print(f"π Total parameters: {sum(p.numel() for p in model.parameters())}") | |
| # Convert to HuggingFace datasets | |
| train_dataset = Dataset.from_pandas(train_df[['maintenance_description', 'label']]) | |
| val_dataset = Dataset.from_pandas(val_df[['maintenance_description', 'label']]) | |
| test_dataset = Dataset.from_pandas(test_df[['maintenance_description', 'label']]) | |
| # Tokenize datasets | |
| print("π€ Tokenizing datasets...") | |
| train_tokenized = tokenize_dataset(train_dataset, tokenizer) | |
| val_tokenized = tokenize_dataset(val_dataset, tokenizer) | |
| # Training arguments | |
| training_args = TrainingArguments( | |
| output_dir="./models/maintenance-predictor", | |
| num_train_epochs=5, | |
| per_device_train_batch_size=8 if is_cuda else 16, | |
| per_device_eval_batch_size=8 if is_cuda else 32, | |
| warmup_steps=100, | |
| weight_decay=0.01, | |
| logging_dir="./logs", | |
| logging_steps=10, | |
| save_steps=100, | |
| evaluation_strategy="steps", | |
| eval_steps=50, | |
| save_strategy="steps", | |
| load_best_model_at_end=True, | |
| metric_for_best_model="f1", | |
| greater_is_better=True, | |
| fp16=fp16, | |
| gradient_accumulation_steps=2, | |
| learning_rate=5e-5, | |
| lr_scheduler_type="cosine", | |
| report_to="none", | |
| ) | |
| # Create trainer | |
| trainer = Trainer( | |
| model=model, | |
| args=training_args, | |
| train_dataset=train_tokenized, | |
| eval_dataset=val_tokenized, | |
| tokenizer=tokenizer, | |
| compute_metrics=compute_metrics, | |
| callbacks=[EarlyStoppingCallback(early_stopping_patience=3)] | |
| ) | |
| # Train model | |
| print("π Starting training (Transformers)...") | |
| trainer.train() | |
| # Evaluate on test set | |
| print("π§ͺ Evaluating on test set...") | |
| test_tokenized = tokenize_dataset(test_dataset, tokenizer) | |
| test_results = trainer.evaluate(test_tokenized) | |
| print("π Test Results:") | |
| for metric, value in test_results.items(): | |
| if metric.startswith("eval_"): | |
| print(f"{metric}: {value:.4f}") | |
| # Save model | |
| print("πΎ Saving fine-tuned model...") | |
| os.makedirs("./models/maintenance-predictor", exist_ok=True) | |
| model.save_pretrained("./models/maintenance-predictor") | |
| tokenizer.save_pretrained("./models/maintenance-predictor") | |
| # Push to Hugging Face Hub | |
| print("π Pushing to Hugging Face Hub...") | |
| try: | |
| from huggingface_hub import HfApi # type: ignore | |
| api = HfApi() | |
| repo_id = "Financbase/maintenance-classifier-v1" | |
| # Push the model | |
| api.upload_folder( | |
| folder_path="./models/maintenance-predictor", | |
| repo_id=repo_id, | |
| repo_type="model" | |
| ) | |
| print(f"β Model pushed to: https://huggingface.co/{repo_id}") | |
| print("π― Ready for EagleViz integration!") | |
| except Exception as e: | |
| print(f"β οΈ Failed to push to HF Hub: {e}") | |
| print("π‘ Model saved locally - you can manually upload to HF Hub") | |
| # Test predictions | |
| print("π§ͺ Testing sample predictions...") | |
| test_samples = [ | |
| "Machine with air temperature 298.1K, process temperature 308.6K, rotational speed 1551 rpm, torque 42.8 Nm, tool wear 0 minutes", | |
| "Machine with air temperature 298.2K, process temperature 308.7K, rotational speed 1408 rpm, torque 46.3 Nm, tool wear 3 minutes. Machine failure: Yes", | |
| "Machine with air temperature 298.9K, process temperature 309.1K, rotational speed 1604 rpm, torque 29.5 Nm, tool wear 14 minutes" | |
| ] | |
| model.eval() | |
| for sample in test_samples: | |
| inputs = tokenizer(sample, return_tensors="pt", padding=True, truncation=True) | |
| with torch.no_grad(): | |
| outputs = model(**inputs) | |
| prediction = torch.argmax(outputs.logits, dim=1).item() | |
| confidence = torch.softmax(outputs.logits, dim=1)[0][prediction].item() | |
| print(f"Sample: {sample[:60]}...") | |
| print(f"Prediction: {'MAINTENANCE NEEDED' if prediction else 'OK'}") | |
| print(f"Confidence: {confidence:.3f}") | |
| print("---") | |
| return "transformers" | |
| def train_with_sklearn(train_df: pd.DataFrame, val_df: pd.DataFrame, test_df: pd.DataFrame): | |
| """Fallback: Train a simple classifier using scikit-learn. | |
| Uses TF-IDF features + Logistic Regression. Exports a joblib artifact. | |
| """ | |
| from sklearn.pipeline import Pipeline | |
| from sklearn.feature_extraction.text import TfidfVectorizer | |
| from sklearn.linear_model import LogisticRegression | |
| import joblib | |
| print("βοΈ Using scikit-learn fallback (PyTorch not available).") | |
| pipeline = Pipeline([ | |
| ("tfidf", TfidfVectorizer(max_features=20000, ngram_range=(1, 2))), | |
| ("clf", LogisticRegression(max_iter=200)) | |
| ]) | |
| X_train = train_df["maintenance_description"].astype(str) | |
| y_train = train_df["label"].astype(int) | |
| X_val = val_df["maintenance_description"].astype(str) | |
| y_val = val_df["label"].astype(int) | |
| X_test = test_df["maintenance_description"].astype(str) | |
| y_test = test_df["label"].astype(int) | |
| print("π Starting training (scikit-learn)...") | |
| pipeline.fit(pd.concat([X_train, X_val]), pd.concat([y_train, y_val])) | |
| print("π§ͺ Evaluating on test set...") | |
| preds = pipeline.predict(X_test) | |
| accuracy = accuracy_score(y_test, preds) | |
| precision, recall, f1, _ = precision_recall_fscore_support(y_test, preds, average='binary') | |
| print(f"accuracy: {accuracy:.4f}") | |
| print(f"precision: {precision:.4f}") | |
| print(f"recall: {recall:.4f}") | |
| print(f"f1: {f1:.4f}") | |
| # Save model | |
| os.makedirs("./models/maintenance-predictor", exist_ok=True) | |
| joblib.dump(pipeline, "./models/maintenance-predictor/sklearn_pipeline.joblib") | |
| print("π§ͺ Testing sample predictions...") | |
| test_samples = [ | |
| "Machine with air temperature 298.1K, process temperature 308.6K, rotational speed 1551 rpm, torque 42.8 Nm, tool wear 0 minutes", | |
| "Machine with air temperature 298.2K, process temperature 308.7K, rotational speed 1408 rpm, torque 46.3 Nm, tool wear 3 minutes. Machine failure: Yes", | |
| "Machine with air temperature 298.9K, process temperature 309.1K, rotational speed 1604 rpm, torque 29.5 Nm, tool wear 14 minutes" | |
| ] | |
| for sample in test_samples: | |
| proba = pipeline.predict_proba([sample])[0] | |
| prediction = int(np.argmax(proba)) | |
| confidence = float(np.max(proba)) | |
| print(f"Sample: {sample[:60]}...") | |
| print(f"Prediction: {'MAINTENANCE NEEDED' if prediction else 'OK'}") | |
| print(f"Confidence: {confidence:.3f}") | |
| print("---") | |
| return "sklearn" | |
| def train_maintenance_model(): | |
| """Main training function""" | |
| print("π€ Training Maintenance Prediction Model") | |
| print("=" * 40) | |
| # Load data | |
| train_df, val_df, test_df = load_and_preprocess_data() | |
| if train_df is None: | |
| return None | |
| # Decide training route | |
| route = None | |
| use_transformers = os.getenv("EAGLEVIZ_USE_TRANSFORMERS", "0").strip() == "1" | |
| if use_transformers and _try_enable_torch(): | |
| try: | |
| route = train_with_transformers(train_df, val_df, test_df) | |
| except Exception as e: | |
| print(f"β οΈ Transformers training failed, falling back to sklearn: {e}") | |
| route = train_with_sklearn(train_df, val_df, test_df) | |
| else: | |
| route = train_with_sklearn(train_df, val_df, test_df) | |
| print("β Training complete!") | |
| print("π Artifacts saved to: ./models/maintenance-predictor") | |
| print(f"π§ Training route used: {route}") | |
| print("π― Ready for integration with EagleViz!") | |
| return route | |
| def main(): | |
| """Main execution""" | |
| try: | |
| route = train_maintenance_model() | |
| if route: | |
| print("\nπ Success! Your maintenance prediction model is ready.") | |
| print("Next steps:") | |
| print("1. Integrate with EagleViz: Update HuggingFaceIntegration.ts or sklearn loader") | |
| print("2. Test with real data: Use your actual maintenance records") | |
| print("3. Monitor performance: Track prediction accuracy over time") | |
| print("4. Fine-tune further: Add more domain-specific training data") | |
| except Exception as e: | |
| print(f"β Training failed: {e}") | |
| print("Troubleshooting:") | |
| print("1. Ensure AI4I dataset is downloaded: python scripts/download_ai4i_dataset.py") | |
| print("2. If using Transformers, verify PyTorch is installed for your platform") | |
| print("3. Try reducing batch size in training arguments") | |
| print("4. Ensure all dependencies are installed") | |
| if __name__ == "__main__": | |
| main() | |