ChobitDecoder

Struct ChobitDecoder 

Source
pub struct ChobitDecoder<const OUT: usize, const MIDDLE: usize, const IN: usize> { /* private fields */ }
Expand description

Decoder from fixed length data to sequence data.

  • OUT : Dimension of output.
  • MIDDLE : Dimension of hidden layer.
  • IN : Dimension of input.

§Example

Letter commentator.

  • If inputs ‘日’, outputs “これは日本語です。”
  • If inputs ‘E’, outputs “This is English.”

(1) Defines ID and messages.

extern crate chobitlibs;
 
use chobitlibs::chobit_ai::{
    MathVec,
    Activation,
    ChobitDecoder,
    ChobitMlDecoder,
    MlDecoderCache
};
 
use chobitlibs::chobit_rand::ChobitRand;
 
const JAPANESE_ID: char = '日';
const ENGLISH_ID: char = 'E';
 
const JAPANESE_MESSAGE: &str = "これは日本語です。";
const ENGLISH_MESSAGE: &str = "This is English.";
 
fn write_string_to_slice(string: &str, slice: &mut [MathVec<32>]) {
    string.chars().zip(slice.iter_mut()).for_each(|(c, s)| {
        s.load_u32_label(c as u32);
    });
}

(2) Creates ChobitDecoder and randomises weights.

const OUT: usize = 32;
const MIDDLE: usize = 64;
const IN: usize = 32;

let max_message_len = JAPANESE_MESSAGE.len().max(ENGLISH_MESSAGE.len());

let mut rng = ChobitRand::new(b"ChobitDecoder Example");

let mut decoder =
    ChobitDecoder::<OUT, MIDDLE, IN>::new(Activation::SoftSign);

// Randomises weights.
decoder.for_each_weight_mut(|weight| {
    *weight = ((rng.next_f64() as f32) * 2.0) - 1.0;
});

let mut input = MathVec::<IN>::new();
let mut output = vec![MathVec::<OUT>::new(); max_message_len];
let initial_state = MathVec::<MIDDLE>::new();

(3) Wraps AI with ChobitMlDecoder for machine learning.

let mut decoder = ChobitMlDecoder::<OUT, MIDDLE, IN>::new(decoder);
let mut cache = MlDecoderCache::<OUT, MIDDLE, IN>::new(max_message_len);

let mut input_error = MathVec::<IN>::new();
let mut output_error = vec![MathVec::<OUT>::new(); max_message_len];
let mut prev_state_error = MathVec::<MIDDLE>::new();

(4) Machine learning.

const EPOCH: usize = 10000;
const BATCH_SIZE: usize = 1;
const RATE: f32 = 0.01;

let japanese_message_len = JAPANESE_MESSAGE.chars().count();
let english_message_len = ENGLISH_MESSAGE.chars().count();

for _ in 0..EPOCH {
    for _ in 0..BATCH_SIZE {
        //--- Learns Japanese ---//
        input.load_u32_label(JAPANESE_ID as u32);

        write_string_to_slice(&JAPANESE_MESSAGE, &mut output);

        // Writes cache.
        decoder.ready(
            &input,
            &initial_state,
            japanese_message_len,
            &mut cache
        );

        // Calculates error.
        cache.calc_output_error(
            &output[..japanese_message_len],
            &mut output_error[..japanese_message_len]
        );

        // Studies.
        decoder.study(
            &output_error[..japanese_message_len],
            &cache,
            &mut input_error,
            &mut prev_state_error
        );

        //--- Learns English ---//
        input.load_u32_label(ENGLISH_ID as u32);

        write_string_to_slice(&ENGLISH_MESSAGE, &mut output);

        // Writes cache.
        decoder.ready(
            &input,
            &initial_state,
            english_message_len,
            &mut cache
        );

        // Calculates error.
        cache.calc_output_error(
            &output[..english_message_len],
            &mut output_error[..english_message_len]
        );

        // Studies.
        decoder.study(
            &output_error[..english_message_len],
            &cache,
            &mut input_error,
            &mut prev_state_error
        );
    }

    // Updates weights.
    decoder.update(RATE);
}

(5) Tests AI.

// Unwrap Decoder.
let mut decoder = decoder.drop();

let mut output = MathVec::<OUT>::new();

// Tests Japanese.
// Sets input.
decoder.input_mut().load_u32_label(JAPANESE_ID as u32);

// Initializes state.
decoder.state_mut().copy_from(&initial_state);

// Outputs for each one.
JAPANESE_MESSAGE.chars().for_each(|c| {
    decoder.output_next(&mut output);

    assert_eq!(output.to_u32_label(), c as u32);
});

// Tests English.
// Sets input.
decoder.input_mut().load_u32_label(ENGLISH_ID as u32);

// Initializes state.
decoder.state_mut().copy_from(&initial_state);

// Outputs for each one.
ENGLISH_MESSAGE.chars().for_each(|c| {
    decoder.output_next(&mut output);

    assert_eq!(output.to_u32_label(), c as u32);
});

Implementations§

Source§

impl<const OUT: usize, const MIDDLE: usize, const IN: usize> ChobitDecoder<OUT, MIDDLE, IN>

Source

pub fn new(activation: Activation) -> Self

Creates ChobitDecoder.

  • activation : Activation function for output layer.
  • Return : ChobitDecoder.
Source

pub fn lstm(&self) -> &Lstm<MIDDLE, IN>

Gets immutable Lstm.

  • Return : Lstm.
Source

pub fn lstm_mut(&mut self) -> &mut Lstm<MIDDLE, IN>

Gets mutable Lstm.

  • Return : Lstm.
Source

pub fn output_layer(&self) -> &Layer<OUT, MIDDLE>

Gets immutable output layer.

  • Return : Output layer.
Source

pub fn output_layer_mut(&mut self) -> &mut Layer<OUT, MIDDLE>

Gets mutable output layer.

  • Return : Output layer.
Source

pub fn input(&self) -> &MathVec<IN>

Gets immutable input.

This should be set before to call output_next().

  • Return : Input.
Source

pub fn input_mut(&mut self) -> &mut MathVec<IN>

Gets mutable input.

This should be set before to call output_next().

  • Return : Input.
Source

pub fn state(&self) -> &MathVec<MIDDLE>

Gets immutable state.

This should be initialized before to call output_next().

  • Return : State.
Source

pub fn state_mut(&mut self) -> &mut MathVec<MIDDLE>

Gets mutable state.

This should be initialized before to call output_next().

  • Return : State.
Source

pub fn output_next(&mut self, output: &mut MathVec<OUT>)

Output next data calculated by current state and input.

  • output : Buffer for next data.
Source

pub fn for_each_weight<F>(&self, f: F)
where F: FnMut(&f32),

Accesses each immutable weight with closure.

  • f : Closure.
Source

pub fn for_each_weight_mut<F>(&mut self, f: F)
where F: FnMut(&mut f32),

Accesses each mutable weight with closure.

  • f : Closure.

Trait Implementations§

Source§

impl<const OUT: usize, const MIDDLE: usize, const IN: usize> Clone for ChobitDecoder<OUT, MIDDLE, IN>

Source§

fn clone(&self) -> ChobitDecoder<OUT, MIDDLE, IN>

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl<const OUT: usize, const MIDDLE: usize, const IN: usize> Debug for ChobitDecoder<OUT, MIDDLE, IN>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<const OUT: usize, const MIDDLE: usize, const IN: usize> PartialEq for ChobitDecoder<OUT, MIDDLE, IN>

Source§

fn eq(&self, other: &ChobitDecoder<OUT, MIDDLE, IN>) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl<const OUT: usize, const MIDDLE: usize, const IN: usize> StructuralPartialEq for ChobitDecoder<OUT, MIDDLE, IN>

Auto Trait Implementations§

§

impl<const OUT: usize, const MIDDLE: usize, const IN: usize> Freeze for ChobitDecoder<OUT, MIDDLE, IN>

§

impl<const OUT: usize, const MIDDLE: usize, const IN: usize> RefUnwindSafe for ChobitDecoder<OUT, MIDDLE, IN>

§

impl<const OUT: usize, const MIDDLE: usize, const IN: usize> Send for ChobitDecoder<OUT, MIDDLE, IN>

§

impl<const OUT: usize, const MIDDLE: usize, const IN: usize> Sync for ChobitDecoder<OUT, MIDDLE, IN>

§

impl<const OUT: usize, const MIDDLE: usize, const IN: usize> Unpin for ChobitDecoder<OUT, MIDDLE, IN>

§

impl<const OUT: usize, const MIDDLE: usize, const IN: usize> UnwindSafe for ChobitDecoder<OUT, MIDDLE, IN>

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> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. 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> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

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

Source§

type Error = Infallible

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

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

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.