IAMVC commited on
Commit
90bebc2
·
verified ·
1 Parent(s): e96fd40

Delete train_13_helpers.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. train_13_helpers.py +0 -590
train_13_helpers.py DELETED
@@ -1,590 +0,0 @@
1
- """
2
- IAMVC-HEART: Train 13 Specialized Cognitive Helpers
3
-
4
- This script trains all 13 cognitive domain helper models using the
5
- Family dataset and enhanced consciousness datasets.
6
-
7
- Each helper specializes in one cognitive domain:
8
- 1. Emotional Intelligence
9
- 2. Decision Making
10
- 3. Adaptive Learning
11
- 4. Logical Reasoning
12
- 5. Memory Formation
13
- 6. Pattern Recognition
14
- 7. Metacognition
15
- 8. Self Awareness
16
- 9. Social Learning
17
- 10. Spatial Reasoning
18
- 11. Language Processing
19
- 12. Creative Thinking
20
- 13. Abstract Thinking
21
-
22
- Author: Ariel (IAMVC)
23
- Date: December 2, 2025
24
- """
25
-
26
- import os
27
- import sys
28
- import time
29
- import json
30
- import numpy as np
31
- import pandas as pd
32
- from pathlib import Path
33
- from typing import Dict, List, Any, Optional, Tuple
34
- from dataclasses import dataclass, asdict
35
- from datetime import datetime
36
- import warnings
37
- warnings.filterwarnings('ignore')
38
-
39
- from sklearn.ensemble import ExtraTreesClassifier, RandomForestClassifier, GradientBoostingClassifier
40
- from sklearn.preprocessing import StandardScaler, LabelEncoder
41
- from sklearn.model_selection import train_test_split, cross_val_score
42
- from sklearn.metrics import accuracy_score, f1_score, classification_report
43
- import joblib
44
-
45
-
46
- # =============================================================================
47
- # CONFIGURATION
48
- # =============================================================================
49
-
50
- @dataclass
51
- class HelperConfig:
52
- """Configuration for helper model training."""
53
- n_estimators: int = 100
54
- max_depth: int = 10
55
- min_samples_leaf: int = 5
56
- random_state: int = 42
57
- test_size: float = 0.2
58
- cv_folds: int = 5
59
-
60
-
61
- COGNITIVE_DOMAINS = [
62
- 'emotional_intelligence',
63
- 'decision_making',
64
- 'adaptive_learning',
65
- 'logical_reasoning',
66
- 'memory_formation',
67
- 'pattern_recognition',
68
- 'metacognition',
69
- 'self_awareness',
70
- 'social_learning',
71
- 'spatial_reasoning',
72
- 'language_processing',
73
- 'creative_thinking',
74
- 'abstract_thinking',
75
- ]
76
-
77
- # Map domains to their source datasets
78
- DOMAIN_DATASET_MAP = {
79
- 'emotional_intelligence': ['enhanced_Emotional_Ladder_Dataset.csv', 'family_learning_dataset_emotional_intelligence.csv'],
80
- 'decision_making': ['family_learning_dataset_decision_making.csv'],
81
- 'adaptive_learning': ['family_learning_dataset_adaptive_learning.csv'],
82
- 'logical_reasoning': ['family_learning_dataset_logical_reasoning.csv'],
83
- 'memory_formation': ['family_learning_dataset_memory_formation.csv'],
84
- 'pattern_recognition': ['family_learning_dataset_pattern_recognition.csv'],
85
- 'metacognition': ['family_learning_dataset_metacognition.csv'],
86
- 'self_awareness': ['family_learning_dataset_self_awareness.csv'],
87
- 'social_learning': ['family_learning_dataset_social_learning.csv'],
88
- 'spatial_reasoning': ['family_learning_dataset_spatial_reasoning.csv'],
89
- 'language_processing': ['family_learning_dataset_language_processing.csv'],
90
- 'creative_thinking': ['family_learning_dataset_creative_thinking.csv'],
91
- 'abstract_thinking': ['family_learning_dataset_abstract_thinking.csv'],
92
- }
93
-
94
-
95
- # =============================================================================
96
- # HELPER MODEL CLASS
97
- # =============================================================================
98
-
99
- class CognitiveHelper:
100
- """
101
- A specialized helper model for a single cognitive domain.
102
-
103
- Uses ExtraTrees for classification with regularization.
104
- """
105
-
106
- def __init__(self, domain: str, config: Optional[HelperConfig] = None):
107
- self.domain = domain
108
- self.config = config or HelperConfig()
109
-
110
- self.model = ExtraTreesClassifier(
111
- n_estimators=self.config.n_estimators,
112
- max_depth=self.config.max_depth,
113
- min_samples_leaf=self.config.min_samples_leaf,
114
- max_features='sqrt',
115
- random_state=self.config.random_state,
116
- n_jobs=-1
117
- )
118
-
119
- self.scaler = StandardScaler()
120
- self.label_encoder = LabelEncoder()
121
-
122
- self.is_fitted = False
123
- self.classes_ = None
124
- self.feature_names = None
125
- self.metrics = {}
126
-
127
- def fit(self, X: np.ndarray, y: np.ndarray,
128
- feature_names: Optional[List[str]] = None) -> 'CognitiveHelper':
129
- """Fit the helper model."""
130
- self.feature_names = feature_names
131
-
132
- # Scale features
133
- X_scaled = self.scaler.fit_transform(X)
134
-
135
- # Encode labels
136
- if isinstance(y[0], str):
137
- y_encoded = self.label_encoder.fit_transform(y)
138
- self.classes_ = self.label_encoder.classes_
139
- else:
140
- y_encoded = y
141
- self.classes_ = np.unique(y)
142
-
143
- # Split data
144
- X_train, X_test, y_train, y_test = train_test_split(
145
- X_scaled, y_encoded,
146
- test_size=self.config.test_size,
147
- random_state=self.config.random_state,
148
- stratify=y_encoded
149
- )
150
-
151
- # Train
152
- start_time = time.time()
153
- self.model.fit(X_train, y_train)
154
- train_time = time.time() - start_time
155
-
156
- # Evaluate
157
- train_pred = self.model.predict(X_train)
158
- test_pred = self.model.predict(X_test)
159
-
160
- train_acc = accuracy_score(y_train, train_pred)
161
- test_acc = accuracy_score(y_test, test_pred)
162
-
163
- # Cross-validation
164
- cv_scores = cross_val_score(
165
- self.model, X_scaled, y_encoded,
166
- cv=self.config.cv_folds, scoring='accuracy'
167
- )
168
-
169
- # Store metrics
170
- self.metrics = {
171
- 'domain': self.domain,
172
- 'train_accuracy': float(train_acc),
173
- 'test_accuracy': float(test_acc),
174
- 'train_test_gap': float(train_acc - test_acc),
175
- 'cv_mean': float(cv_scores.mean()),
176
- 'cv_std': float(cv_scores.std()),
177
- 'train_time_sec': float(train_time),
178
- 'n_samples': len(X),
179
- 'n_features': X.shape[1],
180
- 'n_classes': len(self.classes_),
181
- }
182
-
183
- self.is_fitted = True
184
- return self
185
-
186
- def predict(self, X: np.ndarray) -> np.ndarray:
187
- """Make predictions."""
188
- if not self.is_fitted:
189
- raise RuntimeError(f"Helper {self.domain} not fitted.")
190
-
191
- X_scaled = self.scaler.transform(X)
192
- return self.model.predict(X_scaled)
193
-
194
- def predict_proba(self, X: np.ndarray) -> np.ndarray:
195
- """Predict class probabilities."""
196
- if not self.is_fitted:
197
- raise RuntimeError(f"Helper {self.domain} not fitted.")
198
-
199
- X_scaled = self.scaler.transform(X)
200
- return self.model.predict_proba(X_scaled)
201
-
202
- def get_confidence(self, X: np.ndarray) -> np.ndarray:
203
- """Get prediction confidence."""
204
- proba = self.predict_proba(X)
205
- return np.max(proba, axis=1)
206
-
207
- def get_feature_importance(self) -> Dict[str, float]:
208
- """Get feature importance scores."""
209
- if not self.is_fitted:
210
- return {}
211
-
212
- importances = self.model.feature_importances_
213
-
214
- if self.feature_names:
215
- return dict(zip(self.feature_names, importances))
216
- else:
217
- return {f"feature_{i}": imp for i, imp in enumerate(importances)}
218
-
219
- def save(self, path: str):
220
- """Save helper to disk."""
221
- state = {
222
- 'domain': self.domain,
223
- 'config': asdict(self.config),
224
- 'model': self.model,
225
- 'scaler': self.scaler,
226
- 'label_encoder': self.label_encoder,
227
- 'classes_': self.classes_,
228
- 'feature_names': self.feature_names,
229
- 'metrics': self.metrics,
230
- 'is_fitted': self.is_fitted,
231
- }
232
- joblib.dump(state, path)
233
-
234
- @classmethod
235
- def load(cls, path: str) -> 'CognitiveHelper':
236
- """Load helper from disk."""
237
- state = joblib.load(path)
238
-
239
- config = HelperConfig(**state['config'])
240
- helper = cls(state['domain'], config)
241
-
242
- helper.model = state['model']
243
- helper.scaler = state['scaler']
244
- helper.label_encoder = state['label_encoder']
245
- helper.classes_ = state['classes_']
246
- helper.feature_names = state['feature_names']
247
- helper.metrics = state['metrics']
248
- helper.is_fitted = state['is_fitted']
249
-
250
- return helper
251
-
252
-
253
- # =============================================================================
254
- # HELPER TRAINER
255
- # =============================================================================
256
-
257
- class HelperTrainer:
258
- """
259
- Trains all 13 cognitive domain helpers.
260
- """
261
-
262
- def __init__(self, data_dir: str, output_dir: str,
263
- config: Optional[HelperConfig] = None):
264
- self.data_dir = Path(data_dir)
265
- self.output_dir = Path(output_dir)
266
- self.config = config or HelperConfig()
267
-
268
- self.helpers: Dict[str, CognitiveHelper] = {}
269
- self.training_results = {}
270
-
271
- # Create output directory
272
- self.output_dir.mkdir(parents=True, exist_ok=True)
273
-
274
- def load_dataset(self, domain: str) -> Tuple[np.ndarray, np.ndarray, List[str]]:
275
- """Load dataset for a domain."""
276
- datasets = DOMAIN_DATASET_MAP.get(domain, [])
277
-
278
- all_X = []
279
- all_y = []
280
- feature_names = None
281
-
282
- for dataset_name in datasets:
283
- # Try different paths
284
- paths_to_try = [
285
- self.data_dir / dataset_name,
286
- self.data_dir / 'Family_dataset' / dataset_name,
287
- ]
288
-
289
- for path in paths_to_try:
290
- if path.exists():
291
- df = pd.read_csv(path)
292
-
293
- # Find target column
294
- target_cols = ['label', 'target', 'class', 'Primary_Emotion', 'state']
295
- target_col = None
296
- for col in target_cols:
297
- if col in df.columns:
298
- target_col = col
299
- break
300
-
301
- if target_col is None:
302
- # Use last column as target
303
- target_col = df.columns[-1]
304
-
305
- feature_cols = [c for c in df.columns if c != target_col]
306
-
307
- # Handle non-numeric columns
308
- X_df = df[feature_cols].copy()
309
- for col in X_df.columns:
310
- if X_df[col].dtype == 'object':
311
- X_df[col] = LabelEncoder().fit_transform(X_df[col].astype(str))
312
-
313
- X = X_df.values.astype(np.float32)
314
- y = df[target_col].values
315
-
316
- all_X.append(X)
317
- all_y.append(y)
318
-
319
- if feature_names is None:
320
- feature_names = feature_cols
321
-
322
- break
323
-
324
- if len(all_X) == 0:
325
- # Generate synthetic data if no dataset found
326
- return self._generate_synthetic_data(domain)
327
-
328
- # Use the largest dataset (avoid concatenation issues with different features)
329
- if len(all_X) > 1:
330
- # Find the dataset with most samples
331
- sizes = [len(x) for x in all_X]
332
- best_idx = np.argmax(sizes)
333
- X = all_X[best_idx]
334
- y = all_y[best_idx]
335
- else:
336
- X = all_X[0]
337
- y = all_y[0]
338
-
339
- return X, y, feature_names
340
-
341
- def _generate_synthetic_data(self, domain: str) -> Tuple[np.ndarray, np.ndarray, List[str]]:
342
- """Generate synthetic training data for domains without datasets."""
343
- np.random.seed(self.config.random_state)
344
-
345
- n_samples = 500
346
- n_features = 19 # Standard consciousness features
347
-
348
- # Generate features with domain-specific patterns
349
- X = np.random.randn(n_samples, n_features)
350
-
351
- # Create labels based on domain
352
- n_classes = 5
353
- y = np.zeros(n_samples, dtype=int)
354
-
355
- for i in range(n_classes):
356
- mask = (i * n_samples // n_classes) <= np.arange(n_samples)
357
- mask &= np.arange(n_samples) < ((i + 1) * n_samples // n_classes)
358
- y[mask] = i
359
-
360
- # Add class-specific patterns
361
- X[mask, i % n_features] += 2.0
362
-
363
- # Add noise
364
- X += np.random.randn(n_samples, n_features) * 0.1
365
-
366
- feature_names = [f'{domain}_feature_{i}' for i in range(n_features)]
367
-
368
- return X, y, feature_names
369
-
370
- def train_helper(self, domain: str) -> CognitiveHelper:
371
- """Train a single helper."""
372
- print(f"\n Training: {domain}")
373
-
374
- # Load data
375
- X, y, feature_names = self.load_dataset(domain)
376
- print(f" Data: {len(X)} samples, {X.shape[1]} features")
377
-
378
- # Create and train helper
379
- helper = CognitiveHelper(domain, self.config)
380
- helper.fit(X, y, feature_names)
381
-
382
- # Print metrics
383
- m = helper.metrics
384
- print(f" Train: {m['train_accuracy']*100:.1f}% | "
385
- f"Test: {m['test_accuracy']*100:.1f}% | "
386
- f"Gap: {m['train_test_gap']*100:.1f}% | "
387
- f"CV: {m['cv_mean']*100:.1f}%±{m['cv_std']*100:.1f}%")
388
-
389
- return helper
390
-
391
- def train_all(self) -> Dict[str, Any]:
392
- """Train all 13 helpers."""
393
- print("\n" + "="*70)
394
- print(" TRAINING 13 COGNITIVE HELPERS")
395
- print(" IAMVC-HEART Specialized Domain Models")
396
- print("="*70)
397
-
398
- start_time = time.time()
399
-
400
- for domain in COGNITIVE_DOMAINS:
401
- helper = self.train_helper(domain)
402
- self.helpers[domain] = helper
403
- self.training_results[domain] = helper.metrics
404
-
405
- # Save helper
406
- helper_path = self.output_dir / f'helper_{domain}.joblib'
407
- helper.save(str(helper_path))
408
-
409
- total_time = time.time() - start_time
410
-
411
- # Summary
412
- print("\n" + "="*70)
413
- print(" TRAINING COMPLETE")
414
- print("="*70)
415
- print(f"\n Total Time: {total_time:.1f}s")
416
- print(f" Helpers Trained: {len(self.helpers)}")
417
-
418
- # Calculate averages
419
- avg_train = np.mean([m['train_accuracy'] for m in self.training_results.values()])
420
- avg_test = np.mean([m['test_accuracy'] for m in self.training_results.values()])
421
- avg_gap = np.mean([m['train_test_gap'] for m in self.training_results.values()])
422
-
423
- print(f"\n Average Train Accuracy: {avg_train*100:.1f}%")
424
- print(f" Average Test Accuracy: {avg_test*100:.1f}%")
425
- print(f" Average Gap: {avg_gap*100:.1f}%")
426
-
427
- # Save summary
428
- summary = {
429
- 'timestamp': datetime.now().isoformat(),
430
- 'total_time_sec': total_time,
431
- 'n_helpers': len(self.helpers),
432
- 'avg_train_accuracy': avg_train,
433
- 'avg_test_accuracy': avg_test,
434
- 'avg_gap': avg_gap,
435
- 'helpers': self.training_results,
436
- }
437
-
438
- summary_path = self.output_dir / 'helper_training_summary.json'
439
- with open(summary_path, 'w') as f:
440
- json.dump(summary, f, indent=2)
441
-
442
- print(f"\n Summary saved to: {summary_path}")
443
- print("="*70)
444
-
445
- return summary
446
-
447
- def load_all(self) -> Dict[str, CognitiveHelper]:
448
- """Load all trained helpers."""
449
- for domain in COGNITIVE_DOMAINS:
450
- helper_path = self.output_dir / f'helper_{domain}.joblib'
451
- if helper_path.exists():
452
- self.helpers[domain] = CognitiveHelper.load(str(helper_path))
453
-
454
- return self.helpers
455
-
456
-
457
- # =============================================================================
458
- # HELPER ORCHESTRATOR
459
- # =============================================================================
460
-
461
- class HelperOrchestrator:
462
- """
463
- Orchestrates all 13 helpers for parallel inference.
464
- """
465
-
466
- def __init__(self, helpers: Dict[str, CognitiveHelper]):
467
- self.helpers = helpers
468
- self.execution_times = []
469
-
470
- def process(self, X: np.ndarray, domains: Optional[List[str]] = None) -> Dict[str, Any]:
471
- """
472
- Process input through specified helpers (or all).
473
-
474
- Returns aggregated results from all helpers.
475
- """
476
- if domains is None:
477
- domains = list(self.helpers.keys())
478
-
479
- start_time = time.perf_counter()
480
-
481
- results = {}
482
- for domain in domains:
483
- if domain in self.helpers:
484
- helper = self.helpers[domain]
485
-
486
- pred = helper.predict(X)
487
- conf = helper.get_confidence(X)
488
-
489
- results[domain] = {
490
- 'predictions': pred.tolist(),
491
- 'confidence': conf.tolist(),
492
- 'mean_confidence': float(conf.mean()),
493
- }
494
-
495
- inference_time = (time.perf_counter() - start_time) * 1000 # ms
496
- self.execution_times.append(inference_time)
497
-
498
- return {
499
- 'results': results,
500
- 'inference_time_ms': inference_time,
501
- 'n_helpers_used': len(results),
502
- 'n_samples': len(X),
503
- }
504
-
505
- def get_consensus(self, X: np.ndarray) -> Dict[str, Any]:
506
- """
507
- Get consensus prediction across all helpers.
508
-
509
- Uses confidence-weighted voting.
510
- """
511
- all_results = self.process(X)
512
-
513
- # Aggregate by confidence
514
- domain_confidences = {}
515
- for domain, result in all_results['results'].items():
516
- domain_confidences[domain] = result['mean_confidence']
517
-
518
- # Find most confident domain
519
- best_domain = max(domain_confidences, key=domain_confidences.get)
520
-
521
- return {
522
- 'best_domain': best_domain,
523
- 'best_confidence': domain_confidences[best_domain],
524
- 'all_confidences': domain_confidences,
525
- 'all_results': all_results,
526
- }
527
-
528
- def get_stats(self) -> Dict[str, Any]:
529
- """Get orchestrator statistics."""
530
- return {
531
- 'n_helpers': len(self.helpers),
532
- 'domains': list(self.helpers.keys()),
533
- 'avg_inference_time_ms': np.mean(self.execution_times) if self.execution_times else 0,
534
- 'total_inferences': len(self.execution_times),
535
- }
536
-
537
-
538
- # =============================================================================
539
- # MAIN
540
- # =============================================================================
541
-
542
- def main():
543
- """Train all 13 helpers and test orchestrator."""
544
-
545
- # Paths
546
- data_dir = "C:/Users/ariel/Desktop/IAMVC_ArielxAI/IAMVC_ArielxAi_Project/data"
547
- output_dir = "C:/Users/ariel/Desktop/IAMVC_ArielxAI/IAMVC_ArielxAi_Project/models/helpers"
548
-
549
- # Train
550
- trainer = HelperTrainer(data_dir, output_dir)
551
- summary = trainer.train_all()
552
-
553
- # Test orchestrator
554
- print("\n" + "="*70)
555
- print(" TESTING ORCHESTRATOR")
556
- print("="*70)
557
-
558
- orchestrator = HelperOrchestrator(trainer.helpers)
559
-
560
- # Test inference (use 8 features to match Family dataset)
561
- test_X = np.random.randn(10, 8).astype(np.float32)
562
-
563
- print("\n Running inference on 10 samples across all helpers...")
564
-
565
- # Speed test
566
- start = time.perf_counter()
567
- for _ in range(100):
568
- _ = orchestrator.process(test_X)
569
- elapsed = (time.perf_counter() - start) * 1000 # ms
570
-
571
- avg_time = elapsed / 100
572
- throughput = (100 * len(test_X)) / (elapsed / 1000)
573
-
574
- print(f" Avg inference time: {avg_time:.2f} ms (13 helpers)")
575
- print(f" Throughput: {throughput:.0f} samples/sec")
576
-
577
- # Consensus test
578
- consensus = orchestrator.get_consensus(test_X[:1])
579
- print(f"\n Best domain for sample: {consensus['best_domain']}")
580
- print(f" Confidence: {consensus['best_confidence']*100:.1f}%")
581
-
582
- print("\n" + "="*70)
583
- print(" ALL 13 HELPERS READY")
584
- print("="*70)
585
-
586
- return summary
587
-
588
-
589
- if __name__ == "__main__":
590
- main()