313 lines
7.5 KiB
Python
313 lines
7.5 KiB
Python
# ===============================
|
|
# IMPORTS
|
|
# ===============================
|
|
import os
|
|
import json
|
|
import math
|
|
import time
|
|
import pickle
|
|
import numpy as np
|
|
import pandas as pd
|
|
|
|
import torch
|
|
import torch.nn as nn
|
|
import torch.nn.functional as F
|
|
import torch.optim as optim
|
|
|
|
from torch.utils.data import Dataset, DataLoader
|
|
from sklearn.model_selection import train_test_split
|
|
from sklearn.preprocessing import LabelEncoder
|
|
from multiprocessing import Pool, cpu_count
|
|
from functools import partial
|
|
|
|
# ===============================
|
|
# GPU SETUP
|
|
# ===============================
|
|
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
|
print(f"Using device: {device}")
|
|
|
|
if device.type == "cuda":
|
|
print("GPU:", torch.cuda.get_device_name(0))
|
|
torch.backends.cudnn.benchmark = True
|
|
|
|
# ===============================
|
|
# DATA LOADING
|
|
# ===============================
|
|
def load_kaggle_asl_data(base_path):
|
|
train_df = pd.read_csv(os.path.join(base_path, "train.csv"))
|
|
with open(os.path.join(base_path, "sign_to_prediction_index_map.json")) as f:
|
|
sign_to_idx = json.load(f)
|
|
return train_df, sign_to_idx
|
|
|
|
|
|
def extract_hand_landmarks_from_parquet(path):
|
|
df = pd.read_parquet(path)
|
|
|
|
left = df[df["type"] == "left_hand"]
|
|
right = df[df["type"] == "right_hand"]
|
|
|
|
if len(left) > 0:
|
|
hand = left
|
|
elif len(right) > 0:
|
|
hand = right
|
|
else:
|
|
return None
|
|
|
|
landmarks = []
|
|
for i in range(21):
|
|
lm = hand[hand["landmark_index"] == i]
|
|
if len(lm) == 0:
|
|
landmarks.append([0.0, 0.0, 0.0])
|
|
else:
|
|
landmarks.append([
|
|
lm["x"].mean(),
|
|
lm["y"].mean(),
|
|
lm["z"].mean()
|
|
])
|
|
|
|
return np.array(landmarks, dtype=np.float32)
|
|
|
|
|
|
def get_features(landmarks):
|
|
if landmarks is None:
|
|
return None
|
|
|
|
wrist = landmarks[0]
|
|
points = landmarks - wrist
|
|
|
|
scale = np.linalg.norm(points[9])
|
|
if scale < 1e-6:
|
|
scale = 1.0
|
|
points /= scale
|
|
|
|
mean = points.mean(axis=0)
|
|
std = points.std(axis=0) + 1e-6
|
|
points = (points - mean) / std
|
|
|
|
features = points.flatten()
|
|
|
|
tips = [4, 8, 12, 16, 20]
|
|
bases = [1, 5, 9, 13, 17]
|
|
|
|
tip_dist = []
|
|
curl = []
|
|
|
|
for b, t in zip(bases, tips):
|
|
curl.append(np.linalg.norm(points[t] - points[b]))
|
|
|
|
for i in range(len(tips) - 1):
|
|
tip_dist.append(np.linalg.norm(points[tips[i]] - points[tips[i+1]]))
|
|
|
|
return np.concatenate([features, tip_dist, curl]).astype(np.float32)
|
|
|
|
|
|
def process_row(row, base_path):
|
|
path = os.path.join(base_path, row["path"])
|
|
if not os.path.exists(path):
|
|
return None, None
|
|
|
|
try:
|
|
lm = extract_hand_landmarks_from_parquet(path)
|
|
feat = get_features(lm)
|
|
return feat, row["sign"]
|
|
except:
|
|
return None, None
|
|
|
|
|
|
# ===============================
|
|
# LOAD + PROCESS DATA
|
|
# ===============================
|
|
base_path = "asl_kaggle"
|
|
train_df, sign_to_idx = load_kaggle_asl_data(base_path)
|
|
|
|
rows = [row for _, row in train_df.iterrows()]
|
|
X, y = [], []
|
|
|
|
with Pool(cpu_count()) as pool:
|
|
func = partial(process_row, base_path=base_path)
|
|
for feat, sign in pool.map(func, rows):
|
|
if feat is not None:
|
|
X.append(feat)
|
|
y.append(sign)
|
|
|
|
X = np.array(X, dtype=np.float32)
|
|
y = np.array(y)
|
|
|
|
print("Samples:", len(X))
|
|
print("Feature dim:", X.shape[1])
|
|
|
|
# ===============================
|
|
# LABEL ENCODING
|
|
# ===============================
|
|
le = LabelEncoder()
|
|
y = le.fit_transform(y)
|
|
num_classes = len(le.classes_)
|
|
|
|
# ===============================
|
|
# SPLIT
|
|
# ===============================
|
|
X_train, X_test, y_train, y_test = train_test_split(
|
|
X, y, test_size=0.2, stratify=y, random_state=42
|
|
)
|
|
|
|
# ===============================
|
|
# DATASET
|
|
# ===============================
|
|
class ASLDataset(Dataset):
|
|
def __init__(self, X, y):
|
|
self.X = torch.tensor(X, dtype=torch.float32)
|
|
self.y = torch.tensor(y, dtype=torch.long)
|
|
|
|
def __len__(self):
|
|
return len(self.X)
|
|
|
|
def __getitem__(self, idx):
|
|
return self.X[idx], self.y[idx]
|
|
|
|
|
|
train_loader = DataLoader(
|
|
ASLDataset(X_train, y_train),
|
|
batch_size=256,
|
|
shuffle=True,
|
|
pin_memory=True
|
|
)
|
|
|
|
test_loader = DataLoader(
|
|
ASLDataset(X_test, y_test),
|
|
batch_size=256,
|
|
shuffle=False,
|
|
pin_memory=True
|
|
)
|
|
|
|
# ===============================
|
|
# MODEL (FIXED)
|
|
# ===============================
|
|
class TransformerASL(nn.Module):
|
|
def __init__(self, input_dim, num_classes):
|
|
super().__init__()
|
|
|
|
self.proj = nn.Linear(input_dim, 256)
|
|
self.norm = nn.LayerNorm(256)
|
|
|
|
encoder_layer = nn.TransformerEncoderLayer(
|
|
d_model=256,
|
|
nhead=8,
|
|
dim_feedforward=1024,
|
|
dropout=0.1,
|
|
activation="gelu",
|
|
batch_first=True,
|
|
norm_first=True
|
|
)
|
|
|
|
self.encoder = nn.TransformerEncoder(encoder_layer, num_layers=4)
|
|
|
|
self.fc1 = nn.Linear(256, 512)
|
|
self.bn1 = nn.BatchNorm1d(512)
|
|
self.drop1 = nn.Dropout(0.4)
|
|
|
|
self.fc2 = nn.Linear(512, 256)
|
|
self.bn2 = nn.BatchNorm1d(256)
|
|
self.drop2 = nn.Dropout(0.3)
|
|
|
|
self.out = nn.Linear(256, num_classes)
|
|
|
|
def forward(self, x):
|
|
x = self.proj(x)
|
|
x = self.norm(x)
|
|
|
|
x = x.unsqueeze(1) # (B, 1, 256)
|
|
x = self.encoder(x)
|
|
x = x.squeeze(1)
|
|
|
|
x = F.gelu(self.bn1(self.fc1(x)))
|
|
x = self.drop1(x)
|
|
|
|
x = F.gelu(self.bn2(self.fc2(x)))
|
|
x = self.drop2(x)
|
|
|
|
return self.out(x)
|
|
|
|
|
|
model = TransformerASL(X.shape[1], num_classes).to(device)
|
|
print("Parameters:", sum(p.numel() for p in model.parameters()))
|
|
|
|
# ===============================
|
|
# TRAINING SETUP
|
|
# ===============================
|
|
criterion = nn.CrossEntropyLoss(label_smoothing=0.1)
|
|
optimizer = optim.AdamW(model.parameters(), lr=3e-4, weight_decay=1e-4)
|
|
scheduler = optim.lr_scheduler.CosineAnnealingWarmRestarts(optimizer, 10)
|
|
|
|
# ===============================
|
|
# TRAIN / EVAL
|
|
# ===============================
|
|
def train_epoch():
|
|
model.train()
|
|
total, correct, loss_sum = 0, 0, 0
|
|
|
|
for x, y in train_loader:
|
|
x, y = x.to(device), y.to(device)
|
|
|
|
optimizer.zero_grad(set_to_none=True)
|
|
logits = model(x)
|
|
loss = criterion(logits, y)
|
|
loss.backward()
|
|
|
|
torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
|
|
optimizer.step()
|
|
|
|
loss_sum += loss.item()
|
|
correct += (logits.argmax(1) == y).sum().item()
|
|
total += y.size(0)
|
|
|
|
return loss_sum / len(train_loader), 100 * correct / total
|
|
|
|
|
|
@torch.no_grad()
|
|
def evaluate():
|
|
model.eval()
|
|
total, correct = 0, 0
|
|
|
|
for x, y in test_loader:
|
|
x, y = x.to(device), y.to(device)
|
|
logits = model(x)
|
|
correct += (logits.argmax(1) == y).sum().item()
|
|
total += y.size(0)
|
|
|
|
return 100 * correct / total
|
|
|
|
|
|
# ===============================
|
|
# TRAIN LOOP
|
|
# ===============================
|
|
best_acc = 0
|
|
patience = 15
|
|
wait = 0
|
|
epochs = 50
|
|
|
|
for epoch in range(epochs):
|
|
loss, train_acc = train_epoch()
|
|
test_acc = evaluate()
|
|
scheduler.step()
|
|
|
|
print(f"Epoch {epoch+1}/{epochs} | "
|
|
f"Loss {loss:.4f} | "
|
|
f"Train {train_acc:.2f}% | "
|
|
f"Test {test_acc:.2f}%")
|
|
|
|
if test_acc > best_acc:
|
|
best_acc = test_acc
|
|
wait = 0
|
|
torch.save({
|
|
"model": model.state_dict(),
|
|
"label_encoder": le
|
|
}, "asl_transformer_fixed.pth")
|
|
else:
|
|
wait += 1
|
|
|
|
if wait >= patience:
|
|
print("Early stopping")
|
|
break
|
|
|
|
print("Best accuracy:", best_acc)
|