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>
impl<F: Float + Debug + ScalarOperand + 'static> Dense<F>
Sourcepub fn new<R: Rng>(
input_dim: usize,
output_dim: usize,
activation_name: Option<&str>,
rng: &mut R,
) -> Result<Self>
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 featuresoutput_dim
- Number of output featuresactivation
- Optional activation function namerng
- 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
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 }
Additional examples can be found in:
- examples/neural_network_xor.rs
- examples/visualize_training_progress.rs
- examples/neural_confusion_matrix.rs
- examples/image_classification_complete.rs
- examples/model_architecture_visualization.rs
- examples/improved_model_serialization.rs
- examples/training_loop_example.rs
- examples/advanced_training_example.rs
- examples/text_classification_complete.rs
- examples/model_visualization_cnn.rs
- examples/generative_models_complete.rs
- examples/object_detection_complete.rs
- examples/manual_xor.rs
- examples/model_serialization_example.rs
- examples/batchnorm_example.rs
- examples/dropout_example.rs
- examples/advanced_optimizers_example.rs
Sourcepub fn output_dim(&self) -> usize
pub fn output_dim(&self) -> usize
Get the output dimension
Sourcepub fn activation_name(&self) -> Option<&str>
pub fn activation_name(&self) -> Option<&str>
Get the activation function name
Trait Implementations§
Source§impl<F: Float + Debug + ScalarOperand + 'static> Layer<F> for Dense<F>
impl<F: Float + Debug + ScalarOperand + 'static> Layer<F> for Dense<F>
Source§fn as_any_mut(&mut self) -> &mut dyn Any
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
fn layer_type(&self) -> &str
Get the type of the layer (e.g., “Dense”, “Conv2D”) Read more
Source§fn parameter_count(&self) -> usize
fn parameter_count(&self) -> usize
Get the number of trainable parameters in this layer Read more
Source§fn layer_description(&self) -> String
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>>
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>>
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<()>
fn update(&mut self, learning_rate: F) -> Result<()>
Update the layer parameters with the given gradients Read more
Source§fn gradients(&self) -> Vec<Array<F, IxDyn>> ⓘ
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<()>
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<()>
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)
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
fn is_training(&self) -> bool
Get the current training mode Read more
Source§impl<F: Float + Debug + ScalarOperand + 'static> ParamLayer<F> for Dense<F>
impl<F: Float + Debug + ScalarOperand + 'static> ParamLayer<F> for Dense<F>
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>
impl<F> Unpin for Dense<F>
impl<F> !UnwindSafe for Dense<F>
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more
Source§impl<T> CloneToUninit for Twhere
T: Clone,
impl<T> CloneToUninit for Twhere
T: Clone,
Source§impl<T> IntoEither for T
impl<T> IntoEither for T
Source§fn into_either(self, into_left: bool) -> Either<Self, Self>
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 moreSource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
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