nabla_ml::nab_array

Struct NDArray

Source
pub struct NDArray {
    pub data: Vec<f64>,
    pub shape: Vec<usize>,
}

Fields§

§data: Vec<f64>§shape: Vec<usize>

Implementations§

Source§

impl NDArray

Source

pub fn normalize(&mut self)

Normalizes the array values to range [0, 1] using min-max normalization

Source

pub fn normalize_with_range(&mut self, min_val: f64, max_val: f64)

Normalizes the array values using specified min and max values

Source

pub fn data_mut(&mut self) -> &mut Vec<f64>

Source

pub fn load_and_split_dataset( path: &str, train_percent: f64, ) -> Result<((NDArray, NDArray), (NDArray, NDArray))>

Loads a dataset from .nab files and splits it into training and testing sets

§Arguments
  • path - Base path for the .nab files (e.g., “mnist”)
  • train_percent - Percentage of data to use for training (e.g., 80 for 80%)
§Returns

A tuple containing ((train_images, train_labels), (test_images, test_labels))

Source

pub fn csv_to_nab( csv_path: &str, output_path: &str, shape: Vec<usize>, skip_first_column: bool, ) -> Result<()>

Converts CSV data to .nab format

§Arguments
  • csv_path - Path to the CSV file
  • output_path - Path where to save the .nab file
  • shape - Shape of the resulting array (e.g., [60000, 28, 28] for MNIST images)
Source

pub fn display(&self) -> String

Displays the array in a formatted way similar to numpy’s print format

§Returns

A string representation of the array

Source§

impl NDArray

Source

pub fn new(data: Vec<f64>, shape: Vec<usize>) -> Self

Source

pub fn from_vec(data: Vec<f64>) -> Self

Source

pub fn from_matrix(data: Vec<Vec<f64>>) -> Self

Source

pub fn shape(&self) -> &[usize]

Source

pub fn ndim(&self) -> usize

Source

pub fn data(&self) -> &[f64]

Returns a reference to the data of the array

Source

pub fn rand_2d(rows: usize, cols: usize) -> Self

Creates a 2D array (matrix) of random numbers between 0 and 1

§Arguments
  • rows - The number of rows in the matrix.
  • cols - The number of columns in the matrix.
§Returns

A 2D NDArray filled with random numbers.

Source

pub fn randn(size: usize) -> Self

Creates a 1D array of random numbers following a normal distribution

§Arguments
  • size - The number of elements in the array.
§Returns

A 1D NDArray filled with random numbers from a normal distribution.

Source

pub fn randn_2d(rows: usize, cols: usize) -> Self

Creates a 2D array (matrix) of random numbers following a normal distribution

§Arguments
  • rows - The number of rows in the matrix.
  • cols - The number of columns in the matrix.
§Returns

A 2D NDArray filled with random numbers from a normal distribution.

Source

pub fn randint(low: i32, high: i32, size: usize) -> Self

Creates a 1D array of random integers between low and high

§Arguments
  • low - The lower bound (inclusive).
  • high - The upper bound (exclusive).
  • size - The number of elements in the array.
§Returns

A 1D NDArray filled with random integers.

Source

pub fn randint_2d(low: i32, high: i32, rows: usize, cols: usize) -> Self

Creates a 2D array (matrix) of random integers between low and high

§Arguments
  • low - The lower bound (inclusive).
  • high - The upper bound (exclusive).
  • rows - The number of rows in the matrix.
  • cols - The number of columns in the matrix.
§Returns

A 2D NDArray filled with random integers.

Source

pub fn reshape(&self, new_shape: Vec<isize>) -> Self

Reshapes the array to the specified shape, allowing one dimension to be inferred

§Arguments
  • new_shape - A vector representing the new shape, with at most one dimension as -1.
§Returns

A new NDArray with the specified shape.

Source

pub fn max(&self) -> f64

Returns the maximum value in the array

§Returns

The maximum value as an f64.

Source

pub fn argmax(&self) -> usize

Returns the index of the maximum value in the array

§Returns

The index of the maximum value.

Source

pub fn min(&self) -> f64

Returns the minimum value in the array

§Returns

The minimum value as an f64.

Source

pub fn from_vec_reshape(data: Vec<f64>, shape: Vec<usize>) -> Self

Creates an NDArray from a flat vector and a specified shape

§Arguments
  • data - A vector of f64 values representing the array’s data.
  • shape - A vector of usize values representing the dimensions of the array.
§Returns

A new NDArray instance.

Source

pub fn extract_sample(&self, sample_index: usize) -> Self

Extracts a single sample from a batch of N-dimensional arrays

§Arguments
  • sample_index - The index of the sample to extract
§Returns

A new NDArray containing just the specified sample with N-1 dimensions

Source

pub fn pretty_print(&self, precision: usize)

Pretty prints an N-dimensional array

§Arguments
  • precision - The number of decimal places to round each value to.
Source

pub fn get(&self, index: usize) -> f64

Returns a specific element from the array

§Arguments
  • index - The index of the element to retrieve.
§Returns

The element at the specified index.

Source

pub fn arange(start: f64, stop: f64, step: f64) -> Self

Creates a 1D array with a range of numbers

§Arguments
  • start - The starting value of the range (inclusive).
  • stop - The stopping value of the range (exclusive).
  • step - The step size between each value in the range.
§Returns

A 1D NDArray containing the range of numbers.

Source

pub fn zeros(size: usize) -> Self

Creates a 1D array filled with zeros

§Arguments
  • size - The number of elements in the array.
§Returns

A 1D NDArray filled with zeros.

Source

pub fn zeros_2d(rows: usize, cols: usize) -> Self

Creates a 2D array (matrix) filled with zeros

§Arguments
  • rows - The number of rows in the matrix.
  • cols - The number of columns in the matrix.
§Returns

A 2D NDArray filled with zeros.

Source

pub fn ones(size: usize) -> Self

Creates a 1D array filled with ones

§Arguments
  • size - The number of elements in the array.
§Returns

A 1D NDArray filled with ones.

Source

pub fn ones_2d(rows: usize, cols: usize) -> Self

Creates a 2D array (matrix) filled with ones

§Arguments
  • rows - The number of rows in the matrix.
  • cols - The number of columns in the matrix.
§Returns

A 2D NDArray filled with ones.

Source

pub fn linspace(start: f64, end: f64, num: usize, precision: usize) -> Self

Creates a 1D array with evenly spaced numbers over a specified interval

§Arguments
  • start - The starting value of the interval.
  • end - The ending value of the interval.
  • num - The number of evenly spaced samples to generate.
  • precision - The number of decimal places to round each value to.
§Returns

A 1D NDArray containing the evenly spaced numbers.

Source

pub fn eye(n: usize) -> Self

Creates an identity matrix of size n x n

§Arguments
  • n - The size of the identity matrix.
§Returns

An n x n identity matrix as an NDArray.

Source

pub fn rand(size: usize) -> Self

Creates a 1D array of random numbers between 0 and 1

§Arguments
  • size - The number of elements in the array.
§Returns

A 1D NDArray filled with random numbers.

Source

pub fn sub_matrix( &self, row_start: usize, row_end: usize, col_start: usize, col_end: usize, ) -> Self

Returns a sub-matrix from a 2D array

§Arguments
  • row_start - The starting row index of the sub-matrix.
  • row_end - The ending row index of the sub-matrix (exclusive).
  • col_start - The starting column index of the sub-matrix.
  • col_end - The ending column index of the sub-matrix (exclusive).
§Returns

A new NDArray representing the specified sub-matrix.

Source

pub fn set(&mut self, index: usize, value: f64)

Sets a specific element in the array

§Arguments
  • index - The index of the element to set.
  • value - The value to set the element to.
Source

pub fn set_range(&mut self, start: usize, end: usize, value: f64)

Sets a range of elements in the array to a specific value

§Arguments
  • start - The starting index of the range.
  • end - The ending index of the range (exclusive).
  • value - The value to set the elements to.
Source

pub fn copy(&self) -> Self

Returns a copy of the array

§Returns

A new NDArray that is a copy of the original.

Source

pub fn view(&self, start: usize, end: usize) -> &[f64]

Returns a view (slice) of the array from start to end (exclusive)

§Arguments
  • start - The starting index of the view.
  • end - The ending index of the view (exclusive).
§Returns

A slice of f64 values representing the specified view.

Source

pub fn view_mut(&mut self, start: usize, end: usize) -> &mut [f64]

Returns a mutable view (slice) of the array from start to end (exclusive)

§Arguments
  • start - The starting index of the view.
  • end - The ending index of the view (exclusive).
§Returns

A mutable slice of f64 values representing the specified view.

Source

pub fn get_2d(&self, row: usize, col: usize) -> f64

Returns a specific element from a 2D array

§Arguments
  • row - The row index of the element.
  • col - The column index of the element.
§Returns

The element at the specified row and column.

Source

pub fn set_2d(&mut self, row: usize, col: usize, value: f64)

Sets a specific element in a 2D array

§Arguments
  • row - The row index of the element.
  • col - The column index of the element.
  • value - The value to set the element to.
Source

pub fn new_axis(&self, axis: usize) -> Self

Adds a new axis to the array at the specified position

§Arguments
  • axis - The position at which to add the new axis.
§Returns

A new NDArray with an additional axis.

Source

pub fn expand_dims(&self, axis: usize) -> Self

Expands the dimensions of the array by adding a new axis at the specified index

§Arguments
  • axis - The index at which to add the new axis.
§Returns

A new NDArray with expanded dimensions.

Source

pub fn greater_than(&self, threshold: f64) -> Vec<bool>

Returns a boolean array indicating whether each element satisfies the condition

§Arguments
  • threshold - The threshold value to compare each element against.
§Returns

A vector of boolean values indicating whether each element is greater than the threshold.

Source

pub fn filter(&self, condition: impl Fn(&f64) -> bool) -> Self

Returns a new array containing only the elements that satisfy the condition

§Arguments
  • condition - A closure that takes an f64 and returns a boolean.
§Returns

A new NDArray containing only the elements that satisfy the condition.

Source

pub fn dtype(&self) -> &'static str

Returns the data type of the elements in the array

§Returns

A string representing the data type of the elements.

Source

pub fn size(&self) -> usize

Returns the total number of elements in the array

§Returns

The total number of elements in the array.

Source

pub fn argmin(&self) -> usize

Returns the index of the minimum value in the array

§Returns

The index of the minimum value.

Source

pub fn slice(&self, start: usize, end: usize) -> Self

Returns a slice of the array from start to end (exclusive)

§Arguments
  • start - The starting index of the slice.
  • end - The ending index of the slice (exclusive).
§Returns

A new NDArray containing the specified slice.

Source

pub fn one_hot_encode(labels: &NDArray) -> Self

Converts an NDArray of labels into a one-hot encoded NDArray

§Arguments
  • labels - An NDArray containing numerical labels
§Returns

A new NDArray with one-hot encoded labels where each row corresponds to one label

§Panics

Panics if the input contains non-integer values

Source§

impl NDArray

Source

pub fn nabla(X: &NDArray, y: &NDArray, y_pred: &NDArray, N: usize) -> Vec<f64>

Calculates the gradients (nabla) for linear regression with multiple features

§Arguments
  • X - The input feature matrix
  • y - The actual target values
  • y_pred - The predicted values
  • N - The number of samples
§Returns

A vector containing the gradients for each parameter

Source§

impl NDArray

Source

pub fn mean_squared_error(y_true: &NDArray, y_pred: &NDArray) -> f64

Calculates the Mean Squared Error (MSE) between two arrays

§Arguments
  • y_true - The true values as an NDArray.
  • y_pred - The predicted values as an NDArray.
§Returns

The MSE as a f64.

Source

pub fn cross_entropy_loss(y_true: &NDArray, y_pred: &NDArray) -> f64

Calculates the Cross-Entropy Loss between two arrays

§Arguments
  • y_true - The true values as an NDArray (one-hot encoded).
  • y_pred - The predicted probabilities as an NDArray.
§Returns

The Cross-Entropy Loss as a f64.

Source§

impl NDArray

Source

pub fn tanh(&self) -> Self

Calculates the hyperbolic tangent of each element in the array

§Returns

A new NDArray with the hyperbolic tangent of each element.

Source

pub fn relu(&self) -> Self

Applies the ReLU function to each element in the array

§Returns

A new NDArray with the ReLU function applied to each element.

Source

pub fn leaky_relu(&self, alpha: f64) -> Self

Applies the Leaky ReLU function to each element in the array

§Arguments
  • alpha - The slope for negative values.
§Returns

A new NDArray with the Leaky ReLU function applied to each element.

Source

pub fn sigmoid(&self) -> Self

Applies the Sigmoid function to each element in the array

§Returns

A new NDArray with the Sigmoid function applied to each element.

Source§

impl NDArray

Source

pub fn sqrt(&self) -> Self

Calculates the square root of each element in the array

§Returns

A new NDArray with the square root of each element.

Source

pub fn exp(&self) -> Self

Calculates the exponential (e^x) of each element in the array

§Returns

A new NDArray with the exponential of each element.

Source

pub fn sin(&self) -> Self

Calculates the sine of each element in the array

§Returns

A new NDArray with the sine of each element.

Source

pub fn cos(&self) -> Self

Calculates the cosine of each element in the array

§Returns

A new NDArray with the cosine of each element.

Source

pub fn ln(&self) -> Self

Calculates the natural logarithm of each element in the array

§Returns

A new NDArray with the natural logarithm of each element.

Source§

impl NDArray

Source

pub fn linear_regression( X: &NDArray, y: &NDArray, alpha: f64, epochs: usize, ) -> (Vec<f64>, Vec<f64>)

Performs linear regression using gradient descent with multiple features

§Arguments
  • X - The input feature matrix as an NDArray.
  • y - The output target as an NDArray.
  • alpha - The learning rate.
  • epochs - The number of iterations for gradient descent.
§Returns

A tuple containing the optimized parameters and the history of MSE for each epoch.

Source§

impl NDArray

Represents a dataset split into training and testing sets

Source

pub fn mnist_csv_to_nab( csv_path: &str, images_path: &str, labels_path: &str, image_shape: Vec<usize>, ) -> Result<()>

Converts MNIST CSV data to image and label .nab files

§Arguments
  • csv_path - Path to the CSV file
  • images_path - Path where to save the images .nab file
  • labels_path - Path where to save the labels .nab file
  • image_shape - Shape of a single image (e.g., [28, 28])

Trait Implementations§

Source§

impl Add<f64> for NDArray

Source§

type Output = NDArray

The resulting type after applying the + operator.
Source§

fn add(self, scalar: f64) -> Self::Output

Performs the + operation. Read more
Source§

impl Add for NDArray

Source§

type Output = NDArray

The resulting type after applying the + operator.
Source§

fn add(self, other: Self) -> Self::Output

Performs the + operation. Read more
Source§

impl Clone for NDArray

Source§

fn clone(&self) -> NDArray

Returns a copy 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 Debug for NDArray

Source§

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

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

impl Display for NDArray

Source§

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

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

impl Mul<f64> for NDArray

Source§

type Output = NDArray

The resulting type after applying the * operator.
Source§

fn mul(self, scalar: f64) -> Self::Output

Performs the * operation. Read more
Source§

impl Sub for NDArray

Source§

type Output = NDArray

The resulting type after applying the - operator.
Source§

fn sub(self, other: Self) -> Self::Output

Performs the - operation. Read more

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, dst: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dst. 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> ToString for T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

Converts the given value to a String. 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