concision_core/traits/
mask.rs

1/*
2    Appellation: mask <module>
3    Contrib: @FL03
4*/
5
6/// [Dropout] randomly zeroizes elements with a given probability (`p`).
7pub trait DropOut {
8    type Output;
9
10    fn dropout(&self, p: f64) -> Self::Output;
11}
12
13#[cfg(feature = "rand")]
14impl<A, S, D> DropOut for ndarray::ArrayBase<S, D>
15where
16    A: num_traits::Num + ndarray::ScalarOperand,
17    D: ndarray::Dimension,
18    S: ndarray::DataOwned<Elem = A>,
19{
20    type Output = ndarray::Array<A, D>;
21
22    fn dropout(&self, p: f64) -> Self::Output {
23        pub use crate::init::Initialize;
24        use ndarray::Array;
25        let dim = self.dim();
26        // Create a mask of the same shape as the input array
27        let mask: Array<bool, D> = Array::bernoulli(dim, p).expect("Failed to create mask");
28        let mask = mask.mapv(|x| if x { A::zero() } else { A::one() });
29
30        // Element-wise multiplication to apply dropout
31        self.to_owned() * mask
32    }
33}