Spaces:
Configuration error
Configuration error
File size: 15,176 Bytes
50a9cf2 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 | #!/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()
|