Implement abstract method to convert a slice to a BaseVector, Implement RealNumberVector over BaseVector instead of over Vec<T>

This commit is contained in:
Luis Moreno
2020-11-11 20:53:50 -04:00
parent 82464f41e4
commit 900078cb04
3 changed files with 22 additions and 9 deletions
+15
View File
@@ -83,6 +83,21 @@ pub trait BaseVector<T: RealNumber>: Clone + Debug {
self.len() == 0
}
/// Create a new vector from a &[T]
/// ```
/// use smartcore::linalg::naive::dense_matrix::*;
/// let slice: &[f64] = &[0., 0.5, 2., 3., 4.];
/// let a: Vec<f64> = BaseVector::from_slice(slice);
/// assert_eq!(a, vec![0., 0.5, 2., 3., 4.]);
/// ```
fn from_slice(f: &[T]) -> Self {
let mut v = Self::zeros(f.len());
for (i, elem) in f.iter().enumerate() {
v.set(i, *elem);
}
v
}
/// Return a vector with the elements of the one-dimensional array.
fn to_vec(&self) -> Vec<T>;
+6 -5
View File
@@ -1,13 +1,14 @@
use crate::math::num::RealNumber;
use std::collections::HashMap;
use crate::linalg::BaseVector;
pub trait RealNumberVector<T: RealNumber> {
fn unique(&self) -> (Vec<T>, Vec<usize>);
}
impl<T: RealNumber> RealNumberVector<T> for Vec<T> {
impl<T: RealNumber, V: BaseVector<T>> RealNumberVector<T> for V {
fn unique(&self) -> (Vec<T>, Vec<usize>) {
let mut unique = self.clone();
let mut unique = self.to_vec();
unique.sort_by(|a, b| a.partial_cmp(b).unwrap());
unique.dedup();
@@ -17,8 +18,8 @@ impl<T: RealNumber> RealNumberVector<T> for Vec<T> {
}
let mut unique_index = Vec::with_capacity(self.len());
for e in self {
unique_index.push(index[&e.to_i64().unwrap()]);
for idx in 0..self.len() {
unique_index.push(index[&self.get(idx).to_i64().unwrap()]);
}
(unique, unique_index)
@@ -27,7 +28,7 @@ impl<T: RealNumber> RealNumberVector<T> for Vec<T> {
#[cfg(test)]
mod tests {
use super::*;
use super::RealNumberVector;
#[test]
fn unique() {
+1 -4
View File
@@ -58,10 +58,7 @@ impl<T: RealNumber, M: Matrix<T>, D: NBDistribution<T, M>> BaseNaiveBayes<T, M,
*prediction
})
.collect::<Vec<T>>();
let mut y_hat = M::RowVector::zeros(rows);
for (i, prediction) in predictions.iter().enumerate().take(rows) {
y_hat.set(i, *prediction);
}
let y_hat = M::RowVector::from_slice(&predictions);
Ok(y_hat)
}
}