Tensor

Struct Tensor 

Source
pub struct Tensor {
    pub data: Array,
    pub grad: Option<Rc<RefCell<Array>>>,
    pub requires_grad: bool,
    pub compute_node: Option<Rc<ComputeNode>>,
    pub is_leaf: bool,
}
Expand description

Tensor con soporte para autograd

Fields§

§data: Array

Datos del tensor

§grad: Option<Rc<RefCell<Array>>>

Gradiente acumulado (dL/d(este tensor))

§requires_grad: bool

Si este tensor requiere gradientes

§compute_node: Option<Rc<ComputeNode>>

Nodo del compute graph (None para leaf tensors)

§is_leaf: bool

Si es un leaf tensor (parámetro del modelo)

Implementations§

Source§

impl Tensor

Source

pub fn add(&self, other: &Tensor) -> Result<Self>

Add: self + other

Source

pub fn sub(&self, other: &Tensor) -> Result<Self>

Sub: self - other

Source

pub fn mul(&self, other: &Tensor) -> Result<Self>

Mul (elementwise): self * other

Source

pub fn div(&self, other: &Tensor) -> Result<Self>

Div: self / other

Source

pub fn matmul(&self, other: &Tensor) -> Result<Self>

MatMul: self @ other

Source

pub fn relu(&self) -> Result<Self>

ReLU: max(0, self)

Source

pub fn sigmoid(&self) -> Result<Self>

Sigmoid: 1 / (1 + exp(-self))

Source

pub fn exp(&self) -> Result<Self>

Exp: exp(self)

Source

pub fn log(&self) -> Result<Self>

Log: log(self)

Source

pub fn sum(&self) -> Result<Self>

Sum: suma todos los elementos

Source

pub fn mean(&self) -> Result<Self>

Mean: promedio de todos los elementos

Source

pub fn mse_loss(&self, target: &Tensor) -> Result<Self>

MSE Loss: mean((self - target)^2)

Source

pub fn cross_entropy_loss(&self, target: &Tensor) -> Result<Self>

Cross-entropy loss con softmax integrado (Batch-aware)

Source

pub fn flatten(&self, start_dim: usize, end_dim: usize) -> Result<Self>

Flatten: flatten(start, end)

Source

pub fn reshape(&self, shape: Vec<usize>) -> Result<Self>

Reshape: input.reshape([d1, d2, …])

Source

pub fn conv1d( &self, weight: &Tensor, bias: Option<&Tensor>, stride: usize, padding: usize, ) -> Result<Self>

Conv1D

Source

pub fn batch_norm( &self, running_mean: &mut Tensor, running_var: &mut Tensor, weight: &Tensor, bias: &Tensor, training: bool, momentum: f32, eps: f32, ) -> Result<Self>

BatchNorm

Source

pub fn dropout(&self, p: f32, training: bool) -> Result<Self>

Dropout

Source

pub fn pow(&self, exponent: f32) -> Result<Self>

Pow: self^exponent

Source

pub fn sqrt(&self) -> Result<Self>

Sqrt: sqrt(self)

Source

pub fn sin(&self) -> Result<Self>

Sin: sin(self)

Source

pub fn cos(&self) -> Result<Self>

Cos: cos(self)

Source

pub fn tan(&self) -> Result<Self>

Tan: tan(self)

Source

pub fn tanh(&self) -> Result<Self>

Tanh: tanh(self)

Source§

impl Tensor

Source

pub fn new(data: Array, requires_grad: bool) -> Self

Crea un nuevo tensor desde un Array

§Argumentos
  • data: Array con los datos
  • requires_grad: Si se deben calcular gradientes para este tensor
Source

pub fn from_operation( data: Array, compute_node: ComputeNode, requires_grad: bool, ) -> Self

Crea tensor desde resultado de operación

Source

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

Acceso directo a la forma

Source

pub fn values(&self) -> &[f32]

Acceso directo a los datos

Source

pub fn gradient(&self) -> Option<Array>

Obtiene el gradiente actual (si existe)

Source

pub fn item(&self) -> f32

Obtiene el valor escalar de un tensor de 1 elemento

Source

pub fn set_gradient(&self, grad: Array) -> Result<()>

Establece el gradiente manualmente

Source

pub fn accumulate_gradient(&self, incoming_grad: &Array) -> Result<()>

Acumula gradiente (grad += incoming_grad)

Source

pub fn zero_grad(&self)

Resetea el gradiente a cero

Source

pub fn detach(&self) -> Self

Desconecta del compute graph (detach) Retorna un nuevo tensor sin gradientes

Source

pub fn to_array(&self) -> Array

Convierte a Array (sin autograd)

Source

pub fn node_id(&self) -> Option<NodeId>

Obtiene el ID del nodo en el compute graph

Source

pub fn backward(&self) -> Result<()>

Backpropagation - Calcula gradientes desde este tensor hacia las hojas

Este es el algoritmo principal de autograd:

  1. Inicializa grad = 1.0 para este tensor (dL/dL = 1)
  2. Recorre el graph en orden topológico inverso
  3. Para cada operación, llama su backward_fn
  4. Acumula gradientes en los inputs
Source

pub fn transpose(&self) -> Result<Tensor>

Transpose del tensor (invierte dimensiones)

Trait Implementations§

Source§

impl Clone for Tensor

Source§

fn clone(&self) -> Tensor

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

Source§

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

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

impl Display for Tensor

Source§

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

Formats the value using the given formatter. Read more

Auto Trait Implementations§

§

impl Freeze for Tensor

§

impl !RefUnwindSafe for Tensor

§

impl !Send for Tensor

§

impl !Sync for Tensor

§

impl Unpin for Tensor

§

impl !UnwindSafe for Tensor

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

Source§

fn downcast(&self) -> &T

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

Source§

fn upcast(&self) -> Option<&T>