Upload full project with correct structure
Browse files- weights.py +60 -0
weights.py
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
from collections import defaultdict
|
| 3 |
+
import numpy as np
|
| 4 |
+
|
| 5 |
+
TRAIN_JSON_PATH = "./data/miko/train.json"
|
| 6 |
+
ACTION_STATS_PATH = "./data/action_statistics.json"
|
| 7 |
+
|
| 8 |
+
# Constants to stabilize training
|
| 9 |
+
MIN_TOTAL_LEN = 1.0 # Minimum allowed total duration
|
| 10 |
+
MAX_WEIGHT = 0.05 # Cap to prevent a single label from dominating
|
| 11 |
+
|
| 12 |
+
# Load train.json
|
| 13 |
+
with open(TRAIN_JSON_PATH, "r") as f:
|
| 14 |
+
dataset = json.load(f)
|
| 15 |
+
|
| 16 |
+
# Collect durations for each act_cat
|
| 17 |
+
act_cat_stats = defaultdict(float)
|
| 18 |
+
|
| 19 |
+
for entry in dataset:
|
| 20 |
+
labels = entry.get("frame_ann", {}).get("labels", [])
|
| 21 |
+
for label in labels:
|
| 22 |
+
start = label.get("start_t")
|
| 23 |
+
end = label.get("end_t")
|
| 24 |
+
act_cats = label.get("act_cat", [])
|
| 25 |
+
if start is None or end is None:
|
| 26 |
+
continue
|
| 27 |
+
duration = max(0.01, end - start)
|
| 28 |
+
for act in act_cats:
|
| 29 |
+
act_cat_stats[act] += duration
|
| 30 |
+
|
| 31 |
+
# Recompute weights
|
| 32 |
+
cleaned_stats = {}
|
| 33 |
+
for act, total_len in act_cat_stats.items():
|
| 34 |
+
total_len = max(MIN_TOTAL_LEN, total_len)
|
| 35 |
+
if np.isfinite(total_len):
|
| 36 |
+
raw_weight = 1.0 / total_len
|
| 37 |
+
weight = min(raw_weight, MAX_WEIGHT)
|
| 38 |
+
weight = max(0.0, weight) # ✅ Clip negatives to 0
|
| 39 |
+
cleaned_stats[act] = {
|
| 40 |
+
"total_len": total_len,
|
| 41 |
+
"total_weight": 1,
|
| 42 |
+
"weight": weight
|
| 43 |
+
}
|
| 44 |
+
else:
|
| 45 |
+
print(f"⚠️ Skipping act_cat '{act}' due to invalid total_len={total_len}")
|
| 46 |
+
|
| 47 |
+
# Normalize weights
|
| 48 |
+
total_weight_sum = sum(stats["weight"] for stats in cleaned_stats.values())
|
| 49 |
+
if total_weight_sum == 0:
|
| 50 |
+
raise ValueError("❌ All weights are zero. Check act_cat labels or durations.")
|
| 51 |
+
|
| 52 |
+
for stats in cleaned_stats.values():
|
| 53 |
+
stats["weight"] /= total_weight_sum
|
| 54 |
+
|
| 55 |
+
# Save updated statistics
|
| 56 |
+
with open(ACTION_STATS_PATH, "w") as f:
|
| 57 |
+
json.dump(cleaned_stats, f, indent=2)
|
| 58 |
+
|
| 59 |
+
print(f"✅ Saved {len(cleaned_stats)} act_cat entries to {ACTION_STATS_PATH}")
|
| 60 |
+
print(f"🎯 Final normalized weight sum: {sum(stats['weight'] for stats in cleaned_stats.values()):.4f}")
|