concision_core/ops/mask/
dropout.rs

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