unify model names

This commit is contained in:
Dobromir Popov
2025-09-09 01:10:35 +03:00
parent 0e886527c8
commit 317c703ea0
5 changed files with 229 additions and 104 deletions

View File

@@ -15,11 +15,19 @@ Architecture:
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
import logging
from typing import Dict, List, Optional, Tuple, Any
from abc import ABC, abstractmethod
# Try to import numpy, but provide fallback if not available
try:
import numpy as np
HAS_NUMPY = True
except ImportError:
np = None
HAS_NUMPY = False
logging.warning("NumPy not available - COB RL model will have limited functionality")
from .model_interfaces import ModelInterface
logger = logging.getLogger(__name__)
@@ -164,45 +172,54 @@ class MassiveRLNetwork(nn.Module):
'features': x # Hidden features for analysis
}
def predict(self, cob_features: np.ndarray) -> Dict[str, Any]:
def predict(self, cob_features) -> Dict[str, Any]:
"""
High-level prediction method for COB features
Args:
cob_features: COB features as numpy array [input_size]
cob_features: COB features as tensor or numpy array [input_size]
Returns:
Dict containing prediction results
"""
self.eval()
with torch.no_grad():
# Convert to tensor and add batch dimension
if isinstance(cob_features, np.ndarray):
if HAS_NUMPY and isinstance(cob_features, np.ndarray):
x = torch.from_numpy(cob_features).float()
else:
elif isinstance(cob_features, torch.Tensor):
x = cob_features.float()
else:
# Try to convert from list or other format
x = torch.tensor(cob_features, dtype=torch.float32)
if x.dim() == 1:
x = x.unsqueeze(0) # Add batch dimension
# Move to device
device = next(self.parameters()).device
x = x.to(device)
# Forward pass
outputs = self.forward(x)
# Process outputs
price_probs = F.softmax(outputs['price_logits'], dim=1)
predicted_direction = torch.argmax(price_probs, dim=1).item()
confidence = outputs['confidence'].item()
value = outputs['value'].item()
# Convert probabilities to list (works with or without numpy)
if HAS_NUMPY:
probabilities = price_probs.cpu().numpy()[0].tolist()
else:
probabilities = price_probs.cpu().tolist()[0]
return {
'predicted_direction': predicted_direction, # 0=DOWN, 1=SIDEWAYS, 2=UP
'confidence': confidence,
'value': value,
'probabilities': price_probs.cpu().numpy()[0],
'probabilities': probabilities,
'direction_text': ['DOWN', 'SIDEWAYS', 'UP'][predicted_direction]
}
@@ -250,36 +267,45 @@ class COBRLModelInterface(ModelInterface):
logger.info(f"COB RL Model Interface initialized on {self.device}")
def predict(self, cob_features: np.ndarray) -> Dict[str, Any]:
def predict(self, cob_features) -> Dict[str, Any]:
"""Make prediction using the model"""
self.model.eval()
with torch.no_grad():
# Convert to tensor and add batch dimension
if isinstance(cob_features, np.ndarray):
if HAS_NUMPY and isinstance(cob_features, np.ndarray):
x = torch.from_numpy(cob_features).float()
else:
elif isinstance(cob_features, torch.Tensor):
x = cob_features.float()
else:
# Try to convert from list or other format
x = torch.tensor(cob_features, dtype=torch.float32)
if x.dim() == 1:
x = x.unsqueeze(0) # Add batch dimension
# Move to device
x = x.to(self.device)
# Forward pass
outputs = self.model(x)
# Process outputs
price_probs = F.softmax(outputs['price_logits'], dim=1)
predicted_direction = torch.argmax(price_probs, dim=1).item()
confidence = outputs['confidence'].item()
value = outputs['value'].item()
# Convert probabilities to list (works with or without numpy)
if HAS_NUMPY:
probabilities = price_probs.cpu().numpy()[0].tolist()
else:
probabilities = price_probs.cpu().tolist()[0]
return {
'predicted_direction': predicted_direction, # 0=DOWN, 1=SIDEWAYS, 2=UP
'confidence': confidence,
'value': value,
'probabilities': price_probs.cpu().numpy()[0],
'probabilities': probabilities,
'direction_text': ['DOWN', 'SIDEWAYS', 'UP'][predicted_direction]
}