Skip to main content

NeuralNetwork

Struct NeuralNetwork 

Source
pub struct NeuralNetwork<L: Layers, Opt = Sgd> { /* private fields */ }
Expand description

A trainable feed-forward network over a tuple of Dense layers (C++ NeuralNetwork<..., HiddenLayers<...>, ...>). See the module documentation for an example.

Opt is the optimizer: Sgd (the default) or an adaptive one from optimizer, passed to with_optimizer.

Implementations§

Source§

impl<V: Fixed, L: Layers<Value = V> + Default> NeuralNetwork<L, Sgd>

Source

pub fn new(random_weight: impl FnMut() -> V) -> Self

Build the network, trained with Sgd, and initialise its weights from random_weight, in the C++ order: each layer’s inputs and then its bias, from the input side, then one draw per output neuron (the C++ output neurons own an unused connection whose initialisation consumes a draw).

Examples found in repository?
examples/common/anomaly_demo.rs (line 127)
124pub fn new_autoencoder(seed: u32) -> Autoencoder {
125    let mut rng = GlibcRand::new(seed);
126    let half = Q16_16::ONE.raw() / 2;
127    let mut nn = Autoencoder::new(|| Q16_16::from_raw(rng.next_i32() % (2 * half + 1) - half));
128    nn.set_learning_rate(Q16_16::from_raw(1 << 11)); // 1/32
129    nn.set_momentum_rate(Q16_16::from_raw(1 << 15)); // 1/2
130    nn.set_acceleration_rate(Q16_16::ZERO);
131    nn.set_gradient_clip(Some((Q16_16::from_int(-1), Q16_16::ONE)));
132    nn
133}
Source§

impl<V: Fixed, L: Layers<Value = V> + Default, Opt: Optimizer<V>> NeuralNetwork<L, Opt>

Source

pub fn with_optimizer(random_weight: impl FnMut() -> V, optimizer: Opt) -> Self

As new, trained with optimizer, for example Adam.

Source§

impl<V: Fixed, L: Layers<Value = V>, Opt: Optimizer<V>> NeuralNetwork<L, Opt>

Source

pub fn optimizer(&self) -> &Opt

The optimizer, for example to read Adam::timestep.

Source

pub fn set_learning_rate(&mut self, rate: V)

Replace the learning rate (default 2^-2).

Examples found in repository?
examples/common/anomaly_demo.rs (line 128)
124pub fn new_autoencoder(seed: u32) -> Autoencoder {
125    let mut rng = GlibcRand::new(seed);
126    let half = Q16_16::ONE.raw() / 2;
127    let mut nn = Autoencoder::new(|| Q16_16::from_raw(rng.next_i32() % (2 * half + 1) - half));
128    nn.set_learning_rate(Q16_16::from_raw(1 << 11)); // 1/32
129    nn.set_momentum_rate(Q16_16::from_raw(1 << 15)); // 1/2
130    nn.set_acceleration_rate(Q16_16::ZERO);
131    nn.set_gradient_clip(Some((Q16_16::from_int(-1), Q16_16::ONE)));
132    nn
133}
Source

pub fn set_momentum_rate(&mut self, rate: V)

Replace the momentum rate (default 2^-1).

Examples found in repository?
examples/common/anomaly_demo.rs (line 129)
124pub fn new_autoencoder(seed: u32) -> Autoencoder {
125    let mut rng = GlibcRand::new(seed);
126    let half = Q16_16::ONE.raw() / 2;
127    let mut nn = Autoencoder::new(|| Q16_16::from_raw(rng.next_i32() % (2 * half + 1) - half));
128    nn.set_learning_rate(Q16_16::from_raw(1 << 11)); // 1/32
129    nn.set_momentum_rate(Q16_16::from_raw(1 << 15)); // 1/2
130    nn.set_acceleration_rate(Q16_16::ZERO);
131    nn.set_gradient_clip(Some((Q16_16::from_int(-1), Q16_16::ONE)));
132    nn
133}
Source

pub fn set_acceleration_rate(&mut self, rate: V)

Replace the acceleration rate, the weight on the delta weight from two steps back (default 2^-4).

Examples found in repository?
examples/common/anomaly_demo.rs (line 130)
124pub fn new_autoencoder(seed: u32) -> Autoencoder {
125    let mut rng = GlibcRand::new(seed);
126    let half = Q16_16::ONE.raw() / 2;
127    let mut nn = Autoencoder::new(|| Q16_16::from_raw(rng.next_i32() % (2 * half + 1) - half));
128    nn.set_learning_rate(Q16_16::from_raw(1 << 11)); // 1/32
129    nn.set_momentum_rate(Q16_16::from_raw(1 << 15)); // 1/2
130    nn.set_acceleration_rate(Q16_16::ZERO);
131    nn.set_gradient_clip(Some((Q16_16::from_int(-1), Q16_16::ONE)));
132    nn
133}
Source

pub fn set_gradient_clip(&mut self, range: Option<(V, V)>)

Clip each weight’s gradient to [min, max] before the update, or None (the default). C++ GradientClipByValue<ValueType, I, F> is Some((QValue(-I, F), QValue(I, F))); the default GradientClipByValue<ValueType> is Some((-1.0, 1.0)). Bias weights are never clipped, as in the C++.

Examples found in repository?
examples/common/anomaly_demo.rs (line 131)
124pub fn new_autoencoder(seed: u32) -> Autoencoder {
125    let mut rng = GlibcRand::new(seed);
126    let half = Q16_16::ONE.raw() / 2;
127    let mut nn = Autoencoder::new(|| Q16_16::from_raw(rng.next_i32() % (2 * half + 1) - half));
128    nn.set_learning_rate(Q16_16::from_raw(1 << 11)); // 1/32
129    nn.set_momentum_rate(Q16_16::from_raw(1 << 15)); // 1/2
130    nn.set_acceleration_rate(Q16_16::ZERO);
131    nn.set_gradient_clip(Some((Q16_16::from_int(-1), Q16_16::ONE)));
132    nn
133}
Source

pub fn feed_forward(&mut self, inputs: &L::Inputs)

Run one forward pass. Read the result with learned_values.

Examples found in repository?
examples/common/anomaly_demo.rs (line 119)
118pub fn score(nn: &mut Autoencoder, w: &[Q16_16; WINDOW]) -> Q16_16 {
119    nn.feed_forward(w);
120    nn.calculate_error(w)
121}
Source

pub fn learned_values(&self) -> L::Outputs

The output layer’s activations from the latest forward pass.

Source

pub fn calculate_error(&self, targets: &L::Outputs) -> V

Mean-squared error of the latest forward pass against targets (C++ MeanSquaredErrorCalculator).

Examples found in repository?
examples/common/anomaly_demo.rs (line 120)
118pub fn score(nn: &mut Autoencoder, w: &[Q16_16; WINDOW]) -> Q16_16 {
119    nn.feed_forward(w);
120    nn.calculate_error(w)
121}
Source

pub fn train(&mut self, targets: &L::Outputs)

One back-propagation step towards targets for the latest forward pass (C++ ChainBackPropagationPolicy).

Examples found in repository?
examples/common/anomaly_demo.rs (line 141)
139pub fn train_step(nn: &mut Autoencoder, w: &[Q16_16; WINDOW]) -> Q16_16 {
140    let error = score(nn, w);
141    nn.train(w);
142    error
143}
Source

pub fn layers(&self) -> &L

The layers, to read their weights (nn.layers().0.weights()).

Examples found in repository?
examples/common/anomaly_demo.rs (line 189)
182pub fn evaluate(
183    nn: &mut Autoencoder,
184    signal: &mut Signal,
185    out: &mut dyn Write,
186    each: &mut dyn FnMut(&str, i32),
187) -> Result<u32, fmt::Error> {
188    let mut hash = Fnv::new();
189    let (l0, l1) = nn.layers();
190    for row in l0.weights() {
191        for w in row {
192            hash.add(w.raw());
193        }
194    }
195    for w in l0.bias_weights() {
196        hash.add(w.raw());
197    }
198    for row in l1.weights() {
199        for w in row {
200            hash.add(w.raw());
201        }
202    }
203    for w in l1.bias_weights() {
204        hash.add(w.raw());
205    }
206
207    // Threshold: twice the largest error on normal validation windows.
208    let mut max_normal = 0;
209    for _ in 0..NORMAL_WINDOWS {
210        let e = score(nn, &signal.window(Kind::Normal)).raw();
211        hash.add(e);
212        max_normal = max_normal.max(e);
213    }
214    let threshold = max_normal.saturating_mul(2);
215    writeln!(
216        out,
217        "threshold={threshold} (2 x the largest error on {NORMAL_WINDOWS} normal windows, raw Q16.16)"
218    )?;
219
220    let mut flagged = |kind: Kind, name: &str, n: u32, hash: &mut Fnv| {
221        let mut count = 0;
222        for _ in 0..n {
223            let e = score(nn, &signal.window(kind)).raw();
224            hash.add(e);
225            each(name, e);
226            count += u32::from(e > threshold);
227        }
228        count
229    };
230    let fp = flagged(Kind::Normal, "normal", NORMAL_WINDOWS, &mut hash);
231    writeln!(out, "normal: flagged {fp}/{NORMAL_WINDOWS} (false alarms)")?;
232    for (kind, name) in FAULTS {
233        let tp = flagged(kind, name, FAULT_WINDOWS, &mut hash);
234        writeln!(out, "{name}: flagged {tp}/{FAULT_WINDOWS}")?;
235    }
236    writeln!(out, "hash=0x{:08X}", hash.0)?;
237    Ok(hash.0)
238}
Source

pub fn layers_mut(&mut self) -> &mut L

The layers, to load weights (nn.layers_mut().0.set_weights(..)).

Auto Trait Implementations§

§

impl<L, Opt> Forget for NeuralNetwork<L, Opt>

§

impl<L, Opt> Freeze for NeuralNetwork<L, Opt>
where L: Freeze, <L as LayersImpl>::Inputs: Freeze, <L as LayersImpl>::Value: Freeze, Option<(<L as LayersImpl>::Value, <L as LayersImpl>::Value)>: Freeze, Opt: Freeze,

§

impl<L, Opt> RefUnwindSafe for NeuralNetwork<L, Opt>
where L: RefUnwindSafe, <L as LayersImpl>::Inputs: RefUnwindSafe, <L as LayersImpl>::Value: RefUnwindSafe, Option<(<L as LayersImpl>::Value, <L as LayersImpl>::Value)>: RefUnwindSafe, Opt: RefUnwindSafe,

§

impl<L, Opt> Send for NeuralNetwork<L, Opt>
where L: Send, <L as LayersImpl>::Inputs: Send, <L as LayersImpl>::Value: Send, Option<(<L as LayersImpl>::Value, <L as LayersImpl>::Value)>: Send, Opt: Send,

§

impl<L, Opt> Sync for NeuralNetwork<L, Opt>
where L: Sync, <L as LayersImpl>::Inputs: Sync, <L as LayersImpl>::Value: Sync, Option<(<L as LayersImpl>::Value, <L as LayersImpl>::Value)>: Sync, Opt: Sync,

§

impl<L, Opt> Unpin for NeuralNetwork<L, Opt>
where L: Unpin, <L as LayersImpl>::Inputs: Unpin, <L as LayersImpl>::Value: Unpin, Option<(<L as LayersImpl>::Value, <L as LayersImpl>::Value)>: Unpin, Opt: Unpin,

§

impl<L, Opt> UnsafeUnpin for NeuralNetwork<L, Opt>
where L: UnsafeUnpin, <L as LayersImpl>::Inputs: UnsafeUnpin, <L as LayersImpl>::Value: UnsafeUnpin, Option<(<L as LayersImpl>::Value, <L as LayersImpl>::Value)>: UnsafeUnpin, Opt: UnsafeUnpin,

§

impl<L, Opt> UnwindSafe for NeuralNetwork<L, Opt>
where L: UnwindSafe, <L as LayersImpl>::Inputs: UnwindSafe, <L as LayersImpl>::Value: UnwindSafe, Option<(<L as LayersImpl>::Value, <L as LayersImpl>::Value)>: UnwindSafe, Opt: UnwindSafe,

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.