Skip to main content

TsetlinMachine

Struct TsetlinMachine 

Source
pub struct TsetlinMachine { /* private fields */ }
Expand description

§Overview

Binary classification Tsetlin Machine with weighted clauses and adaptive threshold.

§Examples

use tsetlin_rs::{Config, TsetlinMachine};

let config = Config::builder().clauses(20).features(2).build().unwrap();

let mut tm = TsetlinMachine::new(config, 15);

Implementations§

Source§

impl TsetlinMachine

Source

pub fn new(config: Config, threshold: i32) -> Self

§Overview

Creates new machine. Half clauses +1 polarity, half -1.

Source

pub fn with_advanced( config: Config, threshold: i32, advanced: AdvancedOptions, ) -> Self

§Overview

Creates machine with advanced options.

Source

pub fn threshold(&self) -> f32

Returns current threshold value (may differ from base if adaptive).

Source

pub const fn config(&self) -> &Config

Returns configuration.

Source

pub fn clauses(&self) -> &[Clause]

Returns read-only access to clauses.

Source

pub fn threshold_base(&self) -> f32

§Overview

Base threshold (initial value).

Source

pub fn reset_threshold(&mut self)

§Overview

Resets threshold to base value.

Source

pub fn sum_votes(&self, x: &[u8]) -> f32

§Overview

Sum of weighted clause votes for input x.

Source

pub fn predict(&self, x: &[u8]) -> u8

§Overview

Predicts class (0 or 1).

Source

pub fn predict_batch(&self, xs: &[Vec<u8>]) -> Vec<u8>

§Overview

Batch prediction for multiple samples.

Source

pub fn train_one<R: Rng>(&mut self, x: &[u8], y: u8, rng: &mut R)

§Overview

Trains on single example with tracking.

Source

pub fn update_weights(&mut self)

§Overview

Updates clause weights. Call at end of epoch.

Source

pub fn prune_dead_clauses(&mut self)

§Overview

Prunes dead clauses (low activation or weight).

Source

pub fn reset_activations(&mut self)

§Overview

Resets activation counters. Call at start of epoch.

Source

pub fn fit(&mut self, x: &[Vec<u8>], y: &[u8], epochs: usize, seed: u64)

Simple training for given epochs.

§Arguments
  • x - Training inputs (binary features)
  • y - Binary labels (0 or 1)
  • epochs - Number of training epochs
  • seed - Random seed for reproducibility
Source

pub fn fit_with_options( &mut self, x: &[Vec<u8>], y: &[u8], opts: FitOptions, ) -> FitResult

Training with full options including early stopping and callbacks.

§Arguments
  • x - Training inputs (binary features)
  • y - Binary labels (0 or 1)
  • opts - Training options (epochs, early stopping, callback)
§Returns

FitResult with training statistics.

Source

pub fn evaluate(&self, x: &[Vec<u8>], y: &[u8]) -> f32

Evaluates accuracy on test data.

Returns fraction of correct predictions (0.0 to 1.0).

Source

pub fn rules(&self) -> Vec<Rule>

Extracts learned rules from all clauses.

Source

pub fn clause_weights(&self) -> Vec<f32>

§Overview

Returns clause weights for inspection.

Source

pub fn clause_activations(&self) -> Vec<u32>

Returns clause activation counts.

Source

pub fn quick(n_clauses: usize, n_features: usize, threshold: i32) -> Self

Quick constructor with sensible defaults.

Equivalent to Config::builder().clauses(n_clauses).features(n_features).build() followed by TsetlinMachine::new(config, threshold).

§Panics

Panics if n_clauses is odd or zero, or n_features is zero.

Source

pub fn to_sparse(&self) -> SparseTsetlinMachine

Converts to sparse representation for memory-efficient inference.

Call after fit() to reduce memory by 5-100x depending on clause sparsity. The sparse model supports prediction but not training.

§Memory Savings
FeaturesDenseSparse (typical)Reduction
10040 KB2 KB20x
1000400 KB8 KB50x
100004 MB20 KB200x
§Example
use tsetlin_rs::{Config, TsetlinMachine};

let config = Config::builder().clauses(20).features(100).build().unwrap();
let mut tm = TsetlinMachine::new(config, 10);

let x: Vec<Vec<u8>> = (0..100).map(|i| vec![(i % 2) as u8; 100]).collect();
let y: Vec<u8> = (0..100).map(|i| (i % 2) as u8).collect();

tm.fit(&x, &y, 100, 42);

// Convert to sparse
let sparse = tm.to_sparse();

// Verify same predictions
for xi in &x {
    assert_eq!(tm.predict(xi), sparse.predict(xi));
}

// Check compression
let stats = sparse.memory_stats();
println!("Compression: {}x", stats.compression_ratio(100));
Source

pub fn partial_fit(&mut self, x: &[u8], y: u8, seed: u64)

Trains on a single sample (online/incremental learning).

Unlike fit(), this processes one sample without requiring the full dataset in memory. Useful for streaming data or real-time learning.

§Arguments
  • x - Single input sample (binary features)
  • y - Binary label (0 or 1)
  • seed - Random seed for this update
§Example
use tsetlin_rs::{Config, TsetlinMachine};

let config = Config::builder().clauses(20).features(2).build().unwrap();
let mut tm = TsetlinMachine::new(config, 10);

// Stream samples one at a time
tm.partial_fit(&[0, 1], 1, 42);
tm.partial_fit(&[1, 0], 1, 43);
tm.partial_fit(&[0, 0], 0, 44);
Source

pub fn partial_fit_batch( &mut self, xs: &[Vec<u8>], ys: &[u8], seed: u64, update_weights: bool, )

Trains on a mini-batch of samples (online/incremental learning).

Processes multiple samples in sequence without requiring the full dataset. Optionally updates weights after the batch.

§Arguments
  • xs - Batch of input samples
  • ys - Batch of binary labels
  • seed - Random seed for this batch
  • update_weights - Whether to update clause weights after batch
§Example
use tsetlin_rs::{Config, TsetlinMachine};

let config = Config::builder().clauses(20).features(2).build().unwrap();
let mut tm = TsetlinMachine::new(config, 10);

// Process mini-batches
let batch_x = vec![vec![0, 1], vec![1, 0]];
let batch_y = vec![1, 1];
tm.partial_fit_batch(&batch_x, &batch_y, 42, true);

Trait Implementations§

Source§

impl Clone for TsetlinMachine

Source§

fn clone(&self) -> TsetlinMachine

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for TsetlinMachine

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl TsetlinModel<Vec<u8>, u8> for TsetlinMachine

Source§

fn fit(&mut self, x: &[Vec<u8>], y: &[u8], epochs: usize, seed: u64)

Trains the model on labeled data. Read more
Source§

fn predict(&self, x: &Vec<u8>) -> u8

Predicts label for a single sample.
Source§

fn evaluate(&self, x: &[Vec<u8>], y: &[u8]) -> f32

Evaluates model accuracy/performance on test data. Read more
Source§

fn predict_batch(&self, xs: &[Vec<u8>]) -> Vec<u8>

Batch prediction for multiple samples.
Source§

impl VotingModel<Vec<u8>> for TsetlinMachine

Source§

fn sum_votes(&self, x: &Vec<u8>) -> f32

Returns raw vote sum for input.

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V