-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtrain_har.py
More file actions
126 lines (100 loc) · 4.55 KB
/
train_har.py
File metadata and controls
126 lines (100 loc) · 4.55 KB
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
import os
import numpy as np
import torch
from torch import nn
from torch.utils.data import Dataset, DataLoader
import matplotlib.pyplot as plt
class HARFeatures(Dataset):
def __init__(self, root, split):
X = np.loadtxt(os.path.join(root, split, f"X_{split}.txt"), dtype=np.float32)
y = np.loadtxt(os.path.join(root, split, f"y_{split}.txt"), dtype=np.int64) - 1
self.X = torch.from_numpy(X)
self.y = torch.from_numpy(y)
def __len__(self): return self.X.shape[0]
def __getitem__(self, i): return self.X[i], self.y[i]
class SmallMLP(nn.Module):
def __init__(self, in_dim=561, num_classes=6):
super().__init__()
self.net = nn.Sequential(
nn.Linear(in_dim, 32), nn.ReLU(),
nn.Linear(32, 16), nn.ReLU(),
nn.Linear(16, num_classes),
)
def forward(self, x): return self.net(x)
def main():
root = "UCI HAR Dataset"
device = "cuda" if torch.cuda.is_available() else "cpu"
train_ds = HARFeatures(root, "train")
train_loader = DataLoader(train_ds, batch_size=256, shuffle=True)
model = SmallMLP().to(device)
opt = torch.optim.Adam(model.parameters(), lr=1e-3)
loss_fn = nn.CrossEntropyLoss()
best_acc = 0.0
# Pre-split test set into static (y>=3) and dynamic (y<3) subsets
test_ds = HARFeatures(root, "test")
X_te_all = test_ds.X.to(device)
y_te_all = test_ds.y.to(device)
static_mask = y_te_all >= 3
dynamic_mask = y_te_all < 3
history = {"train_loss": [], "test_loss": [],
"static_loss": [], "static_acc": [],
"dynamic_loss": [], "dynamic_acc": []}
for epoch in range(1, 21):
model.train()
train_loss = 0.0
for X, y in train_loader:
X, y = X.to(device), y.to(device)
opt.zero_grad(set_to_none=True)
loss = loss_fn(model(X), y)
loss.backward()
opt.step()
train_loss += loss.item() * len(X)
train_loss /= len(train_ds)
model.eval()
with torch.no_grad():
logits_all = model(X_te_all)
test_loss = loss_fn(logits_all, y_te_all).item()
static_loss = loss_fn(logits_all[static_mask], y_te_all[static_mask]).item()
static_acc = (logits_all[static_mask].argmax(dim=1) == y_te_all[static_mask]).float().mean().item()
dynamic_loss = loss_fn(logits_all[dynamic_mask], y_te_all[dynamic_mask]).item()
dynamic_acc = (logits_all[dynamic_mask].argmax(dim=1) == y_te_all[dynamic_mask]).float().mean().item()
history["train_loss"].append(train_loss)
history["test_loss"].append(test_loss)
history["static_loss"].append(static_loss)
history["static_acc"].append(static_acc)
history["dynamic_loss"].append(dynamic_loss)
history["dynamic_acc"].append(dynamic_acc)
test_acc = (logits_all.argmax(dim=1) == y_te_all).float().mean().item()
if test_acc > best_acc:
best_acc = test_acc
torch.save(model.state_dict(), "har_mlp_fp32.pt")
print(f"epoch={epoch:02d} train={train_loss:.4f} test={test_loss:.4f}"
f" static_acc={static_acc:.4f} dynamic_acc={dynamic_acc:.4f} best={best_acc:.4f}")
print("saved -> har_mlp_fp32.pt")
ep = range(1, len(history["train_loss"]) + 1)
fig, axes = plt.subplots(2, 2, figsize=(10, 8))
fig.suptitle("SmallMLP Training")
axes[0, 0].plot(ep, history["static_loss"], label="test (static)")
axes[0, 0].plot(ep, history["train_loss"], label="train (all)", linestyle="--", alpha=0.5)
axes[0, 0].set_title("Static — loss")
axes[0, 0].set_xlabel("epoch")
axes[0, 0].legend()
axes[1, 0].plot(ep, history["static_acc"])
axes[1, 0].set_title("Static — test acc")
axes[1, 0].set_xlabel("epoch")
axes[1, 0].set_ylim(0, 1)
axes[0, 1].plot(ep, history["dynamic_loss"], label="test (dynamic)")
axes[0, 1].plot(ep, history["train_loss"], label="train (all)", linestyle="--", alpha=0.5)
axes[0, 1].set_title("Dynamic — loss")
axes[0, 1].set_xlabel("epoch")
axes[0, 1].legend()
axes[1, 1].plot(ep, history["dynamic_acc"])
axes[1, 1].set_title("Dynamic — test acc")
axes[1, 1].set_xlabel("epoch")
axes[1, 1].set_ylim(0, 1)
plt.tight_layout()
plt.savefig("training_curves_mlp.png", dpi=150)
plt.show()
print("saved -> training_curves_mlp.png")
if __name__ == "__main__":
main()