FRsūtil̲s
A fuzzy-rough reasoning utilities library
 
Loading...
Searching...
No Matches
similarities.py
Go to the documentation of this file.
1"""
2Similarities
3
4Provides an extensible and optimized framework to compute similarity matrices
5with pluggable similarity functions (using inheritance)
6
7@author: Mehran Amiri
8"""
9
10import numpy as np
11from abc import ABC, abstractmethod
12from typing import Callable
13
14
15# ------------------------------------------------------------------------------
16# Similarity Function Base & Implementations
17# ------------------------------------------------------------------------------
18
20 """
21 Abstract base class for scalar similarity functions.
22 """
23 @abstractmethod
24 def compute(self, diff: np.ndarray) -> np.ndarray:
25 pass
26
27 def __call__(self, diff: np.ndarray) -> np.ndarray:
28 return self.compute(diff)
29
30
32 """
33 Linear similarity: sim = max(0, 1 - |v1 - v2|)
34 """
35 def compute(self, diff: np.ndarray) -> np.ndarray:
36 return np.maximum(0.0, 1.0 - np.abs(diff))
37
38
40 """
41 Gaussian similarity: sim = exp(-diff^2 / (2 * sigma^2))
42
43 @param sigma: Standard deviation for the Gaussian kernel (must be > 0)
44 """
45 def __init__(self, sigma: float = 0.1):
46 # if not (0 < sigma <= 0.5):
47 # raise ValueError("sigma must be in the range (0, 0.5]")
48 self.sigma = sigma
49
50 def compute(self, diff: np.ndarray) -> np.ndarray:
51 result = np.exp(-(diff ** 2) / (2.0 * self.sigma ** 2))
52 return result
53
54# ------------------------------------------------------------------------------
55# Similarity Matrix Computation
56# ------------------------------------------------------------------------------
57
59 X: np.ndarray,
60 similarity_func: SimilarityFunction,
61 tnorm: Callable[[np.ndarray, np.ndarray], np.ndarray]
62) -> np.ndarray:
63 """
64 Compute the pairwise similarity matrix for samples using a vectorized
65 similarity function and T-norm operator.
66
67 @param X: Normalized input matrix of shape (n_samples, n_features)
68 @param similarity_func: Instance of SimilarityFunction subclass
69 @param tnorm: Callable T-norm function (e.g., min, product, Yager)
70 @return: Similarity matrix of shape (n_samples, n_samples)
71 """
72 n_samples, n_features = X.shape
73 sim_matrix = np.ones((n_samples, n_samples), dtype=np.float64)
74
75 for k in range(n_features):
76 col = X[:, k].reshape(-1, 1) # Shape (n, 1)
77 diff = col - col.T # Shape (n, n)
78 sim_k = similarity_func(diff) # Compute similarity
79 sim_matrix = tnorm(sim_matrix, sim_k) # Apply T-norm
80
81 np.fill_diagonal(sim_matrix, 1.0)
82 return sim_matrix
np.ndarray compute(self, np.ndarray diff)
np.ndarray compute(self, np.ndarray diff)
np.ndarray compute(self, np.ndarray diff)
np.ndarray __call__(self, np.ndarray diff)
np.ndarray calculate_similarity_matrix(np.ndarray X, SimilarityFunction similarity_func, Callable[[np.ndarray, np.ndarray], np.ndarray] tnorm)