nrps_rs/svm/
kernels.rs

1// License: GNU Affero General Public License v3 or later
2// A copy of GNU AGPL v3 should have been included in this software package in LICENSE.txt.
3use std::fmt::Debug;
4
5use crate::errors::NrpsError;
6use crate::svm::vectors::{FeatureVector, SupportVector, Vector};
7
8pub trait Kernel {
9    fn compute(&self, vec1: &SupportVector, vec2: &FeatureVector) -> Result<f64, NrpsError>;
10}
11
12impl Debug for dyn Kernel {
13    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
14        write!(f, "Kernel")
15    }
16}
17
18#[derive(Debug)]
19pub struct LinearKernel {}
20
21impl Kernel for LinearKernel {
22    fn compute(&self, vec1: &SupportVector, vec2: &FeatureVector) -> Result<f64, NrpsError> {
23        vec1.similarity(vec2)
24    }
25}
26
27#[derive(Debug)]
28pub struct RBFKernel {
29    gamma: f64,
30}
31
32impl RBFKernel {
33    pub fn new(gamma: f64) -> Self {
34        RBFKernel { gamma }
35    }
36}
37
38impl Kernel for RBFKernel {
39    fn compute(&self, vec1: &SupportVector, vec2: &FeatureVector) -> Result<f64, NrpsError> {
40        Ok((-self.gamma * vec1.square_dist(vec2)?).exp())
41    }
42}