Configuration class for HDC systems.
@dataclass
class HDCConfig(MemoryConfig):
"""Configuration for HDC system."""
dimension: int = 10000
hypervector_type: str = "bipolar"
sparsity: float = 0.5
levels: int = 3
seed: Optional[int] = NoneParameters:
dimension: Dimensionality of hypervectors (default: 10000)hypervector_type: Type of hypervectors ("binary", "bipolar", "ternary", "level")sparsity: Sparsity level for sparse vectors (0.0 to 1.0)levels: Number of levels for level hypervectorsseed: Random seed for reproducibility
Main HDC class implementing core operations.
class HDC(CognitiveMemory):
def __init__(self, config: HDCConfig)Methods:
def generate_hypervector(self, orthogonal_to: Optional[List[np.ndarray]] = None) -> np.ndarrayGenerate a random hypervector, optionally orthogonal to given vectors.
def bind(self, a: np.ndarray, b: np.ndarray) -> np.ndarrayBind two hypervectors using appropriate operation for the vector type.
def unbind(self, composite: np.ndarray, known: np.ndarray) -> np.ndarrayUnbind a known hypervector from a composite (inverse of bind).
def bundle(self, hypervectors: List[np.ndarray], weights: Optional[List[float]] = None) -> np.ndarrayBundle multiple hypervectors into a single hypervector.
def permute(self, hypervector: np.ndarray, shift: int = 1, inverse: bool = False) -> np.ndarrayPermute hypervector elements by cyclic shift.
def similarity(self, a: np.ndarray, b: np.ndarray, metric: str = "cosine") -> floatCalculate similarity between two hypervectors.
Binary hypervectors with values in {0, 1}.
class BinaryHypervector(Hypervector):
@staticmethod
def random(dimension: int, sparsity: float = 0.5, seed: Optional[int] = None) -> np.ndarray
@staticmethod
def bind(a: np.ndarray, b: np.ndarray) -> np.ndarray
@staticmethod
def bundle(hypervectors: List[np.ndarray], method: str = "majority") -> np.ndarrayBipolar hypervectors with values in {-1, +1}.
class BipolarHypervector(Hypervector):
@staticmethod
def random(dimension: int, seed: Optional[int] = None) -> np.ndarray
@staticmethod
def bind(a: np.ndarray, b: np.ndarray) -> np.ndarray
@staticmethod
def bundle(hypervectors: List[np.ndarray], method: str = "average") -> np.ndarrayTernary hypervectors with values in {-1, 0, +1}.
class TernaryHypervector(Hypervector):
@staticmethod
def random(dimension: int, sparsity: float = 0.33, seed: Optional[int] = None) -> np.ndarrayMulti-level discrete hypervectors.
class LevelHypervector(Hypervector):
@staticmethod
def random(dimension: int, levels: int = 3, seed: Optional[int] = None) -> np.ndarraydef bind_hypervectors(a: np.ndarray, b: np.ndarray, hypervector_type: str = "bipolar") -> np.ndarrayBind two hypervectors based on their type.
def bundle_hypervectors(
hypervectors: List[np.ndarray],
method: BundlingMethod = BundlingMethod.MAJORITY,
weights: Optional[List[float]] = None,
hypervector_type: str = "bipolar"
) -> np.ndarrayBundle multiple hypervectors using specified method.
Bundling Methods:
MAJORITY: Majority voting (binary) or sign (bipolar)AVERAGE: Average and thresholdSAMPLE: Random sampling from inputsWEIGHTED: Weighted sum
def permute_hypervector(
hypervector: np.ndarray,
method: PermutationMethod = PermutationMethod.CYCLIC,
shift: int = 1,
permutation: Optional[np.ndarray] = None,
block_size: Optional[int] = None,
inverse: bool = False
) -> np.ndarrayPermute hypervector elements.
Permutation Methods:
CYCLIC: Circular shiftRANDOM: Random permutationBLOCK: Block-wise permutationINVERSE: Inverse permutation
def similarity(
a: np.ndarray,
b: np.ndarray,
metric: str = "cosine"
) -> floatCalculate similarity between hypervectors.
Metrics:
cosine: Cosine similarityhamming: Hamming similarity (1 - normalized Hamming distance)euclidean: Negative Euclidean distancejaccard: Jaccard similarity (for binary vectors)
Associative memory for storing and retrieving hypervectors.
class ItemMemory:
def __init__(
self,
dimension: int,
similarity_metric: str = "cosine",
max_items: Optional[int] = None
)Methods:
def add(self, label: str, hypervector: np.ndarray) -> NoneAdd a labeled hypervector to memory.
def query(
self,
hypervector: np.ndarray,
top_k: int = 5,
threshold: Optional[float] = None
) -> List[Tuple[str, float]]Query memory with a hypervector, returning top-k similar items.
def cleanup(self, hypervector: np.ndarray) -> Tuple[Optional[np.ndarray], Optional[str]]Find the closest stored hypervector (cleanup memory).
def update(self, label: str, hypervector: np.ndarray) -> NoneUpdate an existing item's hypervector.
def merge(self, label: str, hypervector: np.ndarray, weight: float = 0.5) -> NoneMerge a new hypervector with an existing one.
Encode continuous scalar values.
class ScalarEncoder(Encoder):
def __init__(
self,
dimension: int,
min_value: float,
max_value: float,
n_levels: int = 100,
method: str = "thermometer",
hypervector_type: str = "bipolar"
)Methods:
encode(value: float) -> np.ndarray: Encode a scalar value
Encode discrete categories.
class CategoricalEncoder(Encoder):
def __init__(
self,
dimension: int,
categories: Optional[List[str]] = None,
hypervector_type: str = "bipolar"
)Methods:
encode(category: str) -> np.ndarray: Encode a categoryget_categories() -> List[str]: Get list of known categories
Encode sequences using n-grams or positional encoding.
class SequenceEncoder(Encoder):
def __init__(
self,
dimension: int,
item_encoder: Optional[Encoder] = None,
method: str = "ngram",
n: int = 3,
hypervector_type: str = "bipolar"
)Methods:
encode(sequence: List[any]) -> np.ndarray: Encode a sequence
Encode spatial coordinates.
class SpatialEncoder(Encoder):
def __init__(
self,
dimension: int,
bounds: Tuple[Tuple[float, float], ...],
resolution: int = 10,
hypervector_type: str = "bipolar"
)Methods:
encode(coordinates: Tuple[float, ...]) -> np.ndarray: Encode spatial coordinates
Encode structured records with named fields.
class RecordEncoder(Encoder):
def __init__(
self,
dimension: int,
field_encoders: Optional[Dict[str, Encoder]] = None,
hypervector_type: str = "bipolar"
)Methods:
encode(record: Dict[str, any]) -> np.ndarray: Encode a recordadd_field_encoder(field_name: str, encoder: Encoder) -> None: Add encoder for specific field
Encode text using character or word n-grams.
class NGramEncoder(Encoder):
def __init__(
self,
dimension: int,
n: int = 3,
level: str = "char",
hypervector_type: str = "bipolar"
)Methods:
encode(text: str) -> np.ndarray: Encode text
Learn from single examples per class.
class OneShotClassifier(HDClassifier):
def __init__(
self,
dimension: int,
encoder: Encoder,
similarity_metric: str = "cosine",
hypervector_type: str = "bipolar",
similarity_threshold: float = 0.0
)Methods:
train(X: List[any], y: List[str]) -> None: Train on examplesadd_example(x: any, label: str) -> None: Add single examplepredict(X: List[any]) -> List[str]: Predict labelsremove_class(label: str) -> bool: Remove a class
Online learning classifier with momentum.
class AdaptiveClassifier(HDClassifier):
def __init__(
self,
dimension: int,
encoder: Encoder,
learning_rate: float = 0.1,
momentum: float = 0.9
)Methods:
update(x: any, true_label: str, predicted_label: Optional[str] = None) -> None: Update with feedback
Combine multiple HDC classifiers.
class EnsembleClassifier(HDClassifier):
def __init__(
self,
classifiers: List[HDClassifier],
voting: str = "hard"
)Voting methods:
hard: Majority votingsoft: Average probabilities
Multi-level hierarchical classification.
class HierarchicalClassifier(HDClassifier):
def __init__(
self,
dimension: int,
encoder: Encoder,
hierarchy: Dict[str, List[str]],
similarity_metric: str = "cosine",
hypervector_type: str = "bipolar"
)def measure_capacity(
hdc: HDC,
num_items: int = 1000,
noise_levels: List[float] = None,
similarity_threshold: float = 0.1
) -> HDCPerformanceMetricsMeasure capacity and noise tolerance of HDC system.
def benchmark_operations(hdc: HDC, num_trials: int = 100) -> Dict[str, float]Benchmark HDC operations and return timing in milliseconds.
def estimate_required_dimension(
num_items: int,
similarity_threshold: float = 0.1,
confidence: float = 0.99
) -> intEstimate required dimension for storing items.
def create_codebook(
num_symbols: int,
dimension: int,
hypervector_type: str = "bipolar"
) -> Dict[str, np.ndarray]Create a codebook of quasi-orthogonal hypervectors.
def create_hdc(
dimension: int = 10000,
hypervector_type: str = "bipolar",
**kwargs
) -> HDCCreate an HDC instance with specified configuration.
def generate_orthogonal_hypervectors(
dimension: int,
num_vectors: int,
hypervector_type: str = "bipolar"
) -> List[np.ndarray]Generate a set of quasi-orthogonal hypervectors.