Merge potential next release v0.4 (#187) Breaking Changes
* First draft of the new n-dimensional arrays + NB use case * Improves default implementation of multiple Array methods * Refactors tree methods * Adds matrix decomposition routines * Adds matrix decomposition methods to ndarray and nalgebra bindings * Refactoring + linear regression now uses array2 * Ridge & Linear regression * LBFGS optimizer & logistic regression * LBFGS optimizer & logistic regression * Changes linear methods, metrics and model selection methods to new n-dimensional arrays * Switches KNN and clustering algorithms to new n-d array layer * Refactors distance metrics * Optimizes knn and clustering methods * Refactors metrics module * Switches decomposition methods to n-dimensional arrays * Linalg refactoring - cleanup rng merge (#172) * Remove legacy DenseMatrix and BaseMatrix implementation. Port the new Number, FloatNumber and Array implementation into module structure. * Exclude AUC metrics. Needs reimplementation * Improve developers walkthrough New traits system in place at `src/numbers` and `src/linalg` Co-authored-by: Lorenzo <tunedconsulting@gmail.com> * Provide SupervisedEstimator with a constructor to avoid explicit dynamical box allocation in 'cross_validate' and 'cross_validate_predict' as required by the use of 'dyn' as per Rust 2021 * Implement getters to use as_ref() in src/neighbors * Implement getters to use as_ref() in src/naive_bayes * Implement getters to use as_ref() in src/linear * Add Clone to src/naive_bayes * Change signature for cross_validate and other model_selection functions to abide to use of dyn in Rust 2021 * Implement ndarray-bindings. Remove FloatNumber from implementations * Drop nalgebra-bindings support (as decided in conf-call to go for ndarray) * Remove benches. Benches will have their own repo at smartcore-benches * Implement SVC * Implement SVC serialization. Move search parameters in dedicated module * Implement SVR. Definitely too slow * Fix compilation issues for wasm (#202) Co-authored-by: Luis Moreno <morenol@users.noreply.github.com> * Fix tests (#203) * Port linalg/traits/stats.rs * Improve methods naming * Improve Display for DenseMatrix Co-authored-by: Montana Low <montanalow@users.noreply.github.com> Co-authored-by: VolodymyrOrlov <volodymyr.orlov@gmail.com>
This commit is contained in:
+160
-169
@@ -6,50 +6,51 @@
|
||||
//! Example:
|
||||
//!
|
||||
//! ```
|
||||
//! use smartcore::linalg::naive::dense_matrix::*;
|
||||
//! use smartcore::linalg::basic::matrix::DenseMatrix;
|
||||
//! use smartcore::naive_bayes::categorical::CategoricalNB;
|
||||
//!
|
||||
//! let x = DenseMatrix::from_2d_array(&[
|
||||
//! &[3., 4., 0., 1.],
|
||||
//! &[3., 0., 0., 1.],
|
||||
//! &[4., 4., 1., 2.],
|
||||
//! &[4., 2., 4., 3.],
|
||||
//! &[4., 2., 4., 2.],
|
||||
//! &[4., 1., 1., 0.],
|
||||
//! &[1., 1., 1., 1.],
|
||||
//! &[0., 4., 1., 0.],
|
||||
//! &[0., 3., 2., 1.],
|
||||
//! &[0., 3., 1., 1.],
|
||||
//! &[3., 4., 0., 1.],
|
||||
//! &[3., 4., 2., 4.],
|
||||
//! &[0., 3., 1., 2.],
|
||||
//! &[0., 4., 1., 2.],
|
||||
//! &[3, 4, 0, 1],
|
||||
//! &[3, 0, 0, 1],
|
||||
//! &[4, 4, 1, 2],
|
||||
//! &[4, 2, 4, 3],
|
||||
//! &[4, 2, 4, 2],
|
||||
//! &[4, 1, 1, 0],
|
||||
//! &[1, 1, 1, 1],
|
||||
//! &[0, 4, 1, 0],
|
||||
//! &[0, 3, 2, 1],
|
||||
//! &[0, 3, 1, 1],
|
||||
//! &[3, 4, 0, 1],
|
||||
//! &[3, 4, 2, 4],
|
||||
//! &[0, 3, 1, 2],
|
||||
//! &[0, 4, 1, 2],
|
||||
//! ]);
|
||||
//! let y = vec![0., 0., 1., 1., 1., 0., 1., 0., 1., 1., 1., 1., 1., 0.];
|
||||
//! let y: Vec<u32> = vec![0, 0, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 0];
|
||||
//!
|
||||
//! let nb = CategoricalNB::fit(&x, &y, Default::default()).unwrap();
|
||||
//! let y_hat = nb.predict(&x).unwrap();
|
||||
//! ```
|
||||
use num_traits::Unsigned;
|
||||
|
||||
use crate::api::{Predictor, SupervisedEstimator};
|
||||
use crate::error::Failed;
|
||||
use crate::linalg::BaseVector;
|
||||
use crate::linalg::Matrix;
|
||||
use crate::math::num::RealNumber;
|
||||
use crate::linalg::basic::arrays::{Array1, Array2, ArrayView1};
|
||||
use crate::naive_bayes::{BaseNaiveBayes, NBDistribution};
|
||||
use crate::numbers::basenum::Number;
|
||||
#[cfg(feature = "serde")]
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Naive Bayes classifier for categorical features
|
||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||
#[derive(Debug)]
|
||||
struct CategoricalNBDistribution<T: RealNumber> {
|
||||
#[derive(Debug, Clone)]
|
||||
struct CategoricalNBDistribution<T: Number + Unsigned> {
|
||||
/// number of training samples observed in each class
|
||||
class_count: Vec<usize>,
|
||||
/// class labels known to the classifier
|
||||
class_labels: Vec<T>,
|
||||
/// probability of each class
|
||||
class_priors: Vec<T>,
|
||||
coefficients: Vec<Vec<Vec<T>>>,
|
||||
class_priors: Vec<f64>,
|
||||
coefficients: Vec<Vec<Vec<f64>>>,
|
||||
/// Number of features of each sample
|
||||
n_features: usize,
|
||||
/// Number of categories for each feature
|
||||
@@ -60,7 +61,7 @@ struct CategoricalNBDistribution<T: RealNumber> {
|
||||
category_count: Vec<Vec<Vec<usize>>>,
|
||||
}
|
||||
|
||||
impl<T: RealNumber> PartialEq for CategoricalNBDistribution<T> {
|
||||
impl<T: Number + Unsigned> PartialEq for CategoricalNBDistribution<T> {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
if self.class_labels == other.class_labels
|
||||
&& self.class_priors == other.class_priors
|
||||
@@ -80,7 +81,7 @@ impl<T: RealNumber> PartialEq for CategoricalNBDistribution<T> {
|
||||
return false;
|
||||
}
|
||||
for (a_i_j, b_i_j) in a_i.iter().zip(b_i.iter()) {
|
||||
if (*a_i_j - *b_i_j).abs() > T::epsilon() {
|
||||
if (*a_i_j - *b_i_j).abs() > std::f64::EPSILON {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -93,29 +94,29 @@ impl<T: RealNumber> PartialEq for CategoricalNBDistribution<T> {
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: RealNumber, M: Matrix<T>> NBDistribution<T, M> for CategoricalNBDistribution<T> {
|
||||
fn prior(&self, class_index: usize) -> T {
|
||||
impl<T: Number + Unsigned> NBDistribution<T, T> for CategoricalNBDistribution<T> {
|
||||
fn prior(&self, class_index: usize) -> f64 {
|
||||
if class_index >= self.class_labels.len() {
|
||||
T::zero()
|
||||
0f64
|
||||
} else {
|
||||
self.class_priors[class_index]
|
||||
}
|
||||
}
|
||||
|
||||
fn log_likelihood(&self, class_index: usize, j: &M::RowVector) -> T {
|
||||
fn log_likelihood<'a>(&'a self, class_index: usize, j: &'a Box<dyn ArrayView1<T> + 'a>) -> f64 {
|
||||
if class_index < self.class_labels.len() {
|
||||
let mut likelihood = T::zero();
|
||||
for feature in 0..j.len() {
|
||||
let value = j.get(feature).floor().to_usize().unwrap();
|
||||
let mut likelihood = 0f64;
|
||||
for feature in 0..j.shape() {
|
||||
let value = j.get(feature).to_usize().unwrap();
|
||||
if self.coefficients[feature][class_index].len() > value {
|
||||
likelihood += self.coefficients[feature][class_index][value];
|
||||
} else {
|
||||
return T::zero();
|
||||
return 0f64;
|
||||
}
|
||||
}
|
||||
likelihood
|
||||
} else {
|
||||
T::zero()
|
||||
0f64
|
||||
}
|
||||
}
|
||||
|
||||
@@ -124,13 +125,13 @@ impl<T: RealNumber, M: Matrix<T>> NBDistribution<T, M> for CategoricalNBDistribu
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: RealNumber> CategoricalNBDistribution<T> {
|
||||
impl<T: Number + Unsigned> CategoricalNBDistribution<T> {
|
||||
/// Fits the distribution to a NxM matrix where N is number of samples and M is number of features.
|
||||
/// * `x` - training data.
|
||||
/// * `y` - vector with target values (classes) of length N.
|
||||
/// * `alpha` - Additive (Laplace/Lidstone) smoothing parameter (0 for no smoothing).
|
||||
pub fn fit<M: Matrix<T>>(x: &M, y: &M::RowVector, alpha: T) -> Result<Self, Failed> {
|
||||
if alpha < T::zero() {
|
||||
pub fn fit<X: Array2<T>, Y: Array1<T>>(x: &X, y: &Y, alpha: f64) -> Result<Self, Failed> {
|
||||
if alpha < 0f64 {
|
||||
return Err(Failed::fit(&format!(
|
||||
"alpha should be >= 0, alpha=[{}]",
|
||||
alpha
|
||||
@@ -138,7 +139,7 @@ impl<T: RealNumber> CategoricalNBDistribution<T> {
|
||||
}
|
||||
|
||||
let (n_samples, n_features) = x.shape();
|
||||
let y_samples = y.len();
|
||||
let y_samples = y.shape();
|
||||
if y_samples != n_samples {
|
||||
return Err(Failed::fit(&format!(
|
||||
"Size of x should equal size of y; |x|=[{}], |y|=[{}]",
|
||||
@@ -152,11 +153,7 @@ impl<T: RealNumber> CategoricalNBDistribution<T> {
|
||||
n_samples
|
||||
)));
|
||||
}
|
||||
let y: Vec<usize> = y
|
||||
.to_vec()
|
||||
.iter()
|
||||
.map(|y_i| y_i.floor().to_usize().unwrap())
|
||||
.collect();
|
||||
let y: Vec<usize> = y.iterator(0).map(|y_i| y_i.to_usize().unwrap()).collect();
|
||||
|
||||
let y_max = y
|
||||
.iter()
|
||||
@@ -164,7 +161,7 @@ impl<T: RealNumber> CategoricalNBDistribution<T> {
|
||||
.ok_or_else(|| Failed::fit("Failed to get the labels of y."))?;
|
||||
|
||||
let class_labels: Vec<T> = (0..*y_max + 1)
|
||||
.map(|label| T::from(label).unwrap())
|
||||
.map(|label| T::from_usize(label).unwrap())
|
||||
.collect();
|
||||
let mut class_count = vec![0_usize; class_labels.len()];
|
||||
for elem in y.iter() {
|
||||
@@ -174,9 +171,9 @@ impl<T: RealNumber> CategoricalNBDistribution<T> {
|
||||
let mut n_categories: Vec<usize> = Vec::with_capacity(n_features);
|
||||
for feature in 0..n_features {
|
||||
let feature_max = x
|
||||
.get_col_as_vec(feature)
|
||||
.iter()
|
||||
.map(|f_i| f_i.floor().to_usize().unwrap())
|
||||
.get_col(feature)
|
||||
.iterator(0)
|
||||
.map(|f_i| f_i.to_usize().unwrap())
|
||||
.max()
|
||||
.ok_or_else(|| {
|
||||
Failed::fit(&format!(
|
||||
@@ -187,34 +184,32 @@ impl<T: RealNumber> CategoricalNBDistribution<T> {
|
||||
n_categories.push(feature_max + 1);
|
||||
}
|
||||
|
||||
let mut coefficients: Vec<Vec<Vec<T>>> = Vec::with_capacity(class_labels.len());
|
||||
let mut coefficients: Vec<Vec<Vec<f64>>> = Vec::with_capacity(class_labels.len());
|
||||
let mut category_count: Vec<Vec<Vec<usize>>> = Vec::with_capacity(class_labels.len());
|
||||
for (feature_index, &n_categories_i) in n_categories.iter().enumerate().take(n_features) {
|
||||
let mut coef_i: Vec<Vec<T>> = Vec::with_capacity(n_features);
|
||||
let mut coef_i: Vec<Vec<f64>> = Vec::with_capacity(n_features);
|
||||
let mut category_count_i: Vec<Vec<usize>> = Vec::with_capacity(n_features);
|
||||
for (label, &label_count) in class_labels.iter().zip(class_count.iter()) {
|
||||
let col = x
|
||||
.get_col_as_vec(feature_index)
|
||||
.iter()
|
||||
.get_col(feature_index)
|
||||
.iterator(0)
|
||||
.enumerate()
|
||||
.filter(|(i, _j)| T::from(y[*i]).unwrap() == *label)
|
||||
.filter(|(i, _j)| T::from_usize(y[*i]).unwrap() == *label)
|
||||
.map(|(_, j)| *j)
|
||||
.collect::<Vec<T>>();
|
||||
let mut feat_count: Vec<usize> = vec![0_usize; n_categories_i];
|
||||
for row in col.iter() {
|
||||
let index = row.floor().to_usize().unwrap();
|
||||
let index = row.to_usize().unwrap();
|
||||
feat_count[index] += 1;
|
||||
}
|
||||
|
||||
let coef_i_j = feat_count
|
||||
.iter()
|
||||
.map(|c| {
|
||||
((T::from(*c).unwrap() + alpha)
|
||||
/ (T::from(label_count).unwrap()
|
||||
+ T::from(n_categories_i).unwrap() * alpha))
|
||||
.map(|&c| {
|
||||
((c as f64 + alpha) / (label_count as f64 + n_categories_i as f64 * alpha))
|
||||
.ln()
|
||||
})
|
||||
.collect::<Vec<T>>();
|
||||
.collect::<Vec<f64>>();
|
||||
category_count_i.push(feat_count);
|
||||
coef_i.push(coef_i_j);
|
||||
}
|
||||
@@ -224,8 +219,8 @@ impl<T: RealNumber> CategoricalNBDistribution<T> {
|
||||
|
||||
let class_priors = class_count
|
||||
.iter()
|
||||
.map(|&count| T::from(count).unwrap() / T::from(n_samples).unwrap())
|
||||
.collect::<Vec<T>>();
|
||||
.map(|&count| count as f64 / n_samples as f64)
|
||||
.collect::<Vec<f64>>();
|
||||
|
||||
Ok(Self {
|
||||
class_count,
|
||||
@@ -242,44 +237,44 @@ impl<T: RealNumber> CategoricalNBDistribution<T> {
|
||||
/// `CategoricalNB` parameters. Use `Default::default()` for default values.
|
||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct CategoricalNBParameters<T: RealNumber> {
|
||||
pub struct CategoricalNBParameters {
|
||||
#[cfg_attr(feature = "serde", serde(default))]
|
||||
/// Additive (Laplace/Lidstone) smoothing parameter (0 for no smoothing).
|
||||
pub alpha: T,
|
||||
pub alpha: f64,
|
||||
}
|
||||
|
||||
impl<T: RealNumber> CategoricalNBParameters<T> {
|
||||
impl CategoricalNBParameters {
|
||||
/// Additive (Laplace/Lidstone) smoothing parameter (0 for no smoothing).
|
||||
pub fn with_alpha(mut self, alpha: T) -> Self {
|
||||
pub fn with_alpha(mut self, alpha: f64) -> Self {
|
||||
self.alpha = alpha;
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: RealNumber> Default for CategoricalNBParameters<T> {
|
||||
impl Default for CategoricalNBParameters {
|
||||
fn default() -> Self {
|
||||
Self { alpha: T::one() }
|
||||
Self { alpha: 1f64 }
|
||||
}
|
||||
}
|
||||
|
||||
/// CategoricalNB grid search parameters
|
||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct CategoricalNBSearchParameters<T: RealNumber> {
|
||||
pub struct CategoricalNBSearchParameters {
|
||||
#[cfg_attr(feature = "serde", serde(default))]
|
||||
/// Additive (Laplace/Lidstone) smoothing parameter (0 for no smoothing).
|
||||
pub alpha: Vec<T>,
|
||||
pub alpha: Vec<f64>,
|
||||
}
|
||||
|
||||
/// CategoricalNB grid search iterator
|
||||
pub struct CategoricalNBSearchParametersIterator<T: RealNumber> {
|
||||
categorical_nb_search_parameters: CategoricalNBSearchParameters<T>,
|
||||
pub struct CategoricalNBSearchParametersIterator {
|
||||
categorical_nb_search_parameters: CategoricalNBSearchParameters,
|
||||
current_alpha: usize,
|
||||
}
|
||||
|
||||
impl<T: RealNumber> IntoIterator for CategoricalNBSearchParameters<T> {
|
||||
type Item = CategoricalNBParameters<T>;
|
||||
type IntoIter = CategoricalNBSearchParametersIterator<T>;
|
||||
impl IntoIterator for CategoricalNBSearchParameters {
|
||||
type Item = CategoricalNBParameters;
|
||||
type IntoIter = CategoricalNBSearchParametersIterator;
|
||||
|
||||
fn into_iter(self) -> Self::IntoIter {
|
||||
CategoricalNBSearchParametersIterator {
|
||||
@@ -289,8 +284,8 @@ impl<T: RealNumber> IntoIterator for CategoricalNBSearchParameters<T> {
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: RealNumber> Iterator for CategoricalNBSearchParametersIterator<T> {
|
||||
type Item = CategoricalNBParameters<T>;
|
||||
impl Iterator for CategoricalNBSearchParametersIterator {
|
||||
type Item = CategoricalNBParameters;
|
||||
|
||||
fn next(&mut self) -> Option<Self::Item> {
|
||||
if self.current_alpha == self.categorical_nb_search_parameters.alpha.len() {
|
||||
@@ -307,7 +302,7 @@ impl<T: RealNumber> Iterator for CategoricalNBSearchParametersIterator<T> {
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: RealNumber> Default for CategoricalNBSearchParameters<T> {
|
||||
impl Default for CategoricalNBSearchParameters {
|
||||
fn default() -> Self {
|
||||
let default_params = CategoricalNBParameters::default();
|
||||
|
||||
@@ -320,92 +315,90 @@ impl<T: RealNumber> Default for CategoricalNBSearchParameters<T> {
|
||||
/// CategoricalNB implements the categorical naive Bayes algorithm for categorically distributed data.
|
||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||
#[derive(Debug, PartialEq)]
|
||||
pub struct CategoricalNB<T: RealNumber, M: Matrix<T>> {
|
||||
inner: BaseNaiveBayes<T, M, CategoricalNBDistribution<T>>,
|
||||
pub struct CategoricalNB<T: Number + Unsigned, X: Array2<T>, Y: Array1<T>> {
|
||||
inner: Option<BaseNaiveBayes<T, T, X, Y, CategoricalNBDistribution<T>>>,
|
||||
}
|
||||
|
||||
impl<T: RealNumber, M: Matrix<T>> SupervisedEstimator<M, M::RowVector, CategoricalNBParameters<T>>
|
||||
for CategoricalNB<T, M>
|
||||
impl<T: Number + Unsigned, X: Array2<T>, Y: Array1<T>>
|
||||
SupervisedEstimator<X, Y, CategoricalNBParameters> for CategoricalNB<T, X, Y>
|
||||
{
|
||||
fn fit(
|
||||
x: &M,
|
||||
y: &M::RowVector,
|
||||
parameters: CategoricalNBParameters<T>,
|
||||
) -> Result<Self, Failed> {
|
||||
fn new() -> Self {
|
||||
Self {
|
||||
inner: Option::None,
|
||||
}
|
||||
}
|
||||
|
||||
fn fit(x: &X, y: &Y, parameters: CategoricalNBParameters) -> Result<Self, Failed> {
|
||||
CategoricalNB::fit(x, y, parameters)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: RealNumber, M: Matrix<T>> Predictor<M, M::RowVector> for CategoricalNB<T, M> {
|
||||
fn predict(&self, x: &M) -> Result<M::RowVector, Failed> {
|
||||
impl<T: Number + Unsigned, X: Array2<T>, Y: Array1<T>> Predictor<X, Y> for CategoricalNB<T, X, Y> {
|
||||
fn predict(&self, x: &X) -> Result<Y, Failed> {
|
||||
self.predict(x)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: RealNumber, M: Matrix<T>> CategoricalNB<T, M> {
|
||||
impl<T: Number + Unsigned, X: Array2<T>, Y: Array1<T>> CategoricalNB<T, X, Y> {
|
||||
/// Fits CategoricalNB with given data
|
||||
/// * `x` - training data of size NxM where N is the number of samples and M is the number of
|
||||
/// features.
|
||||
/// * `y` - vector with target values (classes) of length N.
|
||||
/// * `parameters` - additional parameters like alpha for smoothing
|
||||
pub fn fit(
|
||||
x: &M,
|
||||
y: &M::RowVector,
|
||||
parameters: CategoricalNBParameters<T>,
|
||||
) -> Result<Self, Failed> {
|
||||
pub fn fit(x: &X, y: &Y, parameters: CategoricalNBParameters) -> Result<Self, Failed> {
|
||||
let alpha = parameters.alpha;
|
||||
let distribution = CategoricalNBDistribution::fit(x, y, alpha)?;
|
||||
let inner = BaseNaiveBayes::fit(distribution)?;
|
||||
Ok(Self { inner })
|
||||
Ok(Self { inner: Some(inner) })
|
||||
}
|
||||
|
||||
/// Estimates the class labels for the provided data.
|
||||
/// * `x` - data of shape NxM where N is number of data points to estimate and M is number of features.
|
||||
/// Returns a vector of size N with class estimates.
|
||||
pub fn predict(&self, x: &M) -> Result<M::RowVector, Failed> {
|
||||
self.inner.predict(x)
|
||||
pub fn predict(&self, x: &X) -> Result<Y, Failed> {
|
||||
self.inner.as_ref().unwrap().predict(x)
|
||||
}
|
||||
|
||||
/// Class labels known to the classifier.
|
||||
/// Returns a vector of size n_classes.
|
||||
pub fn classes(&self) -> &Vec<T> {
|
||||
&self.inner.distribution.class_labels
|
||||
&self.inner.as_ref().unwrap().distribution.class_labels
|
||||
}
|
||||
|
||||
/// Number of training samples observed in each class.
|
||||
/// Returns a vector of size n_classes.
|
||||
pub fn class_count(&self) -> &Vec<usize> {
|
||||
&self.inner.distribution.class_count
|
||||
&self.inner.as_ref().unwrap().distribution.class_count
|
||||
}
|
||||
|
||||
/// Number of features of each sample
|
||||
pub fn n_features(&self) -> usize {
|
||||
self.inner.distribution.n_features
|
||||
self.inner.as_ref().unwrap().distribution.n_features
|
||||
}
|
||||
|
||||
/// Number of features of each sample
|
||||
pub fn n_categories(&self) -> &Vec<usize> {
|
||||
&self.inner.distribution.n_categories
|
||||
&self.inner.as_ref().unwrap().distribution.n_categories
|
||||
}
|
||||
|
||||
/// Holds arrays of shape (n_classes, n_categories of respective feature)
|
||||
/// for each feature. Each array provides the number of samples
|
||||
/// encountered for each class and category of the specific feature.
|
||||
pub fn category_count(&self) -> &Vec<Vec<Vec<usize>>> {
|
||||
&self.inner.distribution.category_count
|
||||
&self.inner.as_ref().unwrap().distribution.category_count
|
||||
}
|
||||
/// Holds arrays of shape (n_classes, n_categories of respective feature)
|
||||
/// for each feature. Each array provides the empirical log probability
|
||||
/// of categories given the respective feature and class, ``P(x_i|y)``.
|
||||
pub fn feature_log_prob(&self) -> &Vec<Vec<Vec<T>>> {
|
||||
&self.inner.distribution.coefficients
|
||||
pub fn feature_log_prob(&self) -> &Vec<Vec<Vec<f64>>> {
|
||||
&self.inner.as_ref().unwrap().distribution.coefficients
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::linalg::naive::dense_matrix::DenseMatrix;
|
||||
use crate::linalg::basic::matrix::DenseMatrix;
|
||||
|
||||
#[test]
|
||||
fn search_parameters() {
|
||||
@@ -424,28 +417,28 @@ mod tests {
|
||||
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
|
||||
#[test]
|
||||
fn run_categorical_naive_bayes() {
|
||||
let x = DenseMatrix::from_2d_array(&[
|
||||
&[0., 2., 1., 0.],
|
||||
&[0., 2., 1., 1.],
|
||||
&[1., 2., 1., 0.],
|
||||
&[2., 1., 1., 0.],
|
||||
&[2., 0., 0., 0.],
|
||||
&[2., 0., 0., 1.],
|
||||
&[1., 0., 0., 1.],
|
||||
&[0., 1., 1., 0.],
|
||||
&[0., 0., 0., 0.],
|
||||
&[2., 1., 0., 0.],
|
||||
&[0., 1., 0., 1.],
|
||||
&[1., 1., 1., 1.],
|
||||
&[1., 2., 0., 0.],
|
||||
&[2., 1., 1., 1.],
|
||||
let x = DenseMatrix::<u32>::from_2d_array(&[
|
||||
&[0, 2, 1, 0],
|
||||
&[0, 2, 1, 1],
|
||||
&[1, 2, 1, 0],
|
||||
&[2, 1, 1, 0],
|
||||
&[2, 0, 0, 0],
|
||||
&[2, 0, 0, 1],
|
||||
&[1, 0, 0, 1],
|
||||
&[0, 1, 1, 0],
|
||||
&[0, 0, 0, 0],
|
||||
&[2, 1, 0, 0],
|
||||
&[0, 1, 0, 1],
|
||||
&[1, 1, 1, 1],
|
||||
&[1, 2, 0, 0],
|
||||
&[2, 1, 1, 1],
|
||||
]);
|
||||
let y = vec![0., 0., 1., 1., 1., 0., 1., 0., 1., 1., 1., 1., 1., 0.];
|
||||
let y: Vec<u32> = vec![0, 0, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 0];
|
||||
|
||||
let cnb = CategoricalNB::fit(&x, &y, Default::default()).unwrap();
|
||||
|
||||
// checking parity with scikit
|
||||
assert_eq!(cnb.classes(), &[0., 1.]);
|
||||
assert_eq!(cnb.classes(), &[0, 1]);
|
||||
assert_eq!(cnb.class_count(), &[5, 9]);
|
||||
assert_eq!(cnb.n_features(), 4);
|
||||
assert_eq!(cnb.n_categories(), &[3, 3, 2, 2]);
|
||||
@@ -497,67 +490,65 @@ mod tests {
|
||||
]
|
||||
);
|
||||
|
||||
let x_test = DenseMatrix::from_2d_array(&[&[0., 2., 1., 0.], &[2., 2., 0., 0.]]);
|
||||
let x_test = DenseMatrix::from_2d_array(&[&[0, 2, 1, 0], &[2, 2, 0, 0]]);
|
||||
let y_hat = cnb.predict(&x_test).unwrap();
|
||||
assert_eq!(y_hat, vec![0., 1.]);
|
||||
assert_eq!(y_hat, vec![0, 1]);
|
||||
}
|
||||
|
||||
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
|
||||
#[test]
|
||||
fn run_categorical_naive_bayes2() {
|
||||
let x = DenseMatrix::from_2d_array(&[
|
||||
&[3., 4., 0., 1.],
|
||||
&[3., 0., 0., 1.],
|
||||
&[4., 4., 1., 2.],
|
||||
&[4., 2., 4., 3.],
|
||||
&[4., 2., 4., 2.],
|
||||
&[4., 1., 1., 0.],
|
||||
&[1., 1., 1., 1.],
|
||||
&[0., 4., 1., 0.],
|
||||
&[0., 3., 2., 1.],
|
||||
&[0., 3., 1., 1.],
|
||||
&[3., 4., 0., 1.],
|
||||
&[3., 4., 2., 4.],
|
||||
&[0., 3., 1., 2.],
|
||||
&[0., 4., 1., 2.],
|
||||
let x = DenseMatrix::<u32>::from_2d_array(&[
|
||||
&[3, 4, 0, 1],
|
||||
&[3, 0, 0, 1],
|
||||
&[4, 4, 1, 2],
|
||||
&[4, 2, 4, 3],
|
||||
&[4, 2, 4, 2],
|
||||
&[4, 1, 1, 0],
|
||||
&[1, 1, 1, 1],
|
||||
&[0, 4, 1, 0],
|
||||
&[0, 3, 2, 1],
|
||||
&[0, 3, 1, 1],
|
||||
&[3, 4, 0, 1],
|
||||
&[3, 4, 2, 4],
|
||||
&[0, 3, 1, 2],
|
||||
&[0, 4, 1, 2],
|
||||
]);
|
||||
let y = vec![0., 0., 1., 1., 1., 0., 1., 0., 1., 1., 1., 1., 1., 0.];
|
||||
let y: Vec<u32> = vec![0, 0, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 0];
|
||||
|
||||
let cnb = CategoricalNB::fit(&x, &y, Default::default()).unwrap();
|
||||
let y_hat = cnb.predict(&x).unwrap();
|
||||
assert_eq!(
|
||||
y_hat,
|
||||
vec![0., 0., 1., 1., 1., 0., 1., 0., 1., 1., 0., 1., 1., 1.]
|
||||
);
|
||||
assert_eq!(y_hat, vec![0, 0, 1, 1, 1, 0, 1, 0, 1, 1, 0, 1, 1, 1]);
|
||||
}
|
||||
|
||||
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
|
||||
#[test]
|
||||
#[cfg(feature = "serde")]
|
||||
fn serde() {
|
||||
let x = DenseMatrix::<f64>::from_2d_array(&[
|
||||
&[3., 4., 0., 1.],
|
||||
&[3., 0., 0., 1.],
|
||||
&[4., 4., 1., 2.],
|
||||
&[4., 2., 4., 3.],
|
||||
&[4., 2., 4., 2.],
|
||||
&[4., 1., 1., 0.],
|
||||
&[1., 1., 1., 1.],
|
||||
&[0., 4., 1., 0.],
|
||||
&[0., 3., 2., 1.],
|
||||
&[0., 3., 1., 1.],
|
||||
&[3., 4., 0., 1.],
|
||||
&[3., 4., 2., 4.],
|
||||
&[0., 3., 1., 2.],
|
||||
&[0., 4., 1., 2.],
|
||||
]);
|
||||
// TODO: implement serialization
|
||||
// #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
|
||||
// #[test]
|
||||
// #[cfg(feature = "serde")]
|
||||
// fn serde() {
|
||||
// let x = DenseMatrix::from_2d_array(&[
|
||||
// &[3, 4, 0, 1],
|
||||
// &[3, 0, 0, 1],
|
||||
// &[4, 4, 1, 2],
|
||||
// &[4, 2, 4, 3],
|
||||
// &[4, 2, 4, 2],
|
||||
// &[4, 1, 1, 0],
|
||||
// &[1, 1, 1, 1],
|
||||
// &[0, 4, 1, 0],
|
||||
// &[0, 3, 2, 1],
|
||||
// &[0, 3, 1, 1],
|
||||
// &[3, 4, 0, 1],
|
||||
// &[3, 4, 2, 4],
|
||||
// &[0, 3, 1, 2],
|
||||
// &[0, 4, 1, 2],
|
||||
// ]);
|
||||
|
||||
let y = vec![0., 0., 1., 1., 1., 0., 1., 0., 1., 1., 1., 1., 1., 0.];
|
||||
let cnb = CategoricalNB::fit(&x, &y, Default::default()).unwrap();
|
||||
// let y: Vec<u32> = vec![0, 0, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 0];
|
||||
// let cnb = CategoricalNB::fit(&x, &y, Default::default()).unwrap();
|
||||
|
||||
let deserialized_cnb: CategoricalNB<f64, DenseMatrix<f64>> =
|
||||
serde_json::from_str(&serde_json::to_string(&cnb).unwrap()).unwrap();
|
||||
// let deserialized_cnb: CategoricalNB<u32, DenseMatrix<u32>, Vec<u32>> =
|
||||
// serde_json::from_str(&serde_json::to_string(&cnb).unwrap()).unwrap();
|
||||
|
||||
assert_eq!(cnb, deserialized_cnb);
|
||||
}
|
||||
// assert_eq!(cnb, deserialized_cnb);
|
||||
// }
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user