Struct Tensor

Source
pub struct Tensor<T, const N: usize, A: TensorAllocator> {
    pub storage: TensorStorage<T, A>,
    pub shape: [usize; N],
    pub strides: [usize; N],
}
Expand description

A data structure to represent a multi-dimensional tensor.

NOTE: Internally, the data is stored as an arrow::ScalarBuffer which represents a contiguous memory region that can be shared with other buffers and across thread boundaries.

§Attributes

  • storage - The storage of the tensor.
  • shape - The shape of the tensor.
  • strides - The strides of the tensor data in memory.

§Example

use kornia_core::{Tensor, CpuAllocator};

let data: Vec<u8> = vec![1, 2, 3, 4];
let t = Tensor::<u8, 2, CpuAllocator>::from_shape_vec([2, 2], data, CpuAllocator).unwrap();
assert_eq!(t.shape, [2, 2]);

Fields§

§storage: TensorStorage<T, A>

The storage of the tensor.

§shape: [usize; N]

The shape of the tensor.

§strides: [usize; N]

The strides of the tensor data in memory.

Implementations§

Source§

impl<T, const N: usize, A> Tensor<T, N, A>
where A: 'static + TensorAllocator,

Source

pub fn as_slice(&self) -> &[T]

Get the data of the tensor as a slice.

§Returns

A slice containing the data of the tensor.

Source

pub fn as_slice_mut(&mut self) -> &mut [T]

Get the data of the tensor as a mutable slice.

§Returns

A mutable slice containing the data of the tensor.

Source

pub fn as_ptr(&self) -> *const T

Get the data of the tensor as a pointer.

§Returns

A pointer to the data of the tensor.

Source

pub fn as_mut_ptr(&mut self) -> *mut T

Get the data of the tensor as a mutable pointer.

§Returns

A mutable pointer to the data of the tensor.

Source

pub fn into_vec(self) -> Vec<T>

Consumes the tensor and returns the underlying vector.

This method destroys the tensor and returns ownership of the underlying data. The returned vector will have a length equal to the total number of elements in the tensor.

Source

pub fn from_shape_vec( shape: [usize; N], data: Vec<T>, alloc: A, ) -> Result<Self, TensorError>

Creates a new Tensor with the given shape and data.

§Arguments
  • shape - An array containing the shape of the tensor.
  • data - A vector containing the data of the tensor.
  • alloc - The allocator to use.
§Returns

A new Tensor instance.

§Errors

If the number of elements in the data does not match the shape of the tensor, an error is returned.

§Example
use kornia_core::{Tensor, CpuAllocator};

let data: Vec<u8> = vec![1, 2, 3, 4];
let t = Tensor::<u8, 2, CpuAllocator>::from_shape_vec([2, 2], data, CpuAllocator).unwrap();
assert_eq!(t.shape, [2, 2]);
Source

pub fn from_shape_slice( shape: [usize; N], data: &[T], alloc: A, ) -> Result<Self, TensorError>
where T: Clone,

Creates a new Tensor with the given shape and slice of data.

§Arguments
  • shape - An array containing the shape of the tensor.
  • data - A slice containing the data of the tensor.
  • alloc - The allocator to use.
§Returns

A new Tensor instance.

§Errors

If the number of elements in the data does not match the shape of the tensor, an error is returned.

Source

pub fn from_shape_val(shape: [usize; N], value: T, alloc: A) -> Self
where T: Clone,

Creates a new Tensor with the given shape and a default value.

§Arguments
  • shape - An array containing the shape of the tensor.
  • value - The default value to fill the tensor with.
§Returns

A new Tensor instance.

§Example
use kornia_core::{Tensor, CpuAllocator};

let t = Tensor::<u8, 1, CpuAllocator>::from_shape_val([4], 0, CpuAllocator);
assert_eq!(t.as_slice(), vec![0, 0, 0, 0]);

let t = Tensor::<u8, 2, CpuAllocator>::from_shape_val([2, 2], 1, CpuAllocator);
assert_eq!(t.as_slice(), vec![1, 1, 1, 1]);

let t = Tensor::<u8, 3, CpuAllocator>::from_shape_val([2, 1, 3], 2, CpuAllocator);
assert_eq!(t.as_slice(), vec![2, 2, 2, 2, 2, 2]);
Source

pub fn from_shape_fn<F>(shape: [usize; N], alloc: A, f: F) -> Self
where F: Fn([usize; N]) -> T,

Create a new Tensor with the given shape and a function to generate the data.

The function f is called with the index of the element to generate.

§Arguments
  • shape - An array containing the shape of the tensor.
  • f - The function to generate the data.
§Returns

A new Tensor instance.

§Example
use kornia_core::{Tensor, CpuAllocator};

let t = Tensor::<u8, 1, CpuAllocator>::from_shape_fn([4], CpuAllocator, |[i]| i as u8);
assert_eq!(t.as_slice(), vec![0, 1, 2, 3]);

let t = Tensor::<u8, 2, CpuAllocator>::from_shape_fn([2, 2], CpuAllocator, |[i, j]| (i * 2 + j) as u8);
assert_eq!(t.as_slice(), vec![0, 1, 2, 3]);
Source

pub fn numel(&self) -> usize

Returns the number of elements in the tensor.

§Returns

The number of elements in the tensor.

Source

pub fn get_iter_offset(&self, index: [usize; N]) -> Option<usize>

Get the offset of the element at the given index.

§Arguments
  • index - The list of indices to get the element from.
§Returns

The offset of the element at the given index.

Source

pub fn get_iter_offset_unchecked(&self, index: [usize; N]) -> usize

Get the offset of the element at the given index without checking dim sizes.

§Arguments
  • index - The list of indices to get the element from.
§Returns

The offset of the element at the given index.

Source

pub fn get_index_unchecked(&self, offset: usize) -> [usize; N]

Get the index of the element at the given offset without checking dim sizes. The reverse of Self::get_iter_offset_unchecked.

§Arguments
  • offset - The offset of the element at the given index.
§Returns

The array of indices to get the element from.

Source

pub fn get_index(&self, offset: usize) -> Result<[usize; N], TensorError>

Get the index of the element at the given offset. The reverse of Self::get_iter_offset.

§Arguments
  • offset - The offset of the element at the given index.
§Returns

The array of indices to get the element from.

§Errors

If the offset is out of bounds (>= numel), an error is returned.

Source

pub fn get_unchecked(&self, index: [usize; N]) -> &T

Get the element at the given index without checking if the index is out of bounds.

§Arguments
  • index - The list of indices to get the element from.
§Returns

A reference to the element at the given index.

§Example
use kornia_core::{Tensor, CpuAllocator};

let data: Vec<u8> = vec![1, 2, 3, 4];

let t = Tensor::<u8, 2, CpuAllocator>::from_shape_vec([2, 2], data, CpuAllocator).unwrap();
assert_eq!(*t.get_unchecked([0, 0]), 1);
assert_eq!(*t.get_unchecked([0, 1]), 2);
assert_eq!(*t.get_unchecked([1, 0]), 3);
assert_eq!(*t.get_unchecked([1, 1]), 4);
Source

pub fn get(&self, index: [usize; N]) -> Option<&T>

Get the element at the given index, checking if the index is out of bounds.

§Arguments
  • index - The list of indices to get the element from.
§Returns

A reference to the element at the given index.

§Errors

If the index is out of bounds, an error is returned.

§Example
use kornia_core::{Tensor, CpuAllocator};

let data: Vec<u8> = vec![1, 2, 3, 4];

let t = Tensor::<u8, 2, CpuAllocator>::from_shape_vec([2, 2], data, CpuAllocator).unwrap();

assert_eq!(t.get([0, 0]), Some(&1));
assert_eq!(t.get([0, 1]), Some(&2));
assert_eq!(t.get([1, 0]), Some(&3));
assert_eq!(t.get([1, 1]), Some(&4));

assert!(t.get([2, 0]).is_none());
Source

pub fn reshape<const M: usize>( &self, shape: [usize; M], ) -> Result<TensorView<'_, T, M, A>, TensorError>

Reshape the tensor to a new shape.

§Arguments
  • shape - The new shape of the tensor.
§Returns

A new TensorView instance.

§Errors

If the number of elements in the new shape does not match the number of elements in the tensor, an error is returned.

§Example
use kornia_core::{Tensor, CpuAllocator};

let data: Vec<u8> = vec![1, 2, 3, 4];

let t = Tensor::<u8, 1, CpuAllocator>::from_shape_vec([4], data, CpuAllocator).unwrap();
let t2 = t.reshape([2, 2]).unwrap();
assert_eq!(t2.shape, [2, 2]);
assert_eq!(t2.as_slice(), vec![1, 2, 3, 4]);
assert_eq!(t2.strides, [2, 1]);
assert_eq!(t2.numel(), 4);
Source

pub fn permute_axes(&self, axes: [usize; N]) -> TensorView<'_, T, N, A>

Permute the dimensions of the tensor.

The permutation is given as an array of indices, where the value at each index is the new index of the dimension. The data is not moved, only the order of the dimensions is changed.

§Arguments
  • axes - The new order of the dimensions.
§Returns

A view of the tensor with the dimensions permuted.

Source

pub fn view(&self) -> TensorView<'_, T, N, A>

Return a view of the tensor.

The view is a reference to the tensor storage with a different shape and strides.

§Returns

A TensorView instance.

Source

pub fn zeros(shape: [usize; N], alloc: A) -> Tensor<T, N, A>
where T: Clone + Zero,

Create a new tensor with all elements set to zero.

§Arguments
  • shape - The shape of the tensor.
  • alloc - The allocator to use.
§Returns
Source

pub fn map<U, F>(&self, f: F) -> Tensor<U, N, A>
where F: Fn(&T) -> U,

Apply a function to each element of the tensor.

§Arguments
  • f - The function to apply to each element.
§Returns

A new Tensor instance.

§Example
use kornia_core::{Tensor, CpuAllocator};

let data: Vec<u8> = vec![1, 2, 3, 4];
let t = Tensor::<u8, 1, CpuAllocator>::from_shape_vec([4], data, CpuAllocator).unwrap();

let t2 = t.map(|x| *x + 1);
assert_eq!(t2.as_slice(), vec![2, 3, 4, 5]);
Source

pub fn powi(&self, n: i32) -> Tensor<T, N, A>
where T: Float,

Apply the power function to the pixel data.

§Arguments
  • n - The power to raise the pixel data to.
§Returns

A new image with the pixel data raised to the power.

Source

pub fn abs(&self) -> Tensor<T, N, A>
where T: Float,

Compute absolute value of the pixel data.

§Returns

A new image with the pixel data absolute value.

Source

pub fn mean(&self) -> Result<T, TensorError>
where T: Float,

Compute the mean of the pixel data.

§Returns

The mean of the pixel data.

Source

pub fn cast<U>(&self) -> Tensor<U, N, CpuAllocator>
where U: From<T>, T: Clone,

Cast the tensor to a new type.

§Returns

A new Tensor instance.

§Example
use kornia_core::{Tensor, CpuAllocator};

let data: Vec<u8> = vec![1, 2, 3, 4];
let t = Tensor::<u8, 1, CpuAllocator>::from_shape_vec([4], data, CpuAllocator).unwrap();

let t2 = t.cast::<f32>();
assert_eq!(t2.as_slice(), vec![1.0, 2.0, 3.0, 4.0]);
Source

pub fn element_wise_op<F>( &self, other: &Tensor<T, N, CpuAllocator>, op: F, ) -> Result<Tensor<T, N, CpuAllocator>, TensorError>
where F: Fn(&T, &T) -> T,

Perform an element-wise operation on two tensors.

§Arguments
  • other - The other tensor to perform the operation with.
  • op - The operation to perform.
§Returns

A new Tensor instance.

§Example
use kornia_core::{Tensor, CpuAllocator};

let data1: Vec<u8> = vec![1, 2, 3, 4];
let t1 = Tensor::<u8, 1, CpuAllocator>::from_shape_vec([4], data1, CpuAllocator).unwrap();

let data2: Vec<u8> = vec![1, 2, 3, 4];
let t2 = Tensor::<u8, 1, CpuAllocator>::from_shape_vec([4], data2, CpuAllocator).unwrap();

let t3 = t1.element_wise_op(&t2, |a, b| *a + *b).unwrap();
assert_eq!(t3.as_slice(), vec![2, 4, 6, 8]);

let t4 = t1.element_wise_op(&t2, |a, b| *a - *b).unwrap();
assert_eq!(t4.as_slice(), vec![0, 0, 0, 0]);

let t5 = t1.element_wise_op(&t2, |a, b| *a * *b).unwrap();
assert_eq!(t5.as_slice(), vec![1, 4, 9, 16]);

let t6 = t1.element_wise_op(&t2, |a, b| *a / *b).unwrap();
assert_eq!(t6.as_slice(), vec![1, 1, 1, 1]);
Source

pub fn add( &self, other: &Tensor<T, N, CpuAllocator>, ) -> Tensor<T, N, CpuAllocator>
where T: Add<Output = T> + Clone,

Perform an element-wise addition on two tensors.

§Arguments
  • other - The other tensor to add.
§Returns

A new Tensor instance.

§Example
use kornia_core::{Tensor, CpuAllocator};

let data1: Vec<u8> = vec![1, 2, 3, 4];
let t1 = Tensor::<u8, 1, CpuAllocator>::from_shape_vec([4], data1, CpuAllocator).unwrap();

let data2: Vec<u8> = vec![1, 2, 3, 4];
let t2 = Tensor::<u8, 1, CpuAllocator>::from_shape_vec([4], data2, CpuAllocator).unwrap();

let t3 = t1.add(&t2);
assert_eq!(t3.as_slice(), vec![2, 4, 6, 8]);
Source

pub fn sub( &self, other: &Tensor<T, N, CpuAllocator>, ) -> Tensor<T, N, CpuAllocator>
where T: Sub<Output = T> + Clone,

Perform an element-wise subtraction on two tensors.

§Arguments
  • other - The other tensor to subtract.
§Returns

A new Tensor instance.

§Example
use kornia_core::{Tensor, CpuAllocator};

let data1: Vec<u8> = vec![1, 2, 3, 4];
let t1 = Tensor::<u8, 1, CpuAllocator>::from_shape_vec([4], data1, CpuAllocator).unwrap();

let data2: Vec<u8> = vec![1, 2, 3, 4];
let t2 = Tensor::<u8, 1, CpuAllocator>::from_shape_vec([4], data2, CpuAllocator).unwrap();

let t3 = t1.sub(&t2);
assert_eq!(t3.as_slice(), vec![0, 0, 0, 0]);
Source

pub fn mul( &self, other: &Tensor<T, N, CpuAllocator>, ) -> Tensor<T, N, CpuAllocator>
where T: Mul<Output = T> + Clone,

Perform an element-wise multiplication on two tensors.

§Arguments
  • other - The other tensor to multiply.
§Returns

A new Tensor instance.

§Example
use kornia_core::{Tensor, CpuAllocator};

let data1: Vec<u8> = vec![1, 2, 3, 4];
let t1 = Tensor::<u8, 1, CpuAllocator>::from_shape_vec([4], data1, CpuAllocator).unwrap();

let data2: Vec<u8> = vec![1, 2, 3, 4];
let t2 = Tensor::<u8, 1, CpuAllocator>::from_shape_vec([4], data2, CpuAllocator).unwrap();

let t3 = t1.mul(&t2);
assert_eq!(t3.as_slice(), vec![1, 4, 9, 16]);
Source

pub fn div( &self, other: &Tensor<T, N, CpuAllocator>, ) -> Tensor<T, N, CpuAllocator>
where T: Div<Output = T> + Clone,

Perform an element-wise division on two tensors.

§Arguments
  • other - The other tensor to divide.
§Returns

A new Tensor instance.

§Example
use kornia_core::{Tensor, CpuAllocator};

let data1: Vec<u8> = vec![1, 2, 3, 4];
let t1 = Tensor::<u8, 1, CpuAllocator>::from_shape_vec([4], data1, CpuAllocator).unwrap();

let data2: Vec<u8> = vec![1, 2, 3, 4];
let t2 = Tensor::<u8, 1, CpuAllocator>::from_shape_vec([4], data2, CpuAllocator).unwrap();

let t3 = t1.div(&t2);
assert_eq!(t3.as_slice(), vec![1, 1, 1, 1]);

Trait Implementations§

Source§

impl<T, const N: usize, A> Clone for Tensor<T, N, A>
where T: Clone, A: TensorAllocator + Clone + 'static,

Source§

fn clone(&self) -> Self

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<'de, T, const N: usize, A: TensorAllocator + Default + 'static> Deserialize<'de> for Tensor<T, N, A>
where T: Deserialize<'de>,

Source§

fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
Source§

impl<T, const N: usize, A> Display for Tensor<T, N, A>
where T: Display + LowerExp, A: TensorAllocator + 'static,

Source§

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

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

impl<T, const N: usize, A> Serialize for Tensor<T, N, A>
where T: Serialize, A: TensorAllocator + 'static,

Source§

fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: Serializer,

Serialize this value into the given Serde serializer. Read more

Auto Trait Implementations§

§

impl<T, const N: usize, A> Freeze for Tensor<T, N, A>
where A: Freeze,

§

impl<T, const N: usize, A> RefUnwindSafe for Tensor<T, N, A>

§

impl<T, const N: usize, A> Send for Tensor<T, N, A>

§

impl<T, const N: usize, A> Sync for Tensor<T, N, A>

§

impl<T, const N: usize, A> Unpin for Tensor<T, N, A>
where A: Unpin,

§

impl<T, const N: usize, A> UnwindSafe for Tensor<T, N, A>

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> 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<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,