mat

package
v1.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 30, 2023 License: BSD-2-Clause Imports: 16 Imported by: 29

Documentation

Overview

Package mattest provides utilities for testing code involving spaGO matrices.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Abs

func Abs[T float.DType](x T) T

Abs returns the absolute value of x.

func AssertMatrixEquals added in v1.1.0

func AssertMatrixEquals(t T, expected, actual Tensor, args ...any) bool

AssertMatrixEquals tests whether expected is equal to actual; if not, T.Error or T.Errorf are called, providing useful information.

It returns whether the comparison succeeded.

The expected matrix is not allowed to be nil, otherwise the function always produces an error.

func AssertMatrixInDelta added in v1.1.0

func AssertMatrixInDelta(t T, expected, actual Matrix, delta float64, args ...any) bool

AssertMatrixInDelta tests whether expected and actual have the same shape and all elements at the same positions are within delta; if not, T.Error or T.Errorf are called, providing useful information.

It returns whether the comparison succeeded.

The expected matrix is not allowed to be nil, otherwise the function always produces an error.

func Ceil

func Ceil[T float.DType](x T) T

Ceil returns the least integer value greater than or equal to x.

func Cos

func Cos[T float.DType](x T) T

Cos returns the cosine of the radian argument x.

func Cosh

func Cosh[T float.DType](x T) T

Cosh returns the hyperbolic cosine of x.

func CreateIdentityMatrix added in v1.1.0

func CreateIdentityMatrix[T float.DType](size int) []T

func CreateInitializedSlice added in v1.1.0

func CreateInitializedSlice[T float.DType](size int, v T) []T

func CreateOneHotVector added in v1.1.0

func CreateOneHotVector[T float.DType](size int, index int) []T

func Data

func Data[T float.DType](m Tensor) []T

Data returns the underlying data of the matrix, as a raw one-dimensional slice of values in row-major order.

func Equal

func Equal(a, b Tensor) bool

Equal reports whether matrices a and b have the same shape and elements.

func Exp

func Exp[T float.DType](x T) T

Exp returns e**x, the base-e exponential of x.

func Floor

func Floor[T float.DType](x T) T

Floor returns the greatest integer value less than or equal to x.

func InDelta

func InDelta(a, b Matrix, delta float64) bool

InDelta reports whether matrices a and b have the same shape and all elements at the same positions are within delta.

func Inf

func Inf[T float.DType](sign int) T

Inf returns positive infinity if sign >= 0, negative infinity if sign < 0.

func InitializeMatrix added in v1.1.0

func InitializeMatrix[T float.DType](rows, cols int, fn func(r, c int) T) []T

func IsInf

func IsInf[T float.DType](f T, sign int) bool

IsInf reports whether f is an infinity, according to sign.

func IsScalar

func IsScalar(m Tensor) bool

IsScalar returns whether the matrix contains exactly one scalar value (dimensions 1×1).

func IsVector

func IsVector(m Tensor) bool

IsVector returns whether the matrix is either a row or column vector (dimensions N×1 or 1×N).

func Log

func Log[T float.DType](x T) T

Log returns the natural logarithm of x.

func Max

func Max[T float.DType](x, y T) T

Max returns the larger of x or y.

func NaN

func NaN[T float.DType]() T

NaN returns an IEEE 754 “not-a-number” value.

func Pi

func Pi[T float.DType]() T

Pi mathematical constant.

func Pow

func Pow[T float.DType](x, y T) T

Pow returns x**y, the base-x exponential of y.

func RequireMatrixEquals added in v1.1.0

func RequireMatrixEquals(t T, expected, actual Matrix, args ...any)

RequireMatrixEquals tests whether expected is equal to actual; if not, T.Error or T.Errorf are called, providing useful information, followed by T.FailNow.

The expected matrix is not allowed to be nil, otherwise the function always produces an error and fails.

func RequireMatrixInDelta added in v1.1.0

func RequireMatrixInDelta(t T, expected, actual Matrix, delta float64, args ...any)

RequireMatrixInDelta tests whether expected and actual have the same shape and all elements at the same positions are within delta; if not, T.Error or T.Errorf are called, providing useful information, followed by T.FailNow.

The expected matrix is not allowed to be nil, otherwise the function always produces an error and fails.

func Round

func Round[T float.DType](x T) T

Round returns the nearest integer, rounding half away from zero.

func SameDims

func SameDims(a, b Tensor) bool

SameDims reports whether the two matrices have the same dimensions.

func SetData

func SetData[T float.DType](m Tensor, data []T)

SetData sets the content of the matrix, copying the given raw data representation as one-dimensional slice.

func Sin

func Sin[T float.DType](x T) T

Sin returns the sine of the radian argument x.

func Sinh

func Sinh[T float.DType](x T) T

Sinh returns the hyperbolic sine of x.

func SmallestNonzero

func SmallestNonzero[T float.DType]() T

SmallestNonzero returns the smallest positive, non-zero value representable by the type.

func Sqrt

func Sqrt[T float.DType](x T) T

Sqrt returns the square root of x.

func Tan

func Tan[T float.DType](x T) T

Tan returns the tangent of the radian argument x.

func Tanh

func Tanh[T float.DType](x T) T

Tanh returns the hyperbolic tangent of x.

Types

type Dense

type Dense[T float.DType] struct {
	// contains filtered or unexported fields
}

A Dense matrix implementation.

func ConcatV

func ConcatV[T float.DType](vs ...Matrix) *Dense[T]

ConcatV concatenates two or more vectors "vertically", creating a new Dense column vector. It accepts row or column vectors indifferently, virtually treating all of them as column vectors.

func NewDense

func NewDense[T float.DType](opts ...OptionsFunc) *Dense[T]

func Scalar added in v1.1.0

func Scalar[T float.DType](value T, opts ...OptionsFunc) *Dense[T]

func Stack

func Stack[T float.DType](vs ...Matrix) *Dense[T]

Stack stacks two or more vectors of the same size on top of each other, creating a new Dense matrix where each row contains the data of each input vector. It accepts row or column vectors indifferently, virtually treating all of them as row vectors.

func (*Dense[T]) Abs

func (d *Dense[T]) Abs() Matrix

Abs returns a new matrix applying the absolute value function to all elements.

func (*Dense[T]) AccGrad added in v1.1.0

func (d *Dense[T]) AccGrad(grad Tensor)

AccGrad accumulates the gradients. It accumulates the gradients even if the requiresGrad flag is false.

func (*Dense[T]) Add

func (d *Dense[T]) Add(other Matrix) Matrix

Add returns the addition between the receiver and another matrix.

func (*Dense[T]) AddInPlace

func (d *Dense[T]) AddInPlace(other Matrix) Matrix

AddInPlace performs the in-place addition with the other matrix.

func (*Dense[T]) AddScalar

func (d *Dense[T]) AddScalar(n float64) Matrix

AddScalar performs the addition between the matrix and the given value.

func (*Dense[T]) AddScalarInPlace

func (d *Dense[T]) AddScalarInPlace(n float64) Matrix

AddScalarInPlace adds the scalar to all values of the matrix.

func (*Dense[T]) AppendRows

func (d *Dense[T]) AppendRows(vs ...Matrix) Matrix

AppendRows returns a copy of the matrix with len(vs) additional tail rows, being each new row filled with the values of each given vector.

It accepts row or column vectors indifferently, virtually treating all of them as row vectors.

func (*Dense[T]) Apply

func (d *Dense[T]) Apply(fn func(r, c int, v float64) float64) Matrix

Apply creates a new matrix executing the unary function fn.

func (*Dense[T]) ApplyInPlace

func (d *Dense[T]) ApplyInPlace(fn func(r, c int, v float64) float64, a Matrix) Matrix

ApplyInPlace executes the unary function fn over the matrix `a`, and stores the result in the receiver, returning the receiver itself.

func (*Dense[T]) ApplyWithAlpha

func (d *Dense[T]) ApplyWithAlpha(fn func(r, c int, v float64, alpha ...float64) float64, alpha ...float64) Matrix

ApplyWithAlpha creates a new matrix executing the unary function fn, taking additional alpha.

func (*Dense[T]) ApplyWithAlphaInPlace

func (d *Dense[T]) ApplyWithAlphaInPlace(fn func(r, c int, v float64, alpha ...float64) float64, a Matrix, alpha ...float64) Matrix

ApplyWithAlphaInPlace executes the unary function fn over the matrix `a`, taking additional parameters alpha, and stores the result in the receiver, returning the receiver itself.

func (*Dense[T]) ArgMax

func (d *Dense[T]) ArgMax() int

ArgMax returns the index of the vector's element with the maximum value.

func (*Dense[T]) At

func (d *Dense[T]) At(i ...int) Tensor

At returns the value at the given indices. It panics if the given indices are out of range.

func (*Dense[T]) Augment

func (d *Dense[T]) Augment() Matrix

Augment places the identity matrix at the end of the original matrix.

func (*Dense[T]) ClipInPlace

func (d *Dense[T]) ClipInPlace(min, max float64) Matrix

ClipInPlace clips in place each value of the matrix.

func (*Dense[T]) Clone

func (d *Dense[T]) Clone() Matrix

Clone returns a new matrix, copying all its values from the receiver.

func (*Dense[T]) Copy

func (d *Dense[T]) Copy(other Matrix)

Copy copies the data from the other matrix to the receiver. It panics if the matrices have different dimensions.

func (*Dense[T]) CumSum

func (d *Dense[T]) CumSum() Matrix

CumSum computes the cumulative sum of the vector's elements, returning the result as a new column vector.

func (*Dense[T]) Data

func (d *Dense[T]) Data() float.Slice

Data returns the underlying data of the matrix, as a raw one-dimensional slice of values in row-major order.

func (*Dense[_]) Dims

func (d *Dense[_]) Dims() int

Dims returns the number of dimensions.

func (*Dense[T]) Div

func (d *Dense[T]) Div(other Matrix) Matrix

Div returns the result of the element-wise division of the receiver by the other matrix.

func (*Dense[T]) DivInPlace

func (d *Dense[T]) DivInPlace(other Matrix) Matrix

DivInPlace performs the in-place element-wise division of the receiver by the other matrix.

func (*Dense[T]) DoNonZero

func (d *Dense[T]) DoNonZero(fn func(r, c int, v float64))

DoNonZero calls a function for each non-zero element of the matrix. The parameters of the function are the element's indices and value.

func (*Dense[T]) DoVecNonZero

func (d *Dense[T]) DoVecNonZero(fn func(i int, v float64))

DoVecNonZero calls a function for each non-zero element of the vector. The parameters of the function are the element's index and value.

func (*Dense[T]) DotUnitary

func (d *Dense[T]) DotUnitary(other Matrix) Matrix

DotUnitary returns the dot product of two vectors as a scalar Matrix.

func (*Dense[T]) Exp

func (d *Dense[T]) Exp() Matrix

Exp returns a new matrix applying the base-e exponential function to each element.

func (*Dense[T]) ExtractColumn

func (d *Dense[T]) ExtractColumn(i int) Matrix

ExtractColumn returns a copy of the i-th column of the matrix, as a column vector (rows×1).

func (*Dense[T]) ExtractRow

func (d *Dense[T]) ExtractRow(i int) Matrix

ExtractRow returns a copy of the i-th row of the matrix, as a row vector (1×cols).

func (*Dense[T]) Flatten

func (d *Dense[T]) Flatten() Matrix

Flatten creates a new row vector (1×size) corresponding to the "flattened" row-major ordered representation of the initial matrix.

func (*Dense[T]) FlattenInPlace

func (d *Dense[T]) FlattenInPlace() Matrix

FlattenInPlace transforms the matrix in place, changing its dimensions, obtaining a row vector (1×size) containing the "flattened" row-major ordered representation of the initial value. It returns the matrix itself.

func (*Dense[_]) Format

func (d *Dense[_]) Format(f fmt.State, c rune)

Format implements custom formatting for representing a Dense matrix. Thanks to this method, a Dense matrix satisfies the fmt.Formatter interface.

func (*Dense[T]) Grad added in v1.1.0

func (d *Dense[T]) Grad() Tensor

Grad returns the gradients accumulated during the backward pass.

func (*Dense[T]) HasGrad added in v1.1.0

func (d *Dense[T]) HasGrad() bool

HasGrad reports whether there are accumulated gradients.

func (*Dense[T]) Item added in v1.1.0

func (d *Dense[T]) Item() float.Float

Scalar returns the scalar value. It panics if the matrix does not contain exactly one element.

func (*Dense[T]) Log

func (d *Dense[T]) Log() Matrix

Log returns a new matrix applying the natural logarithm function to each element.

func (*Dense[T]) MarshalBinary

func (d *Dense[T]) MarshalBinary() ([]byte, error)

MarshalBinary marshals a Dense matrix into binary form.

func (*Dense[T]) Max

func (d *Dense[T]) Max() Matrix

Max returns the maximum value of the matrix as a scalar Matrix.

func (*Dense[T]) Maximum

func (d *Dense[T]) Maximum(other Matrix) Matrix

Maximum returns a new matrix containing the element-wise maxima.

func (*Dense[T]) Min

func (d *Dense[T]) Min() Matrix

Min returns the minimum value of the matrix as a scalar Matrix.

func (*Dense[T]) Minimum

func (d *Dense[T]) Minimum(other Matrix) Matrix

Minimum returns a new matrix containing the element-wise minima.

func (*Dense[T]) Mul

func (d *Dense[T]) Mul(other Matrix) Matrix

Mul performs the multiplication row by column. If A is an i×j Matrix, and B is j×k, then the resulting Matrix C = AB will be i×k.

func (*Dense[T]) MulT

func (d *Dense[T]) MulT(other Matrix) Matrix

MulT performs the matrix multiplication row by column. ATB = C, where AT is the transpose of A if A is an r x c Matrix, and B is j x k, r = j the resulting Matrix C will be c x k.

func (*Dense[T]) NewConcatV

func (d *Dense[T]) NewConcatV(vs ...Matrix) Matrix

NewConcatV creates a new column vector, of the same type of the receiver, concatenating two or more vectors "vertically" It accepts row or column vectors indifferently, virtually treating all of them as column vectors.

func (*Dense[T]) NewMatrix

func (d *Dense[T]) NewMatrix(opts ...OptionsFunc) Matrix

NewMatrix creates a new matrix, of the same type of the receiver, of size rows×cols, initialized with a copy of raw data.

Rows and columns MUST not be negative, and the length of data MUST be equal to rows*cols, otherwise the method panics.

func (*Dense[T]) NewScalar

func (d *Dense[T]) NewScalar(v float64, opts ...OptionsFunc) Matrix

func (*Dense[T]) NewStack

func (d *Dense[T]) NewStack(vs ...Matrix) Matrix

NewStack creates a new matrix, of the same type of the receiver, stacking two or more vectors of the same size on top of each other; the result is a new matrix where each row contains the data of each input vector. It accepts row or column vectors indifferently, virtually treating all of them as row vectors.

func (*Dense[T]) Norm

func (d *Dense[T]) Norm(pow float64) Matrix

Norm returns the vector's norm. Use pow = 2.0 to compute the Euclidean norm. The result is a scalar Matrix.

func (*Dense[T]) Normalize2

func (d *Dense[T]) Normalize2() Matrix

Normalize2 normalizes an array with the Euclidean norm.

func (*Dense[T]) OnesLike

func (d *Dense[T]) OnesLike() Matrix

OnesLike returns a new matrix with the same dimensions of the receiver, initialized with ones.

func (*Dense[T]) PadColumns

func (d *Dense[T]) PadColumns(n int) Matrix

PadColumns returns a copy of the matrix with n additional tail columns. The additional elements are set to zero.

func (*Dense[T]) PadRows

func (d *Dense[T]) PadRows(n int) Matrix

PadRows returns a copy of the matrix with n additional tail rows. The additional elements are set to zero.

func (*Dense[T]) Pow

func (d *Dense[T]) Pow(power float64) Matrix

Pow returns a new matrix, applying the power function with given exponent to all elements of the matrix.

func (*Dense[T]) Prod

func (d *Dense[T]) Prod(other Matrix) Matrix

Prod performs the element-wise product between the receiver and the other matrix.

func (*Dense[T]) ProdInPlace

func (d *Dense[T]) ProdInPlace(other Matrix) Matrix

ProdInPlace performs the in-place element-wise product with the other matrix.

func (*Dense[T]) ProdMatrixScalarInPlace

func (d *Dense[T]) ProdMatrixScalarInPlace(m Matrix, n float64) Matrix

ProdMatrixScalarInPlace multiplies the given matrix with the value, storing the result in the receiver.

func (*Dense[T]) ProdScalar

func (d *Dense[T]) ProdScalar(n float64) Matrix

ProdScalar returns the multiplication between the matrix and the given value.

func (*Dense[T]) ProdScalarInPlace

func (d *Dense[T]) ProdScalarInPlace(n float64) Matrix

ProdScalarInPlace performs the in-place multiplication between the matrix and the given value.

func (*Dense[T]) Range

func (d *Dense[T]) Range(start, end int) Matrix

Range creates a new vector initialized with data extracted from the matrix raw data, from start (inclusive) to end (exclusive).

func (*Dense[T]) RequiresGrad added in v1.1.0

func (d *Dense[T]) RequiresGrad() bool

RequiresGrad reports whether the Variable requires gradients.

func (*Dense[T]) Reshape

func (d *Dense[T]) Reshape(shape ...int) Matrix

Reshape returns a copy of the matrix. It panics if the dimensions are incompatible.

func (*Dense[T]) ReshapeInPlace

func (d *Dense[T]) ReshapeInPlace(shape ...int) Matrix

ReshapeInPlace changes the dimensions of the matrix in place and returns the matrix itself. It panics if the dimensions are incompatible.

func (*Dense[T]) ResizeVector

func (d *Dense[T]) ResizeVector(newSize int) Matrix

ResizeVector returns a resized copy of the vector.

If the new size is smaller than the input vector, the remaining tail elements are removed. If it's bigger, the additional tail elements are set to zero.

func (*Dense[T]) ScalarAt

func (d *Dense[T]) ScalarAt(indices ...int) float.Float

ScalarAt returns the value at the given indices. It panics if the given indices are out of range.

func (*Dense[T]) SetAt added in v1.1.0

func (d *Dense[T]) SetAt(m Tensor, indices ...int)

SetAt sets the value m at the given indices. It panics if the given indices are out of range.

func (*Dense[T]) SetData

func (d *Dense[T]) SetData(data float.Slice)

SetData sets the content of the matrix, copying the given raw data representation as one-dimensional slice.

func (*Dense[T]) SetRequiresGrad added in v1.1.0

func (d *Dense[T]) SetRequiresGrad(v bool)

SetRequiresGrad sets the requiresGrad flag.

func (*Dense[T]) SetScalar

func (d *Dense[T]) SetScalar(v float.Float, indices ...int)

SetScalar sets the value v at the given indices. It panics if the given indices are out of range.

func (*Dense[_]) Shape added in v1.1.0

func (d *Dense[_]) Shape() []int

Shape returns the size in each dimension.

func (*Dense[T]) Sigmoid

func (d *Dense[T]) Sigmoid() Matrix

Sigmoid returns a new matrix applying the sigmoid function to each element.

func (*Dense[_]) Size

func (d *Dense[_]) Size() int

The Size of the matrix (rows*columns).

func (*Dense[T]) Slice

func (d *Dense[T]) Slice(fromRow, fromCol, toRow, toCol int) Matrix

Slice returns a new matrix obtained by slicing the receiver across the given positions. The parameters "fromRow" and "fromCol" are inclusive, while "toRow" and "toCol" are exclusive.

func (*Dense[T]) Softmax

func (d *Dense[T]) Softmax() Matrix

Softmax applies the softmax function to the vector, returning the result as a new column vector.

func (*Dense[T]) SplitV

func (d *Dense[T]) SplitV(sizes ...int) []Matrix

SplitV splits the vector in N chunks of given sizes, so that N[i] has size sizes[i].

func (*Dense[T]) Sqrt

func (d *Dense[T]) Sqrt() Matrix

Sqrt returns a new matrix applying the square root function to all elements.

func (*Dense[T]) String

func (d *Dense[T]) String() string

String returns a string representation of the matrix.

func (*Dense[T]) Sub

func (d *Dense[T]) Sub(other Matrix) Matrix

Sub returns the subtraction of the other matrix from the receiver.

func (*Dense[T]) SubInPlace

func (d *Dense[T]) SubInPlace(other Matrix) Matrix

SubInPlace performs the in-place subtraction with the other matrix.

func (*Dense[T]) SubScalar

func (d *Dense[T]) SubScalar(n float64) Matrix

SubScalar performs a subtraction between the matrix and the given value.

func (*Dense[T]) SubScalarInPlace

func (d *Dense[T]) SubScalarInPlace(n float64) Matrix

SubScalarInPlace subtracts the scalar from the receiver's values.

func (*Dense[T]) Sum

func (d *Dense[T]) Sum() Matrix

Sum returns the sum of all values of the matrix as a scalar Matrix.

func (*Dense[T]) SwapInPlace

func (d *Dense[T]) SwapInPlace(r1, r2 int) Matrix

SwapInPlace swaps two rows of the matrix in place.

func (*Dense[T]) T

func (d *Dense[T]) T() Matrix

T returns the transpose of the matrix.

func (*Dense[T]) TransposeInPlace

func (d *Dense[T]) TransposeInPlace() Matrix

TransposeInPlace transposes the matrix in place, and returns the matrix itself.

func (*Dense[T]) UnmarshalBinary

func (d *Dense[T]) UnmarshalBinary(data []byte) error

UnmarshalBinary unmarshals a binary representation of a Dense matrix.

func (*Dense[T]) Value added in v1.1.0

func (d *Dense[T]) Value() Tensor

Value returns the value of the Matrix itself.

func (*Dense[T]) ZeroGrad added in v1.1.0

func (d *Dense[T]) ZeroGrad()

ZeroGrad zeroes the gradients, setting the value of Grad to nil.

func (*Dense[T]) Zeros

func (d *Dense[T]) Zeros()

Zeros sets all the values of the matrix to zero.

func (*Dense[T]) ZerosLike

func (d *Dense[T]) ZerosLike() Matrix

ZerosLike returns a new matrix with the same dimensions of the receiver, initialized with zeroes.

type Matrix

type Matrix interface {
	Tensor

	// SetData sets the content of the matrix, copying the given raw
	// data representation as one-dimensional slice.
	SetData(data float.Slice)
	// ZerosLike returns a new matrix with the same dimensions of the
	// receiver, initialized with zeroes.
	ZerosLike() Matrix
	// OnesLike returns a new matrix with the same dimensions of the
	// receiver, initialized with ones.
	OnesLike() Matrix
	// Item returns the scalar value.
	// It panics if the matrix does not contain exactly one element.
	Item() float.Float
	// Zeros sets all the values of the matrix to zero.
	Zeros()
	// SetScalar sets the value at the given indices.
	// It panics if the given indices are out of range.
	SetScalar(v float.Float, indices ...int)
	// ScalarAt returns the value at the given indices.
	// It panics if the given indices are out of range.
	ScalarAt(indices ...int) float.Float
	// ExtractRow returns a copy of the i-th row of the matrix,
	// as a row vector (1×cols).
	ExtractRow(i int) Matrix
	// ExtractColumn returns a copy of the i-th column of the matrix,
	// as a column vector (rows×1).
	ExtractColumn(i int) Matrix
	// Slice returns a new matrix obtained by slicing the receiver across the
	// given positions. The parameters "fromRow" and "fromCol" are inclusive,
	// while "toRow" and "toCol" are exclusive.
	Slice(fromRow, fromCol, toRow, toCol int) Matrix
	// Reshape returns a copy of the matrix.
	// It panics if the dimensions are incompatible.
	Reshape(shape ...int) Matrix
	// ReshapeInPlace changes the dimensions of the matrix in place and returns the
	// matrix itself.
	// It panics if the dimensions are incompatible.
	ReshapeInPlace(shape ...int) Matrix
	// Flatten creates a new row vector (1×size) corresponding to the
	// "flattened" row-major ordered representation of the initial matrix.
	Flatten() Matrix
	// FlattenInPlace transforms the matrix in place, changing its dimensions,
	// obtaining a row vector (1×size) containing the "flattened" row-major
	// ordered representation of the initial value.
	// It returns the matrix itself.
	FlattenInPlace() Matrix
	// ResizeVector returns a resized copy of the vector.
	//
	// If the new size is smaller than the input vector, the remaining tail
	// elements are removed. If it's bigger, the additional tail elements
	// are set to zero.
	ResizeVector(newSize int) Matrix
	// T returns the transpose of the matrix.
	T() Matrix
	// TransposeInPlace transposes the matrix in place, and returns the
	// matrix itself.
	TransposeInPlace() Matrix
	// Add returns the addition between the receiver and another matrix.
	Add(other Matrix) Matrix
	// AddInPlace performs the in-place addition with the other matrix.
	AddInPlace(other Matrix) Matrix
	// AddScalar performs the addition between the matrix and the given value.
	AddScalar(n float64) Matrix
	// AddScalarInPlace adds the scalar to all values of the matrix.
	AddScalarInPlace(n float64) Matrix
	// Sub returns the subtraction of the other matrix from the receiver.
	Sub(other Matrix) Matrix
	// SubInPlace performs the in-place subtraction with the other matrix.
	SubInPlace(other Matrix) Matrix
	// SubScalar performs a subtraction between the matrix and the given value.
	SubScalar(n float64) Matrix
	// SubScalarInPlace subtracts the scalar from the receiver's values.
	SubScalarInPlace(n float64) Matrix
	// Prod performs the element-wise product between the receiver and the other matrix.
	Prod(other Matrix) Matrix
	// ProdInPlace performs the in-place element-wise product with the other matrix.
	ProdInPlace(other Matrix) Matrix
	// ProdScalar returns the multiplication between the matrix and the given value.
	ProdScalar(n float64) Matrix
	// ProdScalarInPlace performs the in-place multiplication between the
	// matrix and the given value.
	ProdScalarInPlace(n float64) Matrix
	// ProdMatrixScalarInPlace multiplies the given matrix with the value,
	// storing the result in the receiver.
	ProdMatrixScalarInPlace(m Matrix, n float64) Matrix
	// Div returns the result of the element-wise division of the receiver by the other matrix.
	Div(other Matrix) Matrix
	// DivInPlace performs the in-place element-wise division of the receiver by the other matrix.
	DivInPlace(other Matrix) Matrix
	// Mul performs the multiplication row by column.
	// If A is an i×j Matrix, and B is j×k, then the resulting Matrix
	// C = AB will be i×k.
	Mul(other Matrix) Matrix
	// MulT performs the matrix multiplication row by column.
	// ATB = C, where AT is the transpose of A
	// if A is an r x c Matrix, and B is j x k, r = j the resulting
	// Matrix C will be c x k.
	MulT(other Matrix) Matrix
	// DotUnitary returns the dot product of two vectors as a scalar Matrix.
	DotUnitary(other Matrix) Matrix
	// ClipInPlace clips in place each value of the matrix.
	ClipInPlace(min, max float64) Matrix
	// Maximum returns a new matrix containing the element-wise maxima.
	Maximum(other Matrix) Matrix
	// Minimum returns a new matrix containing the element-wise minima.
	Minimum(other Matrix) Matrix
	// Abs returns a new matrix applying the absolute value function to all elements.
	Abs() Matrix
	// Pow returns a new matrix, applying the power function with given exponent
	// to all elements of the matrix.
	Pow(power float64) Matrix
	// Sqrt returns a new matrix applying the square root function to all elements.
	Sqrt() Matrix
	// Log returns a new matrix applying the natural logarithm function to each element.
	Log() Matrix
	// Exp returns a new matrix applying the base-e exponential function to each element.
	Exp() Matrix
	// Sigmoid returns a new matrix applying the sigmoid function to each element.
	Sigmoid() Matrix
	// Sum returns the sum of all values of the matrix as a scalar Matrix.
	Sum() Matrix
	// Max returns the maximum value of the matrix as a scalar Matrix.
	Max() Matrix
	// Min returns the minimum value of the matrix as a scalar Matrix.
	Min() Matrix
	// ArgMax returns the index of the vector's element with the maximum value.
	ArgMax() int
	// Softmax applies the softmax function to the vector, returning the
	// result as a new column vector.
	Softmax() Matrix
	// CumSum computes the cumulative sum of the vector's elements, returning
	// the result as a new column vector.
	CumSum() Matrix
	// Range creates a new vector initialized with data extracted from the
	// matrix raw data, from start (inclusive) to end (exclusive).
	Range(start, end int) Matrix
	// SplitV splits the vector in N chunks of given sizes,
	// so that N[i] has size sizes[i].
	SplitV(sizes ...int) []Matrix
	// Augment places the identity matrix at the end of the original matrix.
	Augment() Matrix
	// SwapInPlace swaps two rows of the matrix in place.
	SwapInPlace(r1, r2 int) Matrix
	// PadRows returns a copy of the matrix with n additional tail rows.
	// The additional elements are set to zero.
	PadRows(n int) Matrix
	// PadColumns returns a copy of the matrix with n additional tail columns.
	// The additional elements are set to zero.
	PadColumns(n int) Matrix
	// AppendRows returns a copy of the matrix with len(vs) additional tail rows,
	// being each new row filled with the values of each given vector.
	// It accepts row or column vectors indifferently, virtually treating all of
	// them as row vectors.
	AppendRows(vs ...Matrix) Matrix
	// Norm returns the vector's norm. Use pow = 2.0 to compute the Euclidean norm.
	// The result is a scalar Matrix.
	Norm(pow float64) Matrix
	// Normalize2 normalizes an array with the Euclidean norm.
	Normalize2() Matrix
	// Apply creates a new matrix executing the unary function fn.
	Apply(fn func(r, c int, v float64) float64) Matrix
	// ApplyInPlace executes the unary function fn over the matrix a,
	// and stores the result in the receiver, returning the receiver itself.
	ApplyInPlace(fn func(r, c int, v float64) float64, a Matrix) Matrix
	// ApplyWithAlpha creates a new matrix executing the unary function fn,
	// taking additional parameters alpha.
	ApplyWithAlpha(fn func(r, c int, v float64, alpha ...float64) float64, alpha ...float64) Matrix
	// ApplyWithAlphaInPlace executes the unary function fn over the matrix a,
	// taking additional parameters alpha, and stores the result in the
	// receiver, returning the receiver itself.
	ApplyWithAlphaInPlace(fn func(r, c int, v float64, alpha ...float64) float64, a Matrix, alpha ...float64) Matrix
	// DoNonZero calls a function for each non-zero element of the matrix.
	// The parameters of the function are the element's indices and value.
	DoNonZero(fn func(r, c int, v float64))
	// DoVecNonZero calls a function for each non-zero element of the vector.
	// The parameters of the function are the element's index and value.
	DoVecNonZero(fn func(i int, v float64))
	// Clone returns a new matrix, copying all its values from the receiver.
	Clone() Matrix
	// Copy copies the data from the other matrix to the receiver.
	Copy(other Matrix)
	// String returns a string representation of the matrix.
	String() string

	// NewMatrix creates a new matrix, of the same type of the receiver, of
	// size rows×cols, initialized with a copy of raw data.
	//
	// Rows and columns MUST not be negative, and the length of data MUST be
	// equal to rows*cols, otherwise the method panics.
	NewMatrix(opts ...OptionsFunc) Matrix
	// NewScalar creates a new 1×1 matrix, of the same type of the receiver,
	// containing the given value.
	NewScalar(v float64, opts ...OptionsFunc) Matrix

	// NewConcatV creates a new column vector, of the same type of the receiver,
	// concatenating two or more vectors "vertically"
	// It accepts row or column vectors indifferently, virtually
	// treating all of them as column vectors.
	NewConcatV(vs ...Matrix) Matrix
	// NewStack creates a new matrix, of the same type of the receiver, stacking
	// two or more vectors of the same size on top of each other; the result is
	// a new matrix where each row contains the data of each input vector.
	// It accepts row or column vectors indifferently, virtually treating all of
	// them as row vectors.
	NewStack(vs ...Matrix) Matrix

	SetRequiresGrad(bool)
}

The Matrix interface defines set and get methods to access its elements, plus a few variants to perform linear algebra operations with other matrices, such as element-wise addition, subtraction, product and matrix-matrix multiplication.

type Options added in v1.1.0

type Options struct {
	RequiresGrad bool // default: false
	Shape        []int
	Slice        float.Slice
}

type OptionsFunc added in v1.1.0

type OptionsFunc func(opt *Options)

func WithBacking added in v1.1.0

func WithBacking[T float.DType](data []T) OptionsFunc

func WithGrad added in v1.1.0

func WithGrad(value bool) OptionsFunc

func WithShape added in v1.1.0

func WithShape(shape ...int) OptionsFunc

type T added in v1.1.0

type T interface {
	Helper()
	Error(args ...any)
	Errorf(format string, args ...any)
	FailNow()
}

T requires a subset of methods from testing.TB. This interface is primarily useful to simplify the testing of the package itself.

type Tensor added in v1.1.0

type Tensor interface {
	// Shape returns the size in each dimension.
	Shape() []int
	// Dims returns the number of dimensions.
	Dims() int
	// Size returns the total number of elements.
	Size() int
	// Data returns the underlying data of the tensor.
	Data() float.Slice
	// Item returns the scalar value.
	// It panics if the matrix does not contain exactly one element.
	Item() float.Float
	// SetAt sets the value at the given indices.
	// It panics if the given indices are out of range.
	SetAt(m Tensor, indices ...int)
	// At returns the value at the given indices.
	// It panics if the given indices are out of range.
	At(indices ...int) Tensor
	// Value returns the value of the node.
	// In case of a leaf node, it returns the value of the underlying matrix.
	// In case of a non-leaf node, it returns the value of the operation performed during the forward pass.
	Value() Tensor
	// Grad returns the gradients accumulated during the backward pass.
	// A matrix full of zeros and the nil value are considered equivalent.
	Grad() Tensor
	// HasGrad reports whether there are accumulated gradients.
	HasGrad() bool
	// RequiresGrad reports whether the node requires gradients.
	RequiresGrad() bool
	// AccGrad accumulates the gradients into the node.
	AccGrad(gx Tensor)
	// ZeroGrad zeroes the gradients, setting the value of Grad to nil.
	ZeroGrad()
}

Tensor represents an interface for a generic tensor.

Directories

Path Synopsis
fbs
internal
f32
f32/asm32
Package asm32 provides float32 vector primitives.
Package asm32 provides float32 vector primitives.
f64
f64/asm64
Package asm64 provides float64 vector primitives.
Package asm64 provides float64 vector primitives.
matfuncs/cpu
Package cpu implements processor feature detection for various CPU architectures.
Package cpu implements processor feature detection for various CPU architectures.
rand
Package rand implements pseudo-random number generators.
Package rand implements pseudo-random number generators.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL