-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
198 lines (172 loc) · 6.89 KB
/
main.py
File metadata and controls
198 lines (172 loc) · 6.89 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
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
"""
Action Recognition on Ho-3D with an Action Transformer
-------------------------------------------------------
This script:
1. Loads and annotates Ho-3D per-frame object poses and action labels.
2. Balances classes via oversampling.
3. Scales features and encodes labels.
4. Defines an ActionTransformer classifier (based on nn.TransformerEncoder).
5. Trains and evaluates on train/test split.
Inputs:
- `root` should point to the Ho-3D folder containing subfolders with:
• object_pose.txt
• action_class.txt
• grasp_class.txt (optional)
Outputs:
- Prints per-epoch training/validation loss & accuracy.
- Final test accuracy.
"""
import os
import glob
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import MinMaxScaler, LabelEncoder
from imblearn.over_sampling import RandomOverSampler
import torch
import torch.nn as nn
from torch.utils.data import Dataset, DataLoader
from torch.optim import Adam
# -----------------------------------------------------------------------------
# LOAD & ANNOTATE DATA
# -----------------------------------------------------------------------------
root = '/media/song/新加卷/Action_Recognition/data'
labels, values, actions = [], [], []
for tf in glob.glob(root + '/**/*.txt', recursive=True):
fname = os.path.basename(tf)
with open(tf, 'r') as f:
for line in f:
line = line.strip()
if not line:
continue
if fname == 'object_pose.txt':
values.append([float(x) for x in line.split()])
elif fname == 'action_class.txt':
# format "frame_idx:action_label"
idx, lbl = line.split(':')
actions.append(lbl)
# grasp_class.txt could be parsed similarly if needed
# Build DataFrame: each row = one frame
df = pd.DataFrame(values)
df['ActionClass'] = actions
df.columns = [f"x{i}" for i in range(df.shape[1]-1)] + ['ActionClass']
# Map labels to integers
df['ActionClass'] = df['ActionClass'].str.strip()
le = LabelEncoder()
df['y'] = le.fit_transform(df['ActionClass'])
label_map = {i: lbl for i, lbl in enumerate(le.classes_)}
print("Annotated label mapping:", label_map)
X = df.drop(['ActionClass', 'y'], axis=1).values
y = df['y'].values
# -----------------------------------------------------------------------------
# BALANCE & SCALE
# -----------------------------------------------------------------------------
ros = RandomOverSampler(random_state=42)
X, y = ros.fit_resample(X, y)
scaler = MinMaxScaler()
X = scaler.fit_transform(X)
# -----------------------------------------------------------------------------
# TRAIN/TEST SPLIT
# -----------------------------------------------------------------------------
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42, stratify=y
)
# -----------------------------------------------------------------------------
# PYTORCH DATASET & DATALOADER
# -----------------------------------------------------------------------------
class Ho3DDataset(Dataset):
def __init__(self, X, y):
self.X = torch.from_numpy(X).float()
self.y = torch.from_numpy(y).long()
def __len__(self):
return len(self.y)
def __getitem__(self, idx):
return self.X[idx], self.y[idx]
train_ds = Ho3DDataset(X_train, y_train)
test_ds = Ho3DDataset(X_test, y_test)
train_loader = DataLoader(train_ds, batch_size=64, shuffle=True, num_workers=2)
test_loader = DataLoader(test_ds, batch_size=64, shuffle=False, num_workers=2)
# -----------------------------------------------------------------------------
# ACTION TRANSFORMER MODEL
# -----------------------------------------------------------------------------
class ActionTransformer(nn.Module):
def __init__(self, feature_dim, d_model=128, nhead=4, num_layers=2, num_classes=10):
super().__init__()
# project input features to d_model
self.input_proj = nn.Linear(feature_dim, d_model)
# positional embeddings for a single token
self.pos_emb = nn.Parameter(torch.zeros(1, 1, d_model))
encoder_layer = nn.TransformerEncoderLayer(
d_model=d_model, nhead=nhead, dim_feedforward=256, dropout=0.1
)
self.transformer = nn.TransformerEncoder(encoder_layer, num_layers=num_layers)
self.classifier = nn.Sequential(
nn.LayerNorm(d_model),
nn.Linear(d_model, num_classes)
)
def forward(self, x):
# x: (B, F) -> (B, 1, d_model)
x = self.input_proj(x).unsqueeze(1) + self.pos_emb
# transformer expects (S, B, E)
x = self.transformer(x.permute(1,0,2)) # -> (1, B, d_model)
x = x.squeeze(0) # -> (B, d_model)
return self.classifier(x)
# instantiate
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
model = ActionTransformer(
feature_dim=X_train.shape[1],
d_model=128,
nhead=4,
num_layers=2,
num_classes=len(label_map)
).to(device)
# -----------------------------------------------------------------------------
# TRAINING LOOP
# -----------------------------------------------------------------------------
criterion = nn.CrossEntropyLoss()
optimizer = Adam(model.parameters(), lr=1e-3)
num_epochs = 20
for epoch in range(1, num_epochs+1):
model.train()
running_loss, correct, total = 0, 0, 0
for xb, yb in train_loader:
xb, yb = xb.to(device), yb.to(device)
pred = model(xb)
loss = criterion(pred, yb)
optimizer.zero_grad(); loss.backward(); optimizer.step()
running_loss += loss.item()*xb.size(0)
_, preds = pred.max(1)
correct += (preds==yb).sum().item()
total += yb.size(0)
train_loss = running_loss/total
train_acc = correct/total
# validation
model.eval()
val_loss, val_corr, val_tot = 0, 0, 0
with torch.no_grad():
for xb, yb in test_loader:
xb, yb = xb.to(device), yb.to(device)
pred = model(xb)
l = criterion(pred, yb)
val_loss += l.item()*xb.size(0)
_, preds = pred.max(1)
val_corr += (preds==yb).sum().item()
val_tot += yb.size(0)
val_loss /= val_tot
val_acc = val_corr/val_tot
print(f"Epoch {epoch:02d} | "
f"Train Loss: {train_loss:.4f}, Acc: {train_acc:.3f} | "
f"Val Loss: {val_loss:.4f}, Acc: {val_acc:.3f}")
# -----------------------------------------------------------------------------
# FINAL TEST METRICS
# -----------------------------------------------------------------------------
model.eval()
test_corr, test_tot = 0, 0
with torch.no_grad():
for xb, yb in test_loader:
xb, yb = xb.to(device), yb.to(device)
pred = model(xb)
_, preds = pred.max(1)
test_corr += (preds==yb).sum().item()
test_tot += yb.size(0)
print(f"\nFinal Test Accuracy: {test_corr/test_tot:.3f}")