File size: 1,864 Bytes
cf9e03f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Visual Identity & Brand Impersonation Branch (Acharya, Ale, & Kadel, 2026)
Extracts spatial layout embeddings and brand logo similarity vectors from rendered page screenshots.
"""
import numpy as np


class VisualBrandEncoder:
    """
    Spatial Attention Visual Feature Extractor.
    Processes 224x224 webpage screenshots and extracted logo regions into a 64-D visual identity embedding.
    """

    def __init__(self, input_dim: int = 32, embed_dim: int = 32, seed: int = 42):
        rng = np.random.default_rng(seed)
        self.W1 = rng.normal(0, np.sqrt(2.0 / input_dim), size=(input_dim, 64))
        self.b1 = np.zeros(64)
        self.W_attn = rng.normal(0, 0.1, size=(64, 64))
        self.W2 = rng.normal(0, np.sqrt(2.0 / 64), size=(64, embed_dim))
        self.b2 = np.zeros(embed_dim)

    @staticmethod
    def relu(x: np.ndarray) -> np.ndarray:
        return np.maximum(0.0, x)

    @staticmethod
    def softmax(x: np.ndarray) -> np.ndarray:
        e_x = np.exp(x - np.max(x, axis=-1, keepdims=True))
        return e_x / np.sum(e_x, axis=-1, keepdims=True)

    def forward(self, x_vis: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
        """
        Args:
            x_vis: Array of shape (N, input_dim) representing multi-scale visual descriptors.
        Returns:
            z_vis: Visual identity embedding (N, embed_dim)
            attn_weights: Spatial attention weights for Grad-CAM / XAI attribution (N, 64)
        """
        h1 = self.relu(x_vis @ self.W1 + self.b1)
        attn_scores = h1 @ self.W_attn
        attn_weights = self.softmax(attn_scores)
        h_attended = h1 * (1.0 + attn_weights)
        z_vis = self.relu(h_attended @ self.W2 + self.b2)
        # L2 normalize for cosine brand comparison
        norm = np.linalg.norm(z_vis, axis=-1, keepdims=True) + 1e-8
        return z_vis / norm, attn_weights