Struct Dense

Source
pub struct Dense<F: Float + Debug> { /* private fields */ }
Expand description

Dense (fully connected) layer for neural networks.

A dense layer is a layer where each input neuron is connected to each output neuron. It performs the operation: y = activation(W * x + b), where W is the weight matrix, x is the input vector, b is the bias vector, and activation is the activation function.

§Examples

use scirs2_neural::layers::{Dense, Layer};
use ndarray::{Array, Array2};
use rand::rngs::SmallRng;
use rand::SeedableRng;

// Create a dense layer with 2 input neurons, 3 output neurons, and ReLU activation
let mut rng = SmallRng::seed_from_u64(42);
let dense = Dense::new(2, 3, Some("relu"), &mut rng).unwrap();

// Forward pass with a batch of 2 samples
let input = Array2::from_shape_vec((2, 2), vec![1.0f64, 2.0, 3.0, 4.0]).unwrap().into_dyn();
let output = dense.forward(&input).unwrap();

// Output shape should be (2, 3) - 2 samples with 3 features each
assert_eq!(output.shape(), &[2, 3]);

Dense (fully connected) layer for neural networks.

A dense layer is a layer where each input neuron is connected to each output neuron. It performs the operation: y = activation(W * x + b), where W is the weight matrix, x is the input vector, b is the bias vector, and activation is the activation function.

Implementations§

Source§

impl<F: Float + Debug + ScalarOperand + 'static> Dense<F>

Source

pub fn new<R: Rng>( input_dim: usize, output_dim: usize, activation_name: Option<&str>, rng: &mut R, ) -> Result<Self>

Create a new dense layer.

§Arguments
  • input_dim - Number of input features
  • output_dim - Number of output features
  • activation - Optional activation function name
  • rng - Random number generator for weight initialization
§Returns
  • A new dense layer
Examples found in repository?
examples/improved_xor.rs (line 19)
15    fn new() -> Result<Self> {
16        let mut rng = SmallRng::seed_from_u64(42);
17
18        // Create two layers: 2 inputs -> 5 hidden -> 1 output
19        let hidden_layer = Dense::new(2, 5, Some("relu"), &mut rng)?;
20        let output_layer = Dense::new(5, 1, None, &mut rng)?;
21
22        Ok(Self {
23            hidden_layer,
24            output_layer,
25        })
26    }
More examples
Hide additional examples
examples/model_visualization_simple.rs (line 52)
47fn create_mlp_model<R: rand::Rng>(rng: &mut R) -> Result<Sequential<f64>> {
48    let mut model = Sequential::new();
49
50    // Input layer is implicitly defined by the first layer
51    // Hidden layers
52    model.add_layer(Dense::new(784, 128, Some("relu"), rng)?);
53    model.add_layer(Dense::new(128, 64, Some("relu"), rng)?);
54
55    // Output layer
56    model.add_layer(Dense::new(64, 10, Some("softmax"), rng)?);
57
58    Ok(model)
59}
examples/advanced_callbacks.rs (line 43)
39fn create_regression_model(input_dim: usize, rng: &mut SmallRng) -> Result<Sequential<f32>> {
40    let mut model = Sequential::new();
41
42    // Input layer
43    let dense1 = Dense::new(input_dim, 16, Some("relu"), rng)?;
44    model.add_layer(dense1);
45
46    // Hidden layers
47    let dense2 = Dense::new(16, 8, Some("relu"), rng)?;
48    model.add_layer(dense2);
49
50    // Output layer (linear activation for regression)
51    let dense3 = Dense::new(8, 1, None, rng)?;
52    model.add_layer(dense3);
53
54    Ok(model)
55}
examples/scheduler_optimizer.rs (line 46)
42fn create_xor_model(rng: &mut SmallRng) -> Result<Sequential<f32>> {
43    let mut model = Sequential::new();
44
45    // Input layer with 2 neurons (XOR has 2 inputs)
46    let dense1 = Dense::new(2, 8, Some("relu"), rng)?;
47    model.add_layer(dense1);
48
49    // Hidden layer
50    let dense2 = Dense::new(8, 4, Some("relu"), rng)?;
51    model.add_layer(dense2);
52
53    // Output layer with 1 neuron (XOR has 1 output)
54    let dense3 = Dense::new(4, 1, Some("sigmoid"), rng)?;
55    model.add_layer(dense3);
56
57    Ok(model)
58}
examples/training_callbacks.rs (line 47)
43fn create_xor_model(rng: &mut SmallRng) -> Result<Sequential<f32>> {
44    let mut model = Sequential::new();
45
46    // Input layer with 2 neurons (XOR has 2 inputs)
47    let dense1 = Dense::new(2, 8, Some("relu"), rng)?;
48    model.add_layer(dense1);
49
50    // Hidden layer
51    let dense2 = Dense::new(8, 4, Some("relu"), rng)?;
52    model.add_layer(dense2);
53
54    // Output layer with 1 neuron (XOR has 1 output)
55    let dense3 = Dense::new(4, 1, Some("sigmoid"), rng)?;
56    model.add_layer(dense3);
57
58    Ok(model)
59}
examples/model_evaluation_example.rs (lines 47-52)
43    fn build(&self) -> Result<Self::Model> {
44        let mut model = Sequential::new();
45
46        let mut rng = SmallRng::seed_from_u64(42);
47        model.add(Dense::<F>::new(
48            self.input_dim,
49            self.hidden_dim,
50            Some("relu"),
51            &mut rng,
52        )?);
53
54        model.add(Dropout::<F>::new(0.2, &mut rng)?);
55
56        model.add(Dense::<F>::new(
57            self.hidden_dim,
58            self.output_dim,
59            None,
60            &mut rng,
61        )?);
62
63        Ok(model)
64    }
Source

pub fn input_dim(&self) -> usize

Get the input dimension

Source

pub fn output_dim(&self) -> usize

Get the output dimension

Source

pub fn activation_name(&self) -> Option<&str>

Get the activation function name

Trait Implementations§

Source§

impl<F: Float + Debug + ScalarOperand + 'static> Clone for Dense<F>

Source§

fn clone(&self) -> Self

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

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

Performs copy-assignment from source. Read more
Source§

impl<F: Float + Debug + ScalarOperand + 'static> Debug for Dense<F>

Source§

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

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

impl<F: Float + Debug + ScalarOperand + 'static> Layer<F> for Dense<F>

Source§

fn as_any(&self) -> &dyn Any

Get the layer as a dyn Any for downcasting Read more
Source§

fn as_any_mut(&mut self) -> &mut dyn Any

Get the layer as a mutable dyn Any for downcasting Read more
Source§

fn layer_type(&self) -> &str

Get the type of the layer (e.g., “Dense”, “Conv2D”) Read more
Source§

fn parameter_count(&self) -> usize

Get the number of trainable parameters in this layer Read more
Source§

fn layer_description(&self) -> String

Get a detailed description of this layer Read more
Source§

fn forward(&self, input: &Array<F, IxDyn>) -> Result<Array<F, IxDyn>>

Forward pass of the layer Read more
Source§

fn backward( &self, input: &Array<F, IxDyn>, grad_output: &Array<F, IxDyn>, ) -> Result<Array<F, IxDyn>>

Backward pass of the layer to compute gradients Read more
Source§

fn update(&mut self, learning_rate: F) -> Result<()>

Update the layer parameters with the given gradients Read more
Source§

fn params(&self) -> Vec<Array<F, IxDyn>>

Get the parameters of the layer Read more
Source§

fn gradients(&self) -> Vec<Array<F, IxDyn>>

Get the gradients of the layer parameters Read more
Source§

fn set_gradients(&mut self, _gradients: &[Array<F, IxDyn>]) -> Result<()>

Set the gradients of the layer parameters Read more
Source§

fn set_params(&mut self, _params: &[Array<F, IxDyn>]) -> Result<()>

Set the parameters of the layer Read more
Source§

fn set_training(&mut self, _training: bool)

Set the layer to training mode (true) or evaluation mode (false) Read more
Source§

fn is_training(&self) -> bool

Get the current training mode Read more
Source§

impl<F: Float + Debug + ScalarOperand + 'static> ParamLayer<F> for Dense<F>

Source§

fn get_parameters(&self) -> Vec<&Array<F, IxDyn>>

Get the parameters of the layer as a vector of arrays
Source§

fn get_gradients(&self) -> Vec<&Array<F, IxDyn>>

Get the gradients of the parameters
Source§

fn set_parameters(&mut self, params: Vec<Array<F, IxDyn>>) -> Result<()>

Set the parameters of the layer

Auto Trait Implementations§

§

impl<F> !Freeze for Dense<F>

§

impl<F> !RefUnwindSafe for Dense<F>

§

impl<F> Send for Dense<F>
where F: Send,

§

impl<F> Sync for Dense<F>
where F: Sync + Send,

§

impl<F> Unpin for Dense<F>

§

impl<F> !UnwindSafe for Dense<F>

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> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
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.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V