-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrecommendation_system.py
2010 lines (1664 loc) · 74.5 KB
/
recommendation_system.py
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
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Recommendation System I engineered for a high-traffic AI Platform
## All proprietary language and specific details have been modified.
"""
Hybrid AI Recommendation System
--------------------------------
A versatile and production-ready content recommendation system combining deep learning techniques,
caching mechanisms, and performance optimizations.
Key Features:
1. Advanced Neural Architecture:
- Multi-head attention with residual connections
- Temporal weighting for recency bias
- Hyperparameter tuning using Optuna
- Gradient clipping and learning rate scheduling
2. Production-Grade Optimization:
- Distributed caching with Redis fallback
- Connection pooling and database query optimization
- Automated health monitoring with error recovery
- Detailed logging, metrics, and Prometheus integration
3. Robust Recommendation Logic:
- Cold-start problem handling with diversity enhancements
- A/B testing framework for continuous evaluation
- Real-time trend analysis and caching
- Automatic model versioning and rollback capabilities
Technical Requirements:
- Python 3.8+
- CUDA-compatible GPU (recommended for training)
- 8GB+ RAM
- PostgreSQL 12+
- Redis 6+ (optional, falls back to in-memory cache)
Installation:
pip install -r requirements.txt
# Required packages:
torch>=1.9.0
numpy>=1.19.2
pandas>=1.2.0
redis>=4.0.0
sqlalchemy>=1.4.0
prometheus_client>=0.12.0
optuna>=2.10.0
psutil>=5.8.0
Configuration:
1. Database Setup:
- Configure PostgreSQL connection in config.py
- Run database migrations: `python migrations.py`
2. Model Settings:
- Adjust hyperparameters in config.py
- Default batch size: 64
- Learning rate: 0.001
- Hidden layers: [512, 256, 128]
3. Cache Configuration:
- Redis host/port in config.py
- TTL settings for different cache types
- Memory cache fallback options
Performance Characteristics:
- Inference latency: ~50ms per request
- Throughput: 200+ requests/second
- Cache hit ratio: >90% in production
- Model training time: ~2 hours on GPU
- Memory usage: 2-4GB in production
- Cold start latency: <100ms
Usage Example:
from ai_recommender import ContentRecommender
recommender = ContentRecommender()
# Fetch recommendations
recommendations = recommender.get_recommendations(
user_id=123,
limit=10,
diversity_weight=0.3
)
Author: Vanessa
"""
# Standard library imports
import os
import sys
import time
import json
import pickle
import signal
import logging
import logging.config
import threading
import traceback
from typing import List, Dict, Tuple, Optional, Any, Union, Iterator
from datetime import datetime, timedelta
from pathlib import Path
from collections import defaultdict, deque
from functools import wraps, lru_cache
from dataclasses import dataclass
from enum import Enum
# Third-party machine learning imports
import numpy as np
import pandas as pd
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import ndcg_score, precision_score, roc_auc_score
from sklearn.metrics.pairwise import cosine_similarity
from sklearn.model_selection import train_test_split
# Database and caching
import redis
import psutil
from sqlalchemy import create_engine, text
# Deep learning and optimization
import optuna
from transformers import AutoTokenizer, AutoModel
# Monitoring and metrics
from prometheus_client import Counter, Gauge, Histogram, CollectorRegistry
from prometheus_client import start_http_server as start_metrics_server
# Data processing
import dask.dataframe as dd
import yaml
# Local imports
from config import DATABASE_CONFIG, MODEL_CONFIG, LOGGING_CONFIG, RATE_LIMIT_CONFIG
# Initialize logging
logging.config.dictConfig(LOGGING_CONFIG)
logger = logging.getLogger(__name__)
# Create a custom registry instead of using the default one
REGISTRY = CollectorRegistry()
# Define metrics with the custom registry
REQUESTS = Counter('content_recommender_requests_total',
'Total recommendation requests',
registry=REGISTRY)
ERRORS = Counter('content_recommender_errors_total',
'Total errors',
registry=REGISTRY)
RESPONSE_TIME = Histogram('content_recommender_response_seconds',
'Response time in seconds',
registry=REGISTRY)
CACHE_SIZE = Gauge('content_recommender_cache_size',
'Current cache size',
registry=REGISTRY)
PREDICTION_LATENCY = Histogram('content_recommender_prediction_latency_seconds',
'Prediction latency in seconds',
buckets=(0.1, 0.5, 1, 2, 5),
registry=REGISTRY)
FEATURE_DIMS = Gauge('content_recommender_feature_dimensions',
'Number of feature dimensions',
registry=REGISTRY)
MODEL_VERSION = Gauge('content_recommender_model_version',
'Current model version',
registry=REGISTRY)
class RecommenderError(Exception):
"""Base exception for recommender system"""
pass
class DatabaseError(RecommenderError):
"""Exception for database-related errors"""
pass
@dataclass
class RecommendationResult:
"""Data class for recommendation results"""
content_id: int
title: str
score: float
confidence: float
source: str
metadata: Dict[str, Any]
def __post_init__(self):
"""Validate types after initialization"""
if not isinstance(self.content_id, int):
raise TypeError("content_id must be an integer")
if not isinstance(self.score, float):
self.score = float(self.score)
if not isinstance(self.confidence, float):
self.confidence = float(self.confidence)
class ModelState(Enum):
"""Model states"""
UNTRAINED = 'untrained'
TRAINING = 'training'
READY = 'ready'
ERROR = 'error'
class MultiHeadAttention(nn.Module):
"""Multi-head attention layer with residual connections"""
def __init__(self, embed_dim: int, num_heads: int = 4):
super().__init__()
# Ensure embed_dim is divisible by num_heads
if embed_dim % num_heads != 0:
# Round up to nearest multiple of num_heads
embed_dim = ((embed_dim + num_heads - 1) // num_heads) * num_heads
self.attention = nn.MultiheadAttention(
embed_dim=embed_dim,
num_heads=num_heads,
batch_first=False # Keep sequence first for compatibility
)
self.norm = nn.LayerNorm(embed_dim)
self.dropout = nn.Dropout(0.1)
def forward(self, x):
"""Forward pass with error handling"""
try:
attended, _ = self.attention(x, x, x)
attended = self.dropout(attended)
return self.norm(x + attended)
except Exception as e:
logger.error(f"Error in attention forward pass: {e}")
raise RecommenderError("Attention layer failed") from e
class RecommenderNN(nn.Module):
"""Neural network for character recommendations"""
def __init__(self, input_size: int, hidden_sizes: List[int]):
super().__init__()
self.input_size = input_size
self.hidden_sizes = hidden_sizes
# Input projection with dropout
self.input_proj = nn.Sequential(
nn.Linear(input_size, hidden_sizes[0]),
nn.ReLU(),
nn.LayerNorm(hidden_sizes[0]),
nn.Dropout(0.5)
)
# Hidden layers with residual connections
self.hidden_layers = nn.ModuleList()
for i in range(len(hidden_sizes) - 1):
layer = nn.Sequential(
nn.Linear(hidden_sizes[i], hidden_sizes[i + 1]),
nn.ReLU(),
nn.LayerNorm(hidden_sizes[i + 1]),
nn.Dropout(0.3)
)
self.hidden_layers.append(layer)
# Output layer
self.output = nn.Sequential(
nn.Linear(hidden_sizes[-1], 1),
nn.Sigmoid()
)
# Initialize weights
self.apply(self._init_weights)
def _init_weights(self, module):
"""Initialize network weights"""
if isinstance(module, nn.Linear):
nn.init.kaiming_normal_(module.weight, mode='fan_in', nonlinearity='relu')
if module.bias is not None:
nn.init.constant_(module.bias, 0)
def forward(self, x: torch.Tensor) -> torch.Tensor:
"""Forward pass through the network
Args:
x: Input tensor of shape (batch_size, input_size)
Returns:
Output tensor of shape (batch_size, 1)
"""
# Input projection
x = self.input_proj(x)
# Hidden layers with residual connections
for layer in self.hidden_layers:
residual = x
x = layer(x)
# Add residual if shapes match
if x.shape == residual.shape:
x = x + residual
# Output layer
x = self.output(x)
return x
def predict(self, x: torch.Tensor) -> torch.Tensor:
"""Make predictions with the model
Args:
x: Input tensor of shape (batch_size, input_size)
Returns:
Predictions tensor of shape (batch_size,)
"""
self.eval() # Set to evaluation mode
with torch.no_grad():
return self.forward(x).squeeze()
class MultiHeadAttention(nn.Module):
"""Multi-head attention layer with residual connections"""
def __init__(self, embed_dim: int, num_heads: int = 4):
super().__init__()
# Ensure embed_dim is divisible by num_heads
if embed_dim % num_heads != 0:
# Round up to nearest multiple of num_heads
embed_dim = ((embed_dim + num_heads - 1) // num_heads) * num_heads
self.attention = nn.MultiheadAttention(
embed_dim=embed_dim,
num_heads=num_heads,
batch_first=False # Keep sequence first for compatibility
)
self.norm = nn.LayerNorm(embed_dim)
self.dropout = nn.Dropout(0.1)
def forward(self, x):
"""Forward pass with error handling"""
try:
attended, _ = self.attention(x, x, x)
attended = self.dropout(attended)
return self.norm(x + attended)
except Exception as e:
logger.error(f"Error in attention forward pass: {e}")
raise RecommenderError("Attention layer failed") from e
class HealthMonitor:
"""Enhanced health monitoring with auto-recovery"""
def __init__(self, recommender):
self.recommender = recommender
self.logger = logging.getLogger(__name__) # Add logger
self.error_counts = defaultdict(int)
self.last_check = datetime.now()
self.health_status = True
self.max_errors = 5
self.check_interval = timedelta(minutes=5)
self.metrics = defaultdict(float)
self.error_metric = ERRORS # Reference global metric
def check_health(self) -> bool:
"""Check system health and attempt recovery if needed"""
now = datetime.now()
if now - self.last_check < self.check_interval:
return self.health_status
try:
self._perform_health_checks()
self.error_counts.clear()
self.health_status = True
except Exception as e:
self.error_metric.inc() # Track error
self.logger.error(f"Health check failed: {e}")
self.error_counts['health_check'] += 1
self.health_status = False
if self.error_counts['health_check'] >= self.max_errors:
self._emergency_restart()
self.last_check = now
return self.health_status
def _perform_health_checks(self):
"""Perform individual health checks and update metrics"""
# Check system resources
memory = psutil.virtual_memory()
if memory.percent > 90:
self._cleanup_resources()
# Check database connection
if not self.recommender.connection or self.recommender.connection.closed:
self.recommender.connect_to_db()
# Check model state
if self.recommender.model_state == ModelState.ERROR:
self.recommender.load_model()
# Update metrics
self.metrics.update({
'memory_usage': memory.percent,
'error_rate': sum(self.error_counts.values())
})
def _cleanup_resources(self):
"""Cleanup existing resources"""
if hasattr(self.recommender, 'cleanup'):
self.recommender.cleanup()
def _emergency_restart(self):
"""Emergency restart of critical components"""
self._cleanup_and_reinitialize()
def _cleanup_and_reinitialize(self):
"""Cleanup resources and reinitialize components"""
self.logger.warning("Initiating emergency restart...")
try:
if hasattr(self.recommender, 'cleanup'):
self.recommender.cleanup()
self._reinitialize_components()
self._reset_error_state()
except Exception as e:
self.error_metric.inc()
self.logger.error(f"Failed to cleanup and reinitialize: {e}")
def _reinitialize_components(self):
"""Reinitialize core system components"""
if hasattr(self.recommender, 'connect_to_db'):
self.recommender.connect_to_db()
if hasattr(self.recommender, '_setup_redis'):
self.recommender.redis = self.recommender._setup_redis()
if hasattr(self.recommender, 'load_model'):
try:
self.recommender.load_model()
except Exception as e:
self.logger.error(f"Failed to load model during reinitialization: {e}")
def _reset_error_state(self):
"""Reset error tracking state"""
self.error_counts.clear()
self.health_status = True
class MemoryCache:
"""In-memory cache implementation for Redis fallback"""
def __init__(self):
self.cache: Dict[str, str] = {}
self.ttls: Dict[str, float] = {}
def get(self, key: str) -> Optional[str]:
if key not in self.cache:
return None
if time.time() >= self.ttls.get(key, 0):
del self.cache[key]
del self.ttls[key]
return None
return self.cache[key]
def setex(self, key: str, ttl: timedelta, value: str) -> None:
self.cache[key] = value
self.ttls[key] = time.time() + ttl.total_seconds()
def flushall(self) -> None:
self.cache.clear()
self.ttls.clear()
class ModelVersion:
"""Track model versions"""
def __init__(self):
self.major = 3
self.minor = 0
self.patch = 0
self.timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
def __str__(self):
return f"{self.major}.{self.minor}.{self.patch}"
def __lt__(self, other):
return (self.major, self.minor, self.patch) < (other.major, other.minor, other.patch)
def get_db_connection():
"""Get database connection with retry logic"""
max_retries = 3
retry_delay = 2
for attempt in range(max_retries):
try:
# Use DATABASE_CONFIG directly from config.py
db_url = (
f"postgresql://{DATABASE_CONFIG['user']}:{DATABASE_CONFIG['password']}"
f"@{DATABASE_CONFIG['host']}/{DATABASE_CONFIG['database']}"
)
engine = create_engine(
db_url,
pool_size=DATABASE_CONFIG['pool_size'],
max_overflow=DATABASE_CONFIG['max_overflow'],
pool_timeout=DATABASE_CONFIG['pool_timeout'],
pool_recycle=DATABASE_CONFIG['pool_recycle']
)
# Test connection
with engine.connect() as conn:
conn.execute(text("SELECT 1"))
return engine
except Exception as e:
if attempt == max_retries - 1:
raise RecommenderError(f"Failed to connect to database after {max_retries} attempts") from e
time.sleep(retry_delay * (attempt + 1))
class CacheManager:
"""Unified cache management with Redis fallback"""
def __init__(self):
self.logger = logging.getLogger(__name__)
self.cache = self._setup_cache()
def _setup_cache(self) -> Union[redis.Redis, MemoryCache]:
"""Setup Redis with fallback to in-memory cache"""
try:
client = redis.Redis(
host='localhost',
port=6379,
db=0,
socket_timeout=1,
decode_responses=True
)
client.ping()
return client
except Exception as e:
self.logger.info(f"Redis not available, using memory cache: {e}")
return MemoryCache()
def get(self, key: str) -> Optional[Any]:
"""Get value from cache with proper deserialization"""
try:
if value := self.cache.get(key):
# Properly deserialize RecommendationResult objects
data = json.loads(value)
if isinstance(data, list):
return [RecommendationResult(**item) for item in data]
return data
return None
except Exception as e:
self.logger.error(f"Cache get error: {e}")
return None
def set(self, key: str, value: Any, ttl: int = 3600) -> None:
"""Set value in cache with proper serialization"""
try:
# Convert RecommendationResult objects to dicts
if isinstance(value, list):
value = [
item.__dict__ if isinstance(item, RecommendationResult) else item
for item in value
]
json_value = json.dumps(value)
if isinstance(self.cache, redis.Redis):
self.cache.setex(key, ttl, json_value)
else:
self.cache.setex(key, timedelta(seconds=ttl), json_value)
except Exception as e:
self.logger.error(f"Cache set error: {e}")
class ContentRecommender:
def _validate_config(self, config: Dict[str, Any]) -> None:
"""Validate configuration parameters"""
required_params = [
'MIN_INTERACTION_THRESHOLD',
'MIN_INTERACTIONS',
'BATCH_SIZE',
'MAX_EPOCHS'
]
for param in required_params:
if param not in config:
raise ValueError(f"Missing required config parameter: {param}")
# Validate numeric parameters
if config['MIN_INTERACTION_THRESHOLD'] < 0:
raise ValueError("MIN_INTERACTION_THRESHOLD must be non-negative")
if config['MIN_INTERACTIONS'] < 0:
raise ValueError("MIN_INTERACTIONS must be non-negative")
if config['BATCH_SIZE'] <= 0:
raise ValueError("BATCH_SIZE must be positive")
def __init__(self, model_path: str = "recommender_model", config: Dict[str, Any] = None):
# Initialize logger first
self.logger = logging.getLogger(__name__)
# Validate config
if config:
self._validate_config(config)
# Use the shared registry for metrics
self.registry = REGISTRY
# Initialize error tracking metric using the shared registry
self.error_metric = ERRORS
# Use DATABASE_CONFIG directly instead of trying to get it from config parameter
self.db_config = DATABASE_CONFIG
# Use MODEL_CONFIG for model parameters
self.config = MODEL_CONFIG
# Initialize remaining attributes
self.model_path = model_path
self.model_state = ModelState.UNTRAINED
self.model = None
self.engine = None # Will be set in connect_to_db()
try:
# Connect to database first
if not self.connect_to_db():
raise DatabaseError("Failed to establish database connection")
# Initialize remaining components
self.redis = self._setup_redis()
self.scaler = StandardScaler()
self.vectorizer = TfidfVectorizer()
self.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
# Add model version tracking
self.model_version = ModelVersion()
# Initialize cache
self.cache = CacheManager()
except Exception as e:
self.logger.error(f"Initialization failed: {e}")
self.error_metric.inc()
self.cleanup()
raise
def _setup_redis(self) -> Union[redis.Redis, MemoryCache]:
"""Setup Redis connection with fallback to in-memory cache"""
try:
client = redis.Redis(
host='localhost',
port=6379,
db=0,
socket_timeout=1,
decode_responses=True
)
client.ping() # Quick check
self.logger.info("Redis connection established")
return client
except Exception as e:
self.logger.info(f"Redis not available, using in-memory cache: {e}")
return self._setup_memory_cache()
def _setup_memory_cache(self) -> MemoryCache:
"""Setup in-memory cache as Redis fallback"""
return MemoryCache()
def _build_database_url(self, db_config: Dict[str, str]) -> str:
"""Construct database URL from config"""
return (
f"postgresql://{db_config['user']}:{db_config['password']}"
f"@{db_config['host']}/{db_config['database']}"
)
def _setup_database(self) -> None:
"""Setup database connection with retries"""
retry_count = 0
max_retries = 3
# Check if PostgreSQL is running first
if not self._check_postgres_running():
self.logger.error("PostgreSQL is not running. Please start the service.")
raise RecommenderError("PostgreSQL service not running")
while retry_count < max_retries:
try:
self._setup_database_connection()
self.logger.info("Database connected successfully")
return
except Exception as e:
retry_count += 1
self.logger.error(f"Database connection attempt {retry_count} failed: {e}")
time.sleep(2 ** retry_count) # Exponential backoff
raise RecommenderError("Failed to establish database connection")
def _check_postgres_running(self) -> bool:
"""Check if PostgreSQL service is running"""
try:
import socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
result = sock.connect_ex(('localhost', 5432))
sock.close()
return result == 0
except Exception:
return False
def _setup_database_connection(self) -> None:
"""Setup single database connection"""
self.connect_to_db()
def connect_to_db(self) -> bool:
"""Connect to database with proper error handling"""
try:
# Get pool settings from nested config
pool_settings = self.db_config.get('pool_settings', {})
# Construct database URL
db_url = (
f"postgresql://{self.db_config['user']}:{self.db_config['password']}"
f"@{self.db_config['host']}:{self.db_config.get('port', '5432')}"
f"/{self.db_config['database']}"
)
# Create engine with connection pooling
self.engine = create_engine(
db_url,
pool_size=pool_settings.get('pool_size', 5),
max_overflow=pool_settings.get('max_overflow', 10),
pool_timeout=pool_settings.get('pool_timeout', 30),
pool_recycle=pool_settings.get('pool_recycle', 1800),
pool_pre_ping=pool_settings.get('pool_pre_ping', True),
echo_pool=pool_settings.get('echo_pool', False)
)
# Test connection
with self.engine.connect() as conn:
conn.execute(text("SELECT 1"))
self.logger.info("Database connection established")
return True
except Exception as e:
self.logger.error(f"Database connection failed: {str(e)}")
return False
@RESPONSE_TIME.time()
def _generate_cache_key(self, user_id: int, **params) -> str:
"""Generate cache key with version and parameters
Args:
user_id: User ID for recommendations
**params: Additional parameters that affect recommendations
Returns:
Cache key string incorporating all parameters
"""
try:
key_parts = [f"recommendations:{user_id}"]
key_parts.extend(f"{k}:{v}" for k, v in sorted(params.items()))
version_prefix = f"v{self.model_version}"
return f"{version_prefix}:" + ":".join(key_parts)
except Exception as e:
self.logger.error(f"Error generating cache key: {e}")
return f"recommendations:{user_id}" # Fallback to simple key
def get_recommendations(self, user_id: int, limit: int = 10) -> List[RecommendationResult]:
"""Get personalized recommendations with better diversity"""
try:
self.logger.info(f"Current model state: {self.model_state}")
# Get user interactions
interactions = self.get_user_interactions(user_id)
if interactions.empty:
self.logger.info("No user interactions found, using cold start")
return self._get_cold_start_recommendations(limit)
# Get all characters
characters = self._get_character_features()
if characters.empty:
self.logger.error("No characters found in database")
return self._get_fallback_recommendations(limit)
# Prepare features for both interacted and non-interacted characters
interacted_ids = set(interactions['character_id'].values)
non_interacted = characters[~characters['id'].isin(interacted_ids)]
# Combine features
all_features = pd.concat([interactions, non_interacted], ignore_index=True)
# Prepare features and get predictions
features = self._prepare_features(all_features, characters)
# Convert to PyTorch tensor
features_tensor = torch.FloatTensor(features)
# Get predictions
with torch.no_grad():
scores = self.model(features_tensor).numpy()
# Boost scores for already interacted characters
boost_factor = 1.2 # 20% boost for familiar characters
scores[:len(interactions)] *= boost_factor
# Get top recommendations
recommendations = self._format_recommendations(
all_features,
scores,
limit=limit,
source='neural'
)
self.logger.info(
f"Generated {len(recommendations)} recommendations "
f"(including {len(interactions)} interacted characters)"
)
return recommendations
except Exception as e:
self.logger.error(f"Error getting recommendations: {e}")
self.logger.error(f"Stack trace: {traceback.format_exc()}")
return self._get_fallback_recommendations(limit)
def _create_model(self, trial: optuna.Trial, input_size: int) -> nn.Module:
"""Create model with Optuna-optimized hyperparameters"""
# Get hyperparameters from trial
n_layers = trial.suggest_int('n_layers', 2, 4)
hidden_sizes = []
# First hidden layer size should be smaller than input
first_layer_size = trial.suggest_int('hidden_0', input_size // 4, input_size)
hidden_sizes.append(first_layer_size)
# Subsequent layers get progressively smaller
for i in range(1, n_layers):
prev_size = hidden_sizes[-1]
hidden_sizes.append(
trial.suggest_int(f'hidden_{i}', prev_size // 4, prev_size)
)
dropout = trial.suggest_float('dropout', 0.1, 0.5)
# Create model with suggested architecture
layers = []
prev_size = input_size
for hidden_size in hidden_sizes:
layers.extend([
nn.Linear(prev_size, hidden_size),
nn.ReLU(),
nn.Dropout(dropout)
])
prev_size = hidden_size
# Output layer
layers.append(nn.Linear(prev_size, 1))
layers.append(nn.Sigmoid())
return nn.Sequential(*layers).to(self.device)
def _objective(self, trial: optuna.Trial) -> float:
"""Optuna objective function for model optimization"""
try:
# Create model with trial parameters
model = self._create_model(trial, input_size=self.X_train.shape[1])
# Get hyperparameters from trial
batch_size = trial.suggest_int('batch_size', 32, 256)
learning_rate = trial.suggest_float('learning_rate', 1e-5, 1e-2, log=True)
# Training setup
criterion = nn.BCELoss()
optimizer = optim.Adam(model.parameters(), lr=learning_rate)
# Train model
best_val_loss = float('inf')
patience = 10
patience_counter = 0
for epoch in range(100): # Max epochs
# Training
model.train()
train_loss = 0
for X_batch, y_batch in self._batch_data(self.X_train, self.y_train, batch_size):
optimizer.zero_grad()
output = model(X_batch).squeeze()
loss = criterion(output, y_batch)
loss.backward()
optimizer.step()
train_loss += loss.item()
# Validation
model.eval()
val_loss = 0
with torch.no_grad():
for X_batch, y_batch in self._batch_data(self.X_val, self.y_val, batch_size):
output = model(X_batch).squeeze()
val_loss += criterion(output, y_batch).item()
# Early stopping
if val_loss < best_val_loss:
best_val_loss = val_loss
patience_counter = 0
else:
patience_counter += 1
if patience_counter >= patience:
break
# Report intermediate value
trial.report(val_loss, epoch)
# Handle pruning based on the intermediate value
if trial.should_prune():
raise optuna.TrialPruned()
return best_val_loss
except Exception as e:
self.logger.error(f"Error in Optuna trial: {e}")
raise optuna.TrialPruned()
def train_model(self) -> None:
"""Train model with Optuna optimization"""
try:
self.logger.info("Starting model training with Optuna optimization...")
# Prepare training data first
self._prepare_training_data()
# Create study
study = optuna.create_study(
direction="minimize",
pruner=optuna.pruners.MedianPruner()
)
# Optimize
study.optimize(
self._objective,
n_trials=20, # Number of trials to run
timeout=3600 # 1 hour timeout
)
# Get best trial
best_trial = study.best_trial
self.logger.info(f"Best trial value: {best_trial.value}")
self.logger.info("Best hyperparameters:")
for key, value in best_trial.params.items():
self.logger.info(f" {key}: {value}")
# Train final model with best parameters
self.model = self._create_model(best_trial, input_size=self.X_train.shape[1])
self._train_final_model(best_trial.params)
self.model_state = ModelState.READY
self.logger.info("Model training completed successfully")
except Exception as e:
self.logger.error(f"Error training model: {e}")
self.model_state = ModelState.ERROR
raise
def _prepare_training(self) -> None:
"""Prepare for model training"""
self.model_state = ModelState.TRAINING
self.logger.info("Starting model training...")
def _get_training_data(self) -> Dict[str, np.ndarray]:
"""Get and prepare training data"""
interactions = self._get_all_interactions()
if interactions.empty:
raise RecommenderError("No training data available")
characters = self._get_character_features()
X = self._prepare_features(interactions, characters)
y = interactions['interaction_score'].values
X_train, X_val, y_train, y_val = train_test_split(
X, y, test_size=0.2, random_state=42
)
return {
'X_train': X_train,
'X_val': X_val,
'y_train': y_train,
'y_val': y_val,
'input_size': X.shape[1]
}
def _optimize_model_params(self, data: Dict[str, np.ndarray]) -> Dict[str, Any]:
"""Optimize model hyperparameters"""
return self._optimize_hyperparameters(data['X_train'], data['y_train'])
def _save_training_checkpoint(self, epoch: int, model_state: Dict,
optimizer_state: Dict, loss: float) -> None:
"""Save training checkpoint"""
try:
checkpoint = {
'epoch': epoch,
'model_state_dict': model_state,
'optimizer_state_dict': optimizer_state,
'loss': loss,
'timestamp': datetime.now().isoformat()
}
checkpoint_path = f"{self.model_path}_checkpoint_{epoch}.pt"
torch.save(checkpoint, checkpoint_path)
self.logger.info(f"Saved checkpoint to {checkpoint_path}")
except Exception as e:
self.logger.error(f"Error saving checkpoint: {e}")
def _execute_training_loop(self, data: Dict[str, np.ndarray],