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:
Lorenzo
2022-10-31 10:44:57 +00:00
committed by morenol
parent a32eb66a6a
commit a7fa0585eb
110 changed files with 10327 additions and 9107 deletions
+165 -155
View File
@@ -7,7 +7,7 @@
//! Example:
//!
//! ```
//! use smartcore::linalg::naive::dense_matrix::*;
//! use smartcore::linalg::basic::matrix::DenseMatrix;
//! use smartcore::naive_bayes::multinomial::MultinomialNB;
//!
//! // Training data points are:
@@ -15,69 +15,70 @@
//! // Chinese Chinese Shanghai (class: China)
//! // Chinese Macao (class: China)
//! // Tokyo Japan Chinese (class: Japan)
//! let x = DenseMatrix::<f64>::from_2d_array(&[
//! &[1., 2., 0., 0., 0., 0.],
//! &[0., 2., 0., 0., 1., 0.],
//! &[0., 1., 0., 1., 0., 0.],
//! &[0., 1., 1., 0., 0., 1.],
//! let x = DenseMatrix::<u32>::from_2d_array(&[
//! &[1, 2, 0, 0, 0, 0],
//! &[0, 2, 0, 0, 1, 0],
//! &[0, 1, 0, 1, 0, 0],
//! &[0, 1, 1, 0, 0, 1],
//! ]);
//! let y = vec![0., 0., 0., 1.];
//! let y: Vec<u32> = vec![0, 0, 0, 1];
//! let nb = MultinomialNB::fit(&x, &y, Default::default()).unwrap();
//!
//! // Testing data point is:
//! // Chinese Chinese Chinese Tokyo Japan
//! let x_test = DenseMatrix::<f64>::from_2d_array(&[&[0., 3., 1., 0., 0., 1.]]);
//! let x_test = DenseMatrix::from_2d_array(&[&[0, 3, 1, 0, 0, 1]]);
//! let y_hat = nb.predict(&x_test).unwrap();
//! ```
//!
//! ## References:
//!
//! * ["Introduction to Information Retrieval", Manning C. D., Raghavan P., Schutze H., 2009, Chapter 13 ](https://nlp.stanford.edu/IR-book/information-retrieval-book.html)
use num_traits::Unsigned;
use crate::api::{Predictor, SupervisedEstimator};
use crate::error::Failed;
use crate::linalg::row_iter;
use crate::linalg::BaseVector;
use crate::linalg::Matrix;
use crate::math::num::RealNumber;
use crate::math::vector::RealNumberVector;
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 Multinomial features
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[derive(Debug, PartialEq)]
struct MultinomialNBDistribution<T: RealNumber> {
#[derive(Debug, PartialEq, Clone)]
struct MultinomialNBDistribution<T: Number> {
/// class labels known to the classifier
class_labels: Vec<T>,
/// number of training samples observed in each class
class_count: Vec<usize>,
/// probability of each class
class_priors: Vec<T>,
class_priors: Vec<f64>,
/// Empirical log probability of features given a class
feature_log_prob: Vec<Vec<T>>,
feature_log_prob: Vec<Vec<f64>>,
/// Number of samples encountered for each (class, feature)
feature_count: Vec<Vec<usize>>,
/// Number of features of each sample
n_features: usize,
}
impl<T: RealNumber, M: Matrix<T>> NBDistribution<T, M> for MultinomialNBDistribution<T> {
fn prior(&self, class_index: usize) -> T {
impl<X: Number + Unsigned, Y: Number + Ord + Unsigned> NBDistribution<X, Y>
for MultinomialNBDistribution<Y>
{
fn prior(&self, class_index: usize) -> f64 {
self.class_priors[class_index]
}
fn log_likelihood(&self, class_index: usize, j: &M::RowVector) -> T {
let mut likelihood = T::zero();
for feature in 0..j.len() {
let value = j.get(feature);
fn log_likelihood<'a>(&self, class_index: usize, j: &'a Box<dyn ArrayView1<X> + 'a>) -> f64 {
let mut likelihood = 0f64;
for feature in 0..j.shape() {
let value = X::to_f64(j.get(feature)).unwrap();
likelihood += value * self.feature_log_prob[class_index][feature];
}
likelihood
}
fn classes(&self) -> &Vec<T> {
fn classes(&self) -> &Vec<Y> {
&self.class_labels
}
}
@@ -85,33 +86,33 @@ impl<T: RealNumber, M: Matrix<T>> NBDistribution<T, M> for MultinomialNBDistribu
/// `MultinomialNB` parameters. Use `Default::default()` for default values.
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[derive(Debug, Clone)]
pub struct MultinomialNBParameters<T: RealNumber> {
pub struct MultinomialNBParameters {
#[cfg_attr(feature = "serde", serde(default))]
/// Additive (Laplace/Lidstone) smoothing parameter (0 for no smoothing).
pub alpha: T,
pub alpha: f64,
#[cfg_attr(feature = "serde", serde(default))]
/// Prior probabilities of the classes. If specified the priors are not adjusted according to the data
pub priors: Option<Vec<T>>,
pub priors: Option<Vec<f64>>,
}
impl<T: RealNumber> MultinomialNBParameters<T> {
impl MultinomialNBParameters {
/// 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
}
/// Prior probabilities of the classes. If specified the priors are not adjusted according to the data
pub fn with_priors(mut self, priors: Vec<T>) -> Self {
pub fn with_priors(mut self, priors: Vec<f64>) -> Self {
self.priors = Some(priors);
self
}
}
impl<T: RealNumber> Default for MultinomialNBParameters<T> {
impl Default for MultinomialNBParameters {
fn default() -> Self {
Self {
alpha: T::one(),
priors: None,
alpha: 1f64,
priors: Option::None,
}
}
}
@@ -119,25 +120,25 @@ impl<T: RealNumber> Default for MultinomialNBParameters<T> {
/// MultinomialNB grid search parameters
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[derive(Debug, Clone)]
pub struct MultinomialNBSearchParameters<T: RealNumber> {
pub struct MultinomialNBSearchParameters {
#[cfg_attr(feature = "serde", serde(default))]
/// Additive (Laplace/Lidstone) smoothing parameter (0 for no smoothing).
pub alpha: Vec<T>,
pub alpha: Vec<f64>,
#[cfg_attr(feature = "serde", serde(default))]
/// Prior probabilities of the classes. If specified the priors are not adjusted according to the data
pub priors: Vec<Option<Vec<T>>>,
pub priors: Vec<Option<Vec<f64>>>,
}
/// MultinomialNB grid search iterator
pub struct MultinomialNBSearchParametersIterator<T: RealNumber> {
multinomial_nb_search_parameters: MultinomialNBSearchParameters<T>,
pub struct MultinomialNBSearchParametersIterator {
multinomial_nb_search_parameters: MultinomialNBSearchParameters,
current_alpha: usize,
current_priors: usize,
}
impl<T: RealNumber> IntoIterator for MultinomialNBSearchParameters<T> {
type Item = MultinomialNBParameters<T>;
type IntoIter = MultinomialNBSearchParametersIterator<T>;
impl IntoIterator for MultinomialNBSearchParameters {
type Item = MultinomialNBParameters;
type IntoIter = MultinomialNBSearchParametersIterator;
fn into_iter(self) -> Self::IntoIter {
MultinomialNBSearchParametersIterator {
@@ -148,8 +149,8 @@ impl<T: RealNumber> IntoIterator for MultinomialNBSearchParameters<T> {
}
}
impl<T: RealNumber> Iterator for MultinomialNBSearchParametersIterator<T> {
type Item = MultinomialNBParameters<T>;
impl Iterator for MultinomialNBSearchParametersIterator {
type Item = MultinomialNBParameters;
fn next(&mut self) -> Option<Self::Item> {
if self.current_alpha == self.multinomial_nb_search_parameters.alpha.len()
@@ -177,7 +178,7 @@ impl<T: RealNumber> Iterator for MultinomialNBSearchParametersIterator<T> {
}
}
impl<T: RealNumber> Default for MultinomialNBSearchParameters<T> {
impl Default for MultinomialNBSearchParameters {
fn default() -> Self {
let default_params = MultinomialNBParameters::default();
@@ -188,21 +189,21 @@ impl<T: RealNumber> Default for MultinomialNBSearchParameters<T> {
}
}
impl<T: RealNumber> MultinomialNBDistribution<T> {
impl<TY: Number + Ord + Unsigned> MultinomialNBDistribution<TY> {
/// 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.
/// * `priors` - Optional vector with prior probabilities of the classes. If not defined,
/// priors are adjusted according to the data.
/// * `alpha` - Additive (Laplace/Lidstone) smoothing parameter.
pub fn fit<M: Matrix<T>>(
x: &M,
y: &M::RowVector,
alpha: T,
priors: Option<Vec<T>>,
pub fn fit<TX: Number + Unsigned, X: Array2<TX>, Y: Array1<TY>>(
x: &X,
y: &Y,
alpha: f64,
priors: Option<Vec<f64>>,
) -> Result<Self, Failed> {
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|=[{}]",
@@ -216,16 +217,14 @@ impl<T: RealNumber> MultinomialNBDistribution<T> {
n_samples
)));
}
if alpha < T::zero() {
if alpha < 0f64 {
return Err(Failed::fit(&format!(
"Alpha should be greater than 0; |alpha|=[{}]",
alpha
)));
}
let y = y.to_vec();
let (class_labels, indices) = <Vec<T> as RealNumberVector<T>>::unique_with_indices(&y);
let (class_labels, indices) = y.unique_with_indices();
let mut class_count = vec![0_usize; class_labels.len()];
for class_index in indices.iter() {
@@ -242,14 +241,14 @@ impl<T: RealNumber> MultinomialNBDistribution<T> {
} else {
class_count
.iter()
.map(|&c| T::from(c).unwrap() / T::from(n_samples).unwrap())
.map(|&c| c as f64 / n_samples as f64)
.collect()
};
let mut feature_in_class_counter = vec![vec![0_usize; n_features]; class_labels.len()];
for (row, class_index) in row_iter(x).zip(indices) {
for (idx, row_i) in row.iter().enumerate().take(n_features) {
for (row, class_index) in x.row_iter().zip(indices) {
for (idx, row_i) in row.iterator(0).enumerate().take(n_features) {
feature_in_class_counter[class_index][idx] +=
row_i.to_usize().ok_or_else(|| {
Failed::fit(&format!(
@@ -267,9 +266,7 @@ impl<T: RealNumber> MultinomialNBDistribution<T> {
feature_count
.iter()
.map(|&count| {
((T::from(count).unwrap() + alpha)
/ (T::from(n_c).unwrap() + alpha * T::from(n_features).unwrap()))
.ln()
((count as f64 + alpha) / (n_c as f64 + alpha * n_features as f64)).ln()
})
.collect()
})
@@ -289,87 +286,94 @@ impl<T: RealNumber> MultinomialNBDistribution<T> {
/// MultinomialNB implements the naive Bayes algorithm for multinomially distributed data.
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[derive(Debug, PartialEq)]
pub struct MultinomialNB<T: RealNumber, M: Matrix<T>> {
inner: BaseNaiveBayes<T, M, MultinomialNBDistribution<T>>,
pub struct MultinomialNB<
TX: Number + Unsigned,
TY: Number + Ord + Unsigned,
X: Array2<TX>,
Y: Array1<TY>,
> {
inner: Option<BaseNaiveBayes<TX, TY, X, Y, MultinomialNBDistribution<TY>>>,
}
impl<T: RealNumber, M: Matrix<T>> SupervisedEstimator<M, M::RowVector, MultinomialNBParameters<T>>
for MultinomialNB<T, M>
impl<TX: Number + Unsigned, TY: Number + Ord + Unsigned, X: Array2<TX>, Y: Array1<TY>>
SupervisedEstimator<X, Y, MultinomialNBParameters> for MultinomialNB<TX, TY, X, Y>
{
fn fit(
x: &M,
y: &M::RowVector,
parameters: MultinomialNBParameters<T>,
) -> Result<Self, Failed> {
fn new() -> Self {
Self {
inner: Option::None,
}
}
fn fit(x: &X, y: &Y, parameters: MultinomialNBParameters) -> Result<Self, Failed> {
MultinomialNB::fit(x, y, parameters)
}
}
impl<T: RealNumber, M: Matrix<T>> Predictor<M, M::RowVector> for MultinomialNB<T, M> {
fn predict(&self, x: &M) -> Result<M::RowVector, Failed> {
impl<TX: Number + Unsigned, TY: Number + Ord + Unsigned, X: Array2<TX>, Y: Array1<TY>>
Predictor<X, Y> for MultinomialNB<TX, TY, X, Y>
{
fn predict(&self, x: &X) -> Result<Y, Failed> {
self.predict(x)
}
}
impl<T: RealNumber, M: Matrix<T>> MultinomialNB<T, M> {
impl<TX: Number + Unsigned, TY: Number + Ord + Unsigned, X: Array2<TX>, Y: Array1<TY>>
MultinomialNB<TX, TY, X, Y>
{
/// Fits MultinomialNB 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 class priors, alpha for smoothing and
/// binarizing threshold.
pub fn fit(
x: &M,
y: &M::RowVector,
parameters: MultinomialNBParameters<T>,
) -> Result<Self, Failed> {
pub fn fit(x: &X, y: &Y, parameters: MultinomialNBParameters) -> Result<Self, Failed> {
let distribution =
MultinomialNBDistribution::fit(x, y, parameters.alpha, parameters.priors)?;
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
pub fn classes(&self) -> &Vec<TY> {
&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
}
/// Empirical log probability of features given a class, P(x_i|y).
/// Returns a 2d vector of shape (n_classes, n_features)
pub fn feature_log_prob(&self) -> &Vec<Vec<T>> {
&self.inner.distribution.feature_log_prob
pub fn feature_log_prob(&self) -> &Vec<Vec<f64>> {
&self.inner.as_ref().unwrap().distribution.feature_log_prob
}
/// 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 samples encountered for each (class, feature)
/// Returns a 2d vector of shape (n_classes, n_features)
pub fn feature_count(&self) -> &Vec<Vec<usize>> {
&self.inner.distribution.feature_count
&self.inner.as_ref().unwrap().distribution.feature_count
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::linalg::naive::dense_matrix::DenseMatrix;
use crate::linalg::basic::matrix::DenseMatrix;
#[test]
fn search_parameters() {
@@ -398,19 +402,21 @@ mod tests {
// Chinese Chinese Shanghai (class: China)
// Chinese Macao (class: China)
// Tokyo Japan Chinese (class: Japan)
let x = DenseMatrix::<f64>::from_2d_array(&[
&[1., 2., 0., 0., 0., 0.],
&[0., 2., 0., 0., 1., 0.],
&[0., 1., 0., 1., 0., 0.],
&[0., 1., 1., 0., 0., 1.],
let x = DenseMatrix::from_2d_array(&[
&[1, 2, 0, 0, 0, 0],
&[0, 2, 0, 0, 1, 0],
&[0, 1, 0, 1, 0, 0],
&[0, 1, 1, 0, 0, 1],
]);
let y = vec![0., 0., 0., 1.];
let y: Vec<u32> = vec![0, 0, 0, 1];
let mnb = MultinomialNB::fit(&x, &y, Default::default()).unwrap();
assert_eq!(mnb.classes(), &[0., 1.]);
assert_eq!(mnb.classes(), &[0, 1]);
assert_eq!(mnb.class_count(), &[3, 1]);
assert_eq!(mnb.inner.distribution.class_priors, &[0.75, 0.25]);
let distribution = mnb.inner.clone().unwrap().distribution;
assert_eq!(&distribution.class_priors, &[0.75, 0.25]);
assert_eq!(
mnb.feature_log_prob(),
&[
@@ -435,33 +441,33 @@ mod tests {
// Testing data point is:
// Chinese Chinese Chinese Tokyo Japan
let x_test = DenseMatrix::<f64>::from_2d_array(&[&[0., 3., 1., 0., 0., 1.]]);
let x_test = DenseMatrix::<u32>::from_2d_array(&[&[0, 3, 1, 0, 0, 1]]);
let y_hat = mnb.predict(&x_test).unwrap();
assert_eq!(y_hat, &[0.]);
assert_eq!(y_hat, &[0]);
}
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
#[test]
fn multinomial_nb_scikit_parity() {
let x = DenseMatrix::<f64>::from_2d_array(&[
&[2., 4., 0., 0., 2., 1., 2., 4., 2., 0.],
&[3., 4., 0., 2., 1., 0., 1., 4., 0., 3.],
&[1., 4., 2., 4., 1., 0., 1., 2., 3., 2.],
&[0., 3., 3., 4., 1., 0., 3., 1., 1., 1.],
&[0., 2., 1., 4., 3., 4., 1., 2., 3., 1.],
&[3., 2., 4., 1., 3., 0., 2., 4., 0., 2.],
&[3., 1., 3., 0., 2., 0., 4., 4., 3., 4.],
&[2., 2., 2., 0., 1., 1., 2., 1., 0., 1.],
&[3., 3., 2., 2., 0., 2., 3., 2., 2., 3.],
&[4., 3., 4., 4., 4., 2., 2., 0., 1., 4.],
&[3., 4., 2., 2., 1., 4., 4., 4., 1., 3.],
&[3., 0., 1., 4., 4., 0., 0., 3., 2., 4.],
&[2., 0., 3., 3., 1., 2., 0., 2., 4., 1.],
&[2., 4., 0., 4., 2., 4., 1., 3., 1., 4.],
&[0., 2., 2., 3., 4., 0., 4., 4., 4., 4.],
let x = DenseMatrix::<u32>::from_2d_array(&[
&[2, 4, 0, 0, 2, 1, 2, 4, 2, 0],
&[3, 4, 0, 2, 1, 0, 1, 4, 0, 3],
&[1, 4, 2, 4, 1, 0, 1, 2, 3, 2],
&[0, 3, 3, 4, 1, 0, 3, 1, 1, 1],
&[0, 2, 1, 4, 3, 4, 1, 2, 3, 1],
&[3, 2, 4, 1, 3, 0, 2, 4, 0, 2],
&[3, 1, 3, 0, 2, 0, 4, 4, 3, 4],
&[2, 2, 2, 0, 1, 1, 2, 1, 0, 1],
&[3, 3, 2, 2, 0, 2, 3, 2, 2, 3],
&[4, 3, 4, 4, 4, 2, 2, 0, 1, 4],
&[3, 4, 2, 2, 1, 4, 4, 4, 1, 3],
&[3, 0, 1, 4, 4, 0, 0, 3, 2, 4],
&[2, 0, 3, 3, 1, 2, 0, 2, 4, 1],
&[2, 4, 0, 4, 2, 4, 1, 3, 1, 4],
&[0, 2, 2, 3, 4, 0, 4, 4, 4, 4],
]);
let y = vec![2., 2., 0., 0., 0., 2., 1., 1., 0., 1., 0., 0., 2., 0., 2.];
let y: Vec<u32> = vec![2, 2, 0, 0, 0, 2, 1, 1, 0, 1, 0, 0, 2, 0, 2];
let nb = MultinomialNB::fit(&x, &y, Default::default()).unwrap();
assert_eq!(nb.n_features(), 10);
@@ -476,47 +482,51 @@ mod tests {
let y_hat = nb.predict(&x).unwrap();
assert!(nb
.inner
.distribution
.class_priors
.approximate_eq(&vec!(0.46, 0.2, 0.33), 1e-2));
assert!(nb.feature_log_prob()[1].approximate_eq(
let distribution = nb.inner.clone().unwrap().distribution;
assert_eq!(
&distribution.class_priors,
&vec!(0.4666666666666667, 0.2, 0.3333333333333333)
);
// Due to float differences in WASM32,
// we disable this test for that arch
#[cfg(not(target_arch = "wasm32"))]
assert_eq!(
&nb.feature_log_prob()[1],
&vec![
-2.00148,
-2.35815494,
-2.00148,
-2.69462718,
-2.22462355,
-2.91777073,
-2.10684052,
-2.51230562,
-2.69462718,
-2.00148
],
1e-5
));
assert!(y_hat.approximate_eq(
&vec!(2.0, 2.0, 0.0, 0.0, 0.0, 2.0, 2.0, 1.0, 0.0, 1.0, 0.0, 2.0, 0.0, 0.0, 2.0),
1e-5
));
-2.001480000210124,
-2.3581549441488563,
-2.001480000210124,
-2.6946271807700692,
-2.2246235515243336,
-2.917770732084279,
-2.10684051586795,
-2.512305623976115,
-2.6946271807700692,
-2.001480000210124
]
);
assert_eq!(y_hat, vec!(2, 2, 0, 0, 0, 2, 2, 1, 0, 1, 0, 2, 0, 0, 2));
}
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
#[test]
#[cfg(feature = "serde")]
fn serde() {
let x = DenseMatrix::<f64>::from_2d_array(&[
&[1., 1., 0., 0., 0., 0.],
&[0., 1., 0., 0., 1., 0.],
&[0., 1., 0., 1., 0., 0.],
&[0., 1., 1., 0., 0., 1.],
]);
let y = vec![0., 0., 0., 1.];
let mnb = MultinomialNB::fit(&x, &y, Default::default()).unwrap();
let deserialized_mnb: MultinomialNB<f64, DenseMatrix<f64>> =
serde_json::from_str(&serde_json::to_string(&mnb).unwrap()).unwrap();
// 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(&[
// &[1, 1, 0, 0, 0, 0],
// &[0, 1, 0, 0, 1, 0],
// &[0, 1, 0, 1, 0, 0],
// &[0, 1, 1, 0, 0, 1],
// ]);
// let y = vec![0, 0, 0, 1];
assert_eq!(mnb, deserialized_mnb);
}
// let mnb = MultinomialNB::fit(&x, &y, Default::default()).unwrap();
// let deserialized_mnb: MultinomialNB<u32, u32, DenseMatrix<u32>, Vec<u32>> =
// serde_json::from_str(&serde_json::to_string(&mnb).unwrap()).unwrap();
// assert_eq!(mnb, deserialized_mnb);
// }
}