Struct Softmax

Source
pub struct Softmax { /* private fields */ }
Expand description

Softmax activation function.

The softmax function is defined as: f(x_i) = exp(x_i) / sum_j(exp(x_j))

It transforms a vector of real values into a probability distribution.

§Examples

use scirs2_neural::activations::{Softmax, Activation};
use ndarray::arr1;

// Create softmax activation for 1D array (axis 0)
let softmax = Softmax::new(0);
let input = arr1(&[1.0f64, 2.0, 3.0]).into_dyn();
let output = softmax.forward(&input).unwrap();

// Check that the output sums to 1.0
let sum: f64 = output.sum();
assert!((sum - 1.0).abs() < 1e-6);

// Check that all values are between 0 and 1
for val in output.iter() {
    assert!(*val >= 0.0 && *val <= 1.0);
}

Implementations§

Source§

impl Softmax

Source

pub fn new(axis: usize) -> Self

Create a new Softmax activation function.

§Arguments
  • axis - The axis along which to compute the softmax.
Examples found in repository?
examples/test_softmax.rs (line 11)
4fn main() {
5    println!("Testing softmax implementation...\n");
6
7    // Test case 1: Simple 1D array
8    let input = arr1(&[1.0, 2.0, 3.0]);
9    println!("Input: {:?}", input);
10
11    let softmax = Softmax::new(0);
12    let output = softmax.forward(&input.clone().into_dyn()).unwrap();
13    println!("Softmax output: {:?}", output);
14
15    // Verify that output sums to 1
16    let sum: f64 = output.sum();
17    println!("Sum of softmax: {}", sum);
18    assert!((sum - 1.0).abs() < 1e-6, "Softmax should sum to 1");
19
20    // Test case 2: 2D array (batch processing)
21    println!("\nTest case 2: 2D batch");
22    let input_2d = arr2(&[[1.0, 2.0, 3.0], [3.0, 2.0, 1.0], [2.0, 2.0, 2.0]]);
23    println!("Input 2D:\n{:?}", input_2d);
24
25    // Apply softmax along axis 1 (row-wise)
26    let softmax_2d = Softmax::new(1);
27    let output_2d = softmax_2d.forward(&input_2d.clone().into_dyn()).unwrap();
28    println!("Softmax output 2D:\n{:?}", output_2d);
29
30    // Verify each row sums to 1
31    for i in 0..output_2d.shape()[0] {
32        let row_sum: f64 = output_2d.slice(ndarray::s![i, ..]).sum();
33        println!("Row {} sum: {}", i, row_sum);
34        assert!((row_sum - 1.0).abs() < 1e-6, "Each row should sum to 1");
35    }
36
37    // Test case 3: Gradient computation
38    println!("\nTest case 3: Gradient computation");
39    let grad_output = arr1(&[0.1, 0.2, 0.3]).into_dyn();
40    let forward_output = softmax.forward(&input.clone().into_dyn()).unwrap();
41    let grad_input = softmax.backward(&grad_output, &forward_output).unwrap();
42    println!("Gradient input: {:?}", grad_input);
43
44    println!("\nAll tests passed!");
45}

Trait Implementations§

Source§

impl<F: Float + Debug> Activation<F> for Softmax

Source§

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

Apply the activation function to the input Read more
Source§

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

Compute the derivative of the activation function with respect to the input Read more
Source§

impl Clone for Softmax

Source§

fn clone(&self) -> Softmax

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 Debug for Softmax

Source§

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

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

impl Default for Softmax

Source§

fn default() -> Self

Returns the “default value” for a type. Read more
Source§

impl Copy for Softmax

Auto Trait Implementations§

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