Sahil Garg commited on
Commit
caa411d
·
1 Parent(s): d8c5e83

added fault label

Browse files
Files changed (2) hide show
  1. ml/artifacts/xgb_fault.json +0 -0
  2. ml/inference.py +73 -3
ml/artifacts/xgb_fault.json ADDED
The diff for this file is too large to render. See raw diff
 
ml/inference.py CHANGED
@@ -66,6 +66,21 @@ class MLEngine:
66
  self.ttf_model.load_model(os.path.join(ARTIFACTS_DIR, "xgb_ttf.json"))
67
  self.fail_model = xgb.XGBClassifier()
68
  self.fail_model.load_model(os.path.join(ARTIFACTS_DIR, "xgb_fail.json"))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
69
 
70
  def _load_lstm_model(self):
71
  """Load LSTM autoencoder from safetensors."""
@@ -93,23 +108,73 @@ class MLEngine:
93
 
94
  def _make_predictions(self, df_scaled: pd.DataFrame, anomaly_lstm: float, health: float) -> dict:
95
  """Make TTF and failure probability predictions.
96
- Returns: Dictionary with ttf, failure_prob, and rul predictions
97
  """
98
  latest_features = df_scaled[self.feature_cols].iloc[[-1]].copy()
99
  latest_features["anomaly_lstm"] = anomaly_lstm
100
  latest_features["health_index"] = health
 
 
101
  expected_ttf_days = float(
102
  self.ttf_model.predict(latest_features, validate_features=False)[0]
103
  )
 
 
104
  failure_probability = float(
105
  self.fail_model.predict_proba(latest_features, validate_features=False)[0][1]
106
  )
 
 
107
  expected_rul_days = float(health * self.design_life_days)
108
- confidence = round(0.5 * abs(failure_probability - 0.5) * 2 + 0.5 * health, 2)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
109
  return {
110
  "ttf_days": expected_ttf_days,
111
- "failure_prob": failure_probability,
112
  "rul_days": expected_rul_days,
 
 
 
 
 
113
  "confidence": confidence
114
  }
115
 
@@ -133,8 +198,13 @@ class MLEngine:
133
  logger.info("ML analysis end")
134
  return {
135
  "asset_id": asset_id,
 
 
 
136
  "failure_probability": round(predictions["failure_prob"], 2),
137
  "expected_ttf_days": round(predictions["ttf_days"], 1),
138
  "expected_rul_days": round(predictions["rul_days"], 1),
 
 
139
  "confidence": predictions["confidence"]
140
  }
 
66
  self.ttf_model.load_model(os.path.join(ARTIFACTS_DIR, "xgb_ttf.json"))
67
  self.fail_model = xgb.XGBClassifier()
68
  self.fail_model.load_model(os.path.join(ARTIFACTS_DIR, "xgb_fail.json"))
69
+
70
+ # Load fault type classifier if available
71
+ fault_model_path = os.path.join(ARTIFACTS_DIR, "xgb_fault.json")
72
+ if os.path.exists(fault_model_path):
73
+ self.fault_model = xgb.XGBClassifier()
74
+ self.fault_model.load_model(fault_model_path)
75
+ self.fault_map = {
76
+ 0: "Normal",
77
+ 1: "Short Circuit",
78
+ 2: "Degradation",
79
+ 3: "Open Circuit",
80
+ 4: "Shadowing"
81
+ }
82
+ else:
83
+ self.fault_model = None
84
 
85
  def _load_lstm_model(self):
86
  """Load LSTM autoencoder from safetensors."""
 
108
 
109
  def _make_predictions(self, df_scaled: pd.DataFrame, anomaly_lstm: float, health: float) -> dict:
110
  """Make TTF and failure probability predictions.
111
+ Returns: Dictionary with all predictions including new metrics
112
  """
113
  latest_features = df_scaled[self.feature_cols].iloc[[-1]].copy()
114
  latest_features["anomaly_lstm"] = anomaly_lstm
115
  latest_features["health_index"] = health
116
+
117
+ # TTF prediction
118
  expected_ttf_days = float(
119
  self.ttf_model.predict(latest_features, validate_features=False)[0]
120
  )
121
+
122
+ # Failure probability (improved calculation from Colab)
123
  failure_probability = float(
124
  self.fail_model.predict_proba(latest_features, validate_features=False)[0][1]
125
  )
126
+
127
+ # RUL calculation
128
  expected_rul_days = float(health * self.design_life_days)
129
+
130
+ # Health trend (over last 200 points if available)
131
+ if len(df_scaled) >= 200:
132
+ # Calculate health trend by computing health over the window
133
+ recent_health_values = []
134
+ for i in range(max(0, len(df_scaled) - 200), len(df_scaled)):
135
+ temp_df = df_scaled.iloc[:i+1]
136
+ if len(temp_df) >= self.seq_len:
137
+ temp_anomaly, temp_health = self._compute_anomalies(temp_df.iloc[-self.seq_len:])
138
+ recent_health_values.append(temp_health)
139
+ health_trend = recent_health_values[-1] - recent_health_values[0] if recent_health_values else 0.0
140
+ else:
141
+ health_trend = 0.0
142
+
143
+ # Fault type prediction
144
+ predicted_fault_type = "Unknown"
145
+ fault_confidence = 0.0
146
+ if self.fault_model is not None:
147
+ fault_pred = int(self.fault_model.predict(latest_features, validate_features=False)[0])
148
+ predicted_fault_type = self.fault_map.get(fault_pred, "Unknown")
149
+ fault_proba = self.fault_model.predict_proba(latest_features, validate_features=False)[0]
150
+ fault_confidence = float(np.max(fault_proba))
151
+
152
+ # Improved failure probability calculation (from Colab)
153
+ ttf_norm = 1 - min(expected_ttf_days / self.design_life_days, 1.0)
154
+ health_risk = 1 - health
155
+ trend_risk = max(-health_trend, 0) * 50
156
+ anomaly_risk = min(anomaly_lstm / 1e6, 1.0) # Normalize anomaly
157
+
158
+ improved_failure_prob = (
159
+ 0.35 * anomaly_risk +
160
+ 0.30 * health_risk +
161
+ 0.20 * ttf_norm +
162
+ 0.15 * trend_risk
163
+ )
164
+ improved_failure_prob = min(max(improved_failure_prob, 0), 1)
165
+
166
+ # Overall confidence
167
+ confidence = round(0.5 * abs(improved_failure_prob - 0.5) * 2 + 0.5 * health, 2)
168
+
169
  return {
170
  "ttf_days": expected_ttf_days,
171
+ "failure_prob": improved_failure_prob,
172
  "rul_days": expected_rul_days,
173
+ "health_score": round(health, 3),
174
+ "anomaly_score": round(anomaly_lstm, 4),
175
+ "health_trend_200step": round(health_trend, 4),
176
+ "predicted_fault_type": predicted_fault_type,
177
+ "fault_confidence": round(fault_confidence, 2),
178
  "confidence": confidence
179
  }
180
 
 
198
  logger.info("ML analysis end")
199
  return {
200
  "asset_id": asset_id,
201
+ "health_score": predictions["health_score"],
202
+ "anomaly_score": predictions["anomaly_score"],
203
+ "health_trend_200step": predictions["health_trend_200step"],
204
  "failure_probability": round(predictions["failure_prob"], 2),
205
  "expected_ttf_days": round(predictions["ttf_days"], 1),
206
  "expected_rul_days": round(predictions["rul_days"], 1),
207
+ "predicted_fault_type": predictions["predicted_fault_type"],
208
+ "fault_confidence": predictions["fault_confidence"],
209
  "confidence": predictions["confidence"]
210
  }