architectraghu commited on
Commit
bdbb2ee
·
verified ·
1 Parent(s): 72ac98e

Upload model.py

Browse files
Files changed (1) hide show
  1. model.py +61 -0
model.py ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Loader + server helper for the CBC Manufacturing RUL LSTM reference model.
2
+
3
+ The model is a torch LSTM, so (unlike the other CBC reference models) it cannot be loaded
4
+ with joblib alone — you need this class definition plus the saved state_dict and the
5
+ normalization meta. Usage:
6
+
7
+ from model import load_model, predict_rul
8
+ model, meta = load_model(".") # dir holding manufacturing_lstm.pt + _meta.joblib
9
+ rul = predict_rul(model, meta, raw_window) # raw_window: list[ list[float] ], shape window x n_sensors
10
+ """
11
+ from __future__ import annotations
12
+
13
+ import json
14
+ from pathlib import Path
15
+
16
+ import joblib
17
+ import numpy as np
18
+ import torch
19
+ from torch import nn
20
+
21
+
22
+ class LSTMReg(nn.Module):
23
+ def __init__(self, n_feat: int, hidden: int = 64) -> None:
24
+ super().__init__()
25
+ self.lstm = nn.LSTM(n_feat, hidden, batch_first=True)
26
+ self.head = nn.Linear(hidden, 1)
27
+
28
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
29
+ out, _ = self.lstm(x)
30
+ return self.head(out[:, -1, :]).squeeze(-1)
31
+
32
+
33
+ def load_model(model_dir: str = "."):
34
+ """Return (model, meta). model_dir holds manufacturing_lstm.pt + manufacturing_meta.joblib."""
35
+ d = Path(model_dir)
36
+ meta = joblib.load(d / "manufacturing_meta.joblib")
37
+ model = LSTMReg(meta["n_features"], meta["hidden"])
38
+ model.load_state_dict(torch.load(d / "manufacturing_lstm.pt", map_location="cpu"))
39
+ model.eval()
40
+ return model, meta
41
+
42
+
43
+ def predict_rul(model, meta, raw_window) -> float:
44
+ """raw_window: window x n_sensors of RAW sensor values (in meta['sensors'] order)."""
45
+ sensors = meta["sensors"]
46
+ mn = np.array([meta["mins"][s] for s in sensors], dtype=np.float32)
47
+ mx = np.array([meta["maxs"][s] for s in sensors], dtype=np.float32)
48
+ arr = np.asarray(raw_window, dtype=np.float32)
49
+ if arr.shape != (meta["window"], len(sensors)):
50
+ raise ValueError(f"expected window {meta['window']} x {len(sensors)} sensors, got {arr.shape}")
51
+ norm = (arr - mn) / (mx - mn)
52
+ with torch.no_grad():
53
+ pred = model(torch.from_numpy(norm[None, :, :]).float()).numpy()
54
+ return float(np.clip(pred, 0, None)[0])
55
+
56
+
57
+ if __name__ == "__main__":
58
+ m, meta = load_model(Path(__file__).parent)
59
+ sample = json.load(open(Path(__file__).parent / "sample_input.json"))
60
+ print("predicted RUL:", round(predict_rul(m, meta, sample["window"]), 2),
61
+ "| true RUL:", sample.get("true_rul"))