Skip to content
This repository has been archived by the owner on Jul 16, 2021. It is now read-only.

Update rand to 0.7 and add wasm-bindgen feature enabling corresponding rand feature #205

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,10 @@ license = "MIT"
[features]
stats = []
datasets = []
wasm-bindgen = ["rand/wasm-bindgen"]

[dependencies]
num = { version = "0.1.41", default-features = false }
rand = "0.4.1"
rand = "0.7"
rand_distr = "0.2"
rulinalg = { git = "https://github.com/AtheMathmo/rulinalg", rev = "1ed8b937" }
8 changes: 4 additions & 4 deletions examples/k-means_generating_cluster.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
extern crate rusty_machine;
extern crate rand;
extern crate rand_distr;

use rusty_machine::linalg::{Matrix, BaseMatrix};
use rusty_machine::learning::k_means::KMeansClassifier;
use rusty_machine::learning::UnSupModel;

use rand::thread_rng;
use rand::distributions::IndependentSample;
use rand::distributions::normal::Normal;
use rand_distr::{Distribution, Normal};

fn generate_data(centroids: &Matrix<f64>,
points_per_centroid: usize,
Expand All @@ -20,15 +20,15 @@ fn generate_data(centroids: &Matrix<f64>,
centroids.cols());

let mut rng = thread_rng();
let normal_rv = Normal::new(0f64, noise);
let normal_rv = Normal::new(0f64, noise).unwrap();

for _ in 0..points_per_centroid {
// Generate points from each centroid
for centroid in centroids.row_iter() {
// Generate a point randomly around the centroid
let mut point = Vec::with_capacity(centroids.cols());
for feature in centroid.iter() {
point.push(feature + normal_rv.ind_sample(&mut rng));
point.push(feature + normal_rv.sample(&mut rng));
}

// Push point to raw_cluster_data
Expand Down
33 changes: 16 additions & 17 deletions examples/naive_bayes_dogs.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
extern crate rusty_machine;
extern crate rand;
extern crate rand_distr;

use rand::Rand;
use rand::distributions::Sample;
use rand::distributions::normal::Normal;
use rand::SeedableRng;
use rand_distr::{Distribution, Normal};
use rusty_machine::learning::naive_bayes::{self, NaiveBayes};
use rusty_machine::linalg::{Matrix, BaseMatrix};
use rusty_machine::learning::SupModel;
Expand All @@ -23,18 +23,18 @@ struct Dog {
speed: f64,
}

impl Rand for Dog {
impl Dog {
/// Generate a random dog.
fn rand<R: rand::Rng>(rng: &mut R) -> Self {
fn gen_rand<R: rand::Rng>(rng: &mut R) -> Self {
// Friendliness, furriness, and speed are normally distributed and
// (given color:) independent.
let mut red_dog_friendliness = Normal::new(0., 1.);
let mut red_dog_furriness = Normal::new(0., 1.);
let mut red_dog_speed = Normal::new(0., 1.);
let mut red_dog_friendliness = Normal::new(0., 1.).unwrap();
let mut red_dog_furriness = Normal::new(0., 1.).unwrap();
let mut red_dog_speed = Normal::new(0., 1.).unwrap();

let mut white_dog_friendliness = Normal::new(1., 1.);
let mut white_dog_furriness = Normal::new(1., 1.);
let mut white_dog_speed = Normal::new(-1., 1.);
let mut white_dog_friendliness = Normal::new(1., 1.).unwrap();
let mut white_dog_furriness = Normal::new(1., 1.).unwrap();
let mut white_dog_speed = Normal::new(-1., 1.).unwrap();

// Flip a coin to decide whether to generate a red or white dog.
let coin: f64 = rng.gen();
Expand Down Expand Up @@ -64,19 +64,18 @@ impl Rand for Dog {

fn generate_dog_data(training_set_size: u32, test_set_size: u32)
-> (Matrix<f64>, Matrix<f64>, Matrix<f64>, Vec<Dog>) {
let mut randomness = rand::StdRng::new()
.expect("we should be able to get an RNG");
let mut randomness = rand::rngs::StdRng::seed_from_u64(0);
let rng = &mut randomness;

// We'll train the model on these dogs
let training_dogs = (0..training_set_size)
.map(|_| { Dog::rand(rng) })
.map(|_| { Dog::gen_rand(rng) })
.collect::<Vec<_>>();

// ... and then use the model to make predictions about these dogs' color
// given only their trait measurements.
let test_dogs = (0..test_set_size)
.map(|_| { Dog::rand(rng) })
.map(|_| { Dog::gen_rand(rng) })
.collect::<Vec<_>>();

// The model's `.train` method will take two matrices, each with a row for
Expand Down Expand Up @@ -138,11 +137,11 @@ fn main() {
for (dog, prediction) in test_dogs.iter().zip(predictions.row_iter()).take(unprinted_total) {
evaluate_prediction(&mut hits, dog, prediction.raw_slice());
}

if unprinted_total > 0 {
println!("...");
}

for (dog, prediction) in test_dogs.iter().zip(predictions.row_iter()).skip(unprinted_total) {
let (actual_color, accurate) = evaluate_prediction(&mut hits, dog, prediction.raw_slice());
println!("Predicted: {:?}; Actual: {:?}; Accurate? {:?}",
Expand Down
8 changes: 5 additions & 3 deletions examples/nnet-and_gate.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
extern crate rusty_machine;
extern crate rand;
extern crate rand_distr;

use rand::{random, Closed01};
use rand::{Rng, thread_rng};
use rand_distr::OpenClosed01;
use std::vec::Vec;

use rusty_machine::learning::nnet::{NeuralNet, BCECriterion};
Expand All @@ -26,8 +28,8 @@ fn main() {

for _ in 0..SAMPLES {
// The two inputs are "signals" between 0 and 1
let Closed01(left) = random::<Closed01<f64>>();
let Closed01(right) = random::<Closed01<f64>>();
let left: f64 = thread_rng().sample(OpenClosed01);
let right: f64 = thread_rng().sample(OpenClosed01);
input_data.push(left);
input_data.push(right);
if left > THRESHOLD && right > THRESHOLD {
Expand Down
15 changes: 9 additions & 6 deletions src/data/transforms/shuffle.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,8 @@ use learning::LearningResult;
use linalg::{Matrix, BaseMatrix, BaseMatrixMut};
use super::Transformer;

use rand::{Rng, thread_rng, ThreadRng};
use rand::{Rng, thread_rng};
use rand::rngs::ThreadRng;

/// The `Shuffler`
///
Expand All @@ -49,11 +50,12 @@ impl<R: Rng> Shuffler<R> {
///
/// use rusty_machine::data::transforms::Transformer;
/// use rusty_machine::data::transforms::shuffle::Shuffler;
/// use rand::{StdRng, SeedableRng};
/// use rand::SeedableRng;
/// use rand::rngs::StdRng;
///
/// # fn main() {
/// // We can create a seeded rng
/// let rng = StdRng::from_seed(&[1, 2, 3]);
/// let rng = StdRng::seed_from_u64(123);
///
/// let shuffler = Shuffler::new(rng);
/// # }
Expand Down Expand Up @@ -94,11 +96,12 @@ mod tests {
use super::super::Transformer;
use super::Shuffler;

use rand::{StdRng, SeedableRng};
use rand::SeedableRng;
use rand::rngs::StdRng;

#[test]
fn seeded_shuffle() {
let rng = StdRng::from_seed(&[1, 2, 3]);
let rng = StdRng::seed_from_u64(123);
let mut shuffler = Shuffler::new(rng);

let mat = Matrix::new(4, 2, vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0]);
Expand All @@ -118,4 +121,4 @@ mod tests {
assert_eq!(shuffled.into_vec(),
vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0]);
}
}
}
3 changes: 1 addition & 2 deletions src/learning/nnet/net_layer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,7 @@ use learning::error::{Error, ErrorKind};
use learning::toolkit::activ_fn::ActivationFunc;

use rand::thread_rng;
use rand::distributions::Sample;
use rand::distributions::normal::Normal;
use rand::distributions::{Distribution, Normal};

use std::fmt::Debug;

Expand Down
1 change: 1 addition & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,7 @@
extern crate rulinalg;
extern crate num as libnum;
extern crate rand;
extern crate rand_distr;

pub mod prelude;

Expand Down
19 changes: 6 additions & 13 deletions src/stats/dist/exponential.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,9 @@
//! found in the rand crate. This is provided through
//! traits added within the containing stats module.

use stats::dist::Distribution;
use stats::dist::Distribution as StatDistribution;
use rand::Rng;
use rand::distributions::{Sample, IndependentSample};
use rand::distributions::exponential::Exp1;
use rand_distr::{Distribution, Exp1};

/// An Exponential random variable.
#[derive(Debug, Clone, Copy)]
Expand Down Expand Up @@ -39,7 +38,7 @@ impl Exponential {
}
}

impl Distribution<f64> for Exponential {
impl StatDistribution<f64> for Exponential {
/// The pdf of the exponential distribution.
///
/// # Examples
Expand Down Expand Up @@ -102,15 +101,9 @@ impl Distribution<f64> for Exponential {
}
}

impl Sample<f64> for Exponential {
fn sample<R: Rng>(&mut self, rng: &mut R) -> f64 {
self.ind_sample(rng)
}
}

impl IndependentSample<f64> for Exponential {
fn ind_sample<R: Rng>(&self, rng: &mut R) -> f64 {
let Exp1(n) = rng.gen::<Exp1>();
impl Distribution<f64> for Exponential {
fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> f64 {
let n: f64 = rng.sample(Exp1);
n / self.lambda
}
}
19 changes: 6 additions & 13 deletions src/stats/dist/gaussian.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,9 @@
//! found in the rand crate. This is provided through
//! traits added within the containing stats module.

use stats::dist::Distribution;
use stats::dist::Distribution as StatDistribution;
use rand::Rng;
use rand::distributions::{Sample, IndependentSample};
use rand::distributions::normal::StandardNormal;
use rand_distr::{Distribution, StandardNormal};
use super::consts as stat_consts;
use std::f64::consts as float_consts;

Expand Down Expand Up @@ -68,7 +67,7 @@ impl Gaussian {
///
/// Accurately computes the PDF and log PDF.
/// Estimates the CDF accurate only to 0.003.
impl Distribution<f64> for Gaussian {
impl StatDistribution<f64> for Gaussian {
/// The pdf of the normal distribution
///
/// # Examples
Expand Down Expand Up @@ -147,15 +146,9 @@ impl Distribution<f64> for Gaussian {
}
}

impl Sample<f64> for Gaussian {
fn sample<R: Rng>(&mut self, rng: &mut R) -> f64 {
self.ind_sample(rng)
}
}

impl IndependentSample<f64> for Gaussian {
fn ind_sample<R: Rng>(&self, rng: &mut R) -> f64 {
let StandardNormal(n) = rng.gen::<StandardNormal>();
impl Distribution<f64> for Gaussian {
fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> f64 {
let n: f64 = rng.sample(StandardNormal);
self.mean + self._std_dev * n
}
}
2 changes: 1 addition & 1 deletion tests/learning/pca.rs
Original file line number Diff line number Diff line change
Expand Up @@ -124,4 +124,4 @@ fn test_wide() {

let exp = Matrix::new(1, 2, vec![-6.550335224256381, 1.517487926775624]);
assert_matrix_eq!(outputs, exp, comp=abs, tol=1e-8);
}
}