Skip to content

Commit

Permalink
Fix clippy issues.
Browse files Browse the repository at this point in the history
  • Loading branch information
ralfbiedert committed Dec 14, 2024
1 parent e613152 commit 083bae6
Show file tree
Hide file tree
Showing 17 changed files with 44 additions and 47 deletions.
8 changes: 0 additions & 8 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -14,18 +14,10 @@ exclude = [
"docs/*",
]

[lib]
name = "ffsvm"
path = "src/lib.rs"
crate-type = ["rlib"]

[dependencies]
simd_aligned = "0.6.1"
#simd_aligned = { path = "../simd_aligned" }

[dev-dependencies]
rand = "0.8.5"

[profile.release]
opt-level = 3
lto = true
2 changes: 1 addition & 1 deletion benches/svm_dense.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ mod svm_dense {
problem_mut[i as usize] = i as f32;
}

move || (&svm).predict_value(&mut problem).expect("This should work")
move || svm.predict_value(&mut problem).expect("This should work")
}

// RBF
Expand Down
2 changes: 1 addition & 1 deletion benches/svm_sparse.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ mod svm_sparse {
problem_mut[i as usize] = i as f32;
}

move || (&svm).predict_value(&mut problem).expect("This should work")
move || svm.predict_value(&mut problem).expect("This should work")
}

// RBF
Expand Down
4 changes: 2 additions & 2 deletions src/errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,9 +51,9 @@ pub enum Error {
// }

impl From<ParseFloatError> for Error {
fn from(_e: ParseFloatError) -> Self { Error::Parsing("ParseFloatError".to_owned()) }
fn from(_e: ParseFloatError) -> Self { Self::Parsing("ParseFloatError".to_owned()) }
}

impl From<ParseIntError> for Error {
fn from(_: ParseIntError) -> Self { Error::Parsing("ParseIntError".to_owned()) }
fn from(_: ParseIntError) -> Self { Self::Parsing("ParseIntError".to_owned()) }
}
4 changes: 2 additions & 2 deletions src/parser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,7 @@ impl<'a> TryFrom<&'a str> for ModelFile<'a> {
for line in input.lines() {
let tokens = line.split_whitespace().collect::<Vec<_>>();

match tokens.get(0) {
match tokens.first() {
// Single value headers
//
// svm_type c_svc
Expand Down Expand Up @@ -190,7 +190,7 @@ impl<'a> TryFrom<&'a str> for ModelFile<'a> {
let split = x.split(':').collect::<Vec<&str>>();

Some(Attribute {
index: split.get(0)?.parse::<u32>().ok()?,
index: split.first()?.parse::<u32>().ok()?,
value: split.get(1)?.parse::<f32>().ok()?,
})
})
Expand Down
13 changes: 5 additions & 8 deletions src/sparse.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,11 @@ impl<T> SparseVector<T>
where
T: Clone + Copy + Default,
{
pub fn new() -> Self { Self { entries: Vec::new() } }
pub const fn new() -> Self { Self { entries: Vec::new() } }

pub fn clear(&mut self) { self.entries.clear(); }

pub fn iter(&self) -> SparseVectorIter<'_, T> { SparseVectorIter { vector: self, index: 0 } }
pub const fn iter(&self) -> SparseVectorIter<'_, T> { SparseVectorIter { vector: self, index: 0 } }
}

/// Basic iterator struct to go over matrix
Expand All @@ -41,7 +41,7 @@ where
pub(crate) index: usize,
}

impl<'a, T> Iterator for SparseVectorIter<'a, T>
impl<T> Iterator for SparseVectorIter<'_, T>
where
T: Clone + Copy + Default,
{
Expand Down Expand Up @@ -86,10 +86,7 @@ where
fn index_mut(&mut self, index: usize) -> &mut T {
// TODO: Beautify me

let highest_so_far: i32 = match self.entries.last() {
None => -1,
Some(x) => x.index as i32,
};
let highest_so_far: i32 = self.entries.last().map_or(-1, |x| x.index as i32);

if index as i32 <= highest_so_far {
unimplemented!("We still need to implement unsorted insertion. As of today, you need to insert element in strictly ascending order.");
Expand Down Expand Up @@ -126,7 +123,7 @@ where
pub fn row(&self, row: usize) -> &SparseVector<T> { &self.vectors[row] }

#[inline]
pub fn row_iter(&self) -> SparseMatrixIter<'_, T> { SparseMatrixIter { matrix: self, index: 0 } }
pub const fn row_iter(&self) -> SparseMatrixIter<'_, T> { SparseMatrixIter { matrix: self, index: 0 } }
}

impl<T> Index<(usize, usize)> for SparseMatrix<T>
Expand Down
2 changes: 1 addition & 1 deletion src/svm/class.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use simd_aligned::{
/// Represents one class of the SVM model.
#[derive(Clone, Debug)]
#[doc(hidden)]
pub(crate) struct Class<M32> {
pub struct Class<M32> {
/// The label of this class
pub(crate) label: i32,

Expand Down
10 changes: 5 additions & 5 deletions src/svm/core/dense.rs
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ impl DenseSVM {
///
/// If the label was found its index returned in the [`Option`], otherwise `None`
/// is returned.
pub fn class_index_for_label(&self, label: i32) -> Option<usize> {
#[must_use] pub fn class_index_for_label(&self, label: i32) -> Option<usize> {
for (i, class) in self.classes.iter().enumerate() {
if class.label != label {
continue;
Expand All @@ -84,7 +84,7 @@ impl DenseSVM {
///
/// If the index was found it is returned in the [`Option`], otherwise `None`
/// is returned.
pub fn class_label_for_index(&self, index: usize) -> Option<i32> {
#[must_use] pub fn class_label_for_index(&self, index: usize) -> Option<i32> {
if index >= self.classes.len() {
None
} else {
Expand Down Expand Up @@ -132,10 +132,10 @@ impl DenseSVM {
}

/// Returns number of attributes, reflecting the libSVM model.
pub const fn attributes(&self) -> usize { self.num_attributes }
#[must_use] pub const fn attributes(&self) -> usize { self.num_attributes }

/// Returns number of classes, reflecting the libSVM model.
pub fn classes(&self) -> usize { self.classes.len() }
#[must_use] pub fn classes(&self) -> usize { self.classes.len() }
}

impl Predict<VecSimd<f32x8>> for DenseSVM {
Expand Down Expand Up @@ -173,7 +173,7 @@ impl<'a> TryFrom<&'a str> for DenseSVM {
}
}

impl<'a, 'b> TryFrom<&'a ModelFile<'b>> for DenseSVM {
impl<'a> TryFrom<&'a ModelFile<'_>> for DenseSVM {
type Error = Error;

fn try_from(raw_model: &'a ModelFile<'_>) -> Result<Self, Error> {
Expand Down
4 changes: 2 additions & 2 deletions src/svm/core/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -154,10 +154,10 @@ macro_rules! compute_multiclass_probabilities_impl {
let diff = (-qp[t] + pqp) / q[(t, t)];

probabilities[t] += diff;
pqp = (pqp + diff * (diff * q[(t, t)] + 2.0 * qp[t])) / (1.0 + diff) / (1.0 + diff);
pqp = diff.mul_add(diff.mul_add(q[(t, t)], 2.0 * qp[t]), pqp) / (1.0 + diff) / (1.0 + diff);

for j in 0 .. num_classes {
qp[j] = (qp[j] + diff * q[(t, j)]) / (1.0 + diff);
qp[j] = diff.mul_add(q[(t, j)], qp[j]) / (1.0 + diff);
probabilities[j] /= 1.0 + diff;
}
}
Expand Down
2 changes: 1 addition & 1 deletion src/svm/core/sparse.rs
Original file line number Diff line number Diff line change
Expand Up @@ -171,7 +171,7 @@ impl Predict<SparseVector<f32>> for SparseSVM {
fn predict_probability(&self, problem: &mut FeatureVector<SparseVector<f32>>) -> Result<(), Error> { predict_probability_impl!(self, problem) }
}

impl<'a, 'b> TryFrom<&'a str> for SparseSVM {
impl<'a> TryFrom<&'a str> for SparseSVM {
type Error = Error;

fn try_from(input: &'a str) -> Result<Self, Error> {
Expand Down
6 changes: 3 additions & 3 deletions src/svm/kernel/poly.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ impl KernelDense for Poly {
sum += *a * *b;
}

output[i] = crate::util::powi(f64::from(self.gamma * sum.sum() + self.coef0), self.degree);
output[i] = crate::util::powi(f64::from(self.gamma.mul_add(sum.sum(), self.coef0)), self.degree);
}
}
}
Expand All @@ -51,7 +51,7 @@ impl KernelSparse for Poly {
}
(Some((i_a, _)), Some((i_b, _))) if i_a < i_b => a = a_iter.next(),
(Some((i_a, _)), Some((i_b, _))) if i_a > i_b => b = b_iter.next(),
_ => break crate::util::powi(f64::from(self.gamma * sum + self.coef0), self.degree),
_ => break crate::util::powi(f64::from(self.gamma.mul_add(sum, self.coef0)), self.degree),
}
}
}
Expand All @@ -66,6 +66,6 @@ impl<'a, 'b> TryFrom<&'a ModelFile<'b>> for Poly {
let coef0 = raw_model.header().coef0.ok_or(Error::NoCoef0)?;
let degree = raw_model.header().degree.ok_or(Error::NoDegree)?;

Ok(Self { gamma, coef0, degree })
Ok(Self { degree, gamma, coef0 })
}
}
2 changes: 1 addition & 1 deletion src/svm/kernel/rbf.rs
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ fn compute(rbf: Rbf, vectors: &MatSimd<f32x8, Rows>, feature: &VecSimd<f32x8>, o
} else if is_x86_feature_detected!("avx") {
unsafe { compute_avx(rbf, vectors, feature, output) }
} else {
compute_core(rbf, vectors, feature, output)
compute_core(rbf, vectors, feature, output);
}
}

Expand Down
4 changes: 2 additions & 2 deletions src/svm/kernel/sigmoid.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ impl KernelDense for Sigmoid {
sum += *a * *b;
}

output[i] = (f64::from(self.gamma * sum.sum() + self.coef0)).tanh();
output[i] = (f64::from(self.gamma.mul_add(sum.sum(), self.coef0))).tanh();
}
}
}
Expand All @@ -50,7 +50,7 @@ impl KernelSparse for Sigmoid {
}
(Some((i_a, _)), Some((i_b, _))) if i_a < i_b => a = a_iter.next(),
(Some((i_a, _)), Some((i_b, _))) if i_a > i_b => b = b_iter.next(),
_ => break (f64::from(self.gamma * sum + self.coef0)).tanh(),
_ => break (f64::from(self.gamma.mul_add(sum, self.coef0))).tanh(),
}
}
}
Expand Down
12 changes: 6 additions & 6 deletions src/svm/mod.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
pub(crate) mod class;
pub(crate) mod core;
pub(crate) mod features;
pub(crate) mod kernel;
pub(crate) mod predict;
pub mod class;
pub mod core;
pub mod features;
pub mod kernel;
pub mod predict;

use crate::vectors::Triangular;

#[derive(Clone, Debug, Default)]
pub(crate) struct Probabilities {
pub struct Probabilities {
pub(crate) a: Triangular<f64>,

pub(crate) b: Triangular<f64>,
Expand Down
10 changes: 9 additions & 1 deletion src/svm/predict.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ use crate::{errors::Error, svm::features::FeatureVector};
/// }
/// ```
///
/// Predicting probabilities automatically predicts the best label. In addition [`FeatureVector::probabilities`]
/// Predicting probabilities automatically predicts the best label. In addition, [`FeatureVector::probabilities`]
/// will be updated accordingly. The class labels for each probablity entry can be obtained
/// by the SVM's `class_label_for_index` and `class_index_for_label` methods.
pub trait Predict<T>
Expand All @@ -43,12 +43,20 @@ where
///
/// The problem needs to have all features set. Once this method returns,
/// the [`FeatureVector::label`] will be set.
///
/// # Errors
///
/// Can fail if the feature vector didn't match the original SVM configuration.
fn predict_value(&self, problem: &mut FeatureVector<T>) -> Result<(), Error>;

/// Predict a probability value for a problem.
///
/// The problem needs to have all features set. Once this method returns,
/// both [`FeatureVector::label`] will be set, and all [`FeatureVector::probabilities`] will
/// be available accordingly.
///
/// # Errors
///
/// Can fail if the model was not trained with probability estimates support.
fn predict_probability(&self, problem: &mut FeatureVector<T>) -> Result<(), Error>;
}
4 changes: 2 additions & 2 deletions src/util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ where

/// As implemented in `libsvm`.
pub fn sigmoid_predict(decision_value: f64, a: f64, b: f64) -> f64 {
let fapb = decision_value * a + b;
let fapb = decision_value.mul_add(a, b);

// Citing from the original libSVM implementation:
// "1-p used later; avoid catastrophic cancellation"
Expand All @@ -47,7 +47,7 @@ pub fn powi(base: f64, times: u32) -> f64 {

while t > 0 {
if t % 2 == 1 {
ret *= tmp
ret *= tmp;
};

tmp = tmp * tmp;
Expand Down
2 changes: 1 addition & 1 deletion src/vectors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ where
}
}

impl<'a, T> From<&'a Vec<T>> for Triangular<T>
impl<T> From<&Vec<T>> for Triangular<T>
where
T: Copy + Sized,
{
Expand Down

0 comments on commit 083bae6

Please sign in to comment.