core

package
v0.0.0-...-06c276a Latest Latest
Warning

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

Go to latest
Published: Dec 5, 2025 License: MIT Imports: 12 Imported by: 0

Documentation

Overview

Package core defines the fundamental interfaces and types for the ThinkingNet AI library.

Index

Constants

This section is empty.

Variables

View Source
var CommonErrorMessages = map[ErrorType]map[string]BilingualMessage{
	ErrInvalidInput: {
		"nil_tensor": {
			Arabic:  "المصفوفة لا يمكن أن تكون فارغة",
			English: "tensor cannot be nil",
			Tip:     "تأكد من إنشاء المصفوفة بشكل صحيح | Make sure to create the tensor properly",
		},
		"zero_dimensions": {
			Arabic:  "المصفوفة لا يمكن أن تحتوي على أبعاد صفرية",
			English: "tensor cannot have zero dimensions",
			Tip:     "تحقق من أن البيانات تحتوي على قيم | Check that data contains values",
		},
		"empty_data": {
			Arabic:  "البيانات لا يمكن أن تكون فارغة",
			English: "data cannot be empty",
			Tip:     "تأكد من وجود بيانات للمعالجة | Ensure there is data to process",
		},
		"invalid_range": {
			Arabic:  "القيمة خارج النطاق المسموح",
			English: "value is out of allowed range",
			Tip:     "تحقق من القيم المدخلة | Check input values",
		},
	},
	ErrDimensionMismatch: {
		"incompatible_shapes": {
			Arabic:  "أشكال المصفوفات غير متوافقة",
			English: "tensor shapes are incompatible",
			Tip:     "تأكد من أن أبعاد المصفوفات متوافقة للعملية | Ensure tensor dimensions are compatible for the operation",
		},
		"matrix_multiplication": {
			Arabic:  "أبعاد غير متوافقة لضرب المصفوفات",
			English: "incompatible dimensions for matrix multiplication",
			Tip:     "عدد الأعمدة في المصفوفة الأولى يجب أن يساوي عدد الصفوف في الثانية | Number of columns in first matrix must equal rows in second",
		},
		"training_data_mismatch": {
			Arabic:  "عدد العينات في X و y غير متطابق",
			English: "number of samples in X and y don't match",
			Tip:     "تأكد من أن X و y لهما نفس عدد الصفوف | Ensure X and y have the same number of rows",
		},
	},
	ErrNotFitted: {
		"component_not_fitted": {
			Arabic:  "المكون لم يتم تدريبه بعد",
			English: "component has not been fitted yet",
			Tip:     "استخدم fit() أو train() أولاً | Use fit() or train() first",
		},
	},
	ErrModelNotCompiled: {
		"model_not_compiled": {
			Arabic:  "النموذج لم يتم تجميعه بعد",
			English: "model has not been compiled yet",
			Tip:     "استخدم Compile() مع optimizer و loss function | Use Compile() with optimizer and loss function",
		},
	},
	ErrNumericalInstability: {
		"nan_values": {
			Arabic:  "المصفوفة تحتوي على قيم NaN أو لا نهائية",
			English: "tensor contains NaN or infinite values",
			Tip:     "تحقق من البيانات المدخلة والمعاملات | Check input data and parameters",
		},
		"convergence_failed": {
			Arabic:  "فشل في التقارب",
			English: "convergence failed",
			Tip:     "جرب تقليل معدل التعلم أو زيادة عدد التكرارات | Try reducing learning rate or increasing iterations",
		},
	},
}

Common bilingual error messages

Functions

func Cleanup

func Cleanup()

Cleanup shuts down the global worker pool.

func ClearMatrixPool

func ClearMatrixPool()

ClearMatrixPool clears the global matrix pool.

func ConfigExists

func ConfigExists(filename string) bool

ConfigExists checks if a configuration file exists.

func GetEpsilon

func GetEpsilon() float64

GetEpsilon returns the current epsilon value.

func GetGlobalSeed

func GetGlobalSeed() int64

GetGlobalSeed returns the global random seed.

func GetMatrix

func GetMatrix(rows, cols int) *mat.Dense

GetMatrix retrieves a matrix from the global pool.

func GetMaxFloat

func GetMaxFloat() float64

GetMaxFloat returns the maximum float value.

func GetMinFloat

func GetMinFloat() float64

GetMinFloat returns the minimum float value.

func IsDebugMode

func IsDebugMode() bool

IsDebugMode returns true if debug mode is enabled.

func IsMatrixPoolEnabled

func IsMatrixPoolEnabled() bool

IsMatrixPoolEnabled returns whether the global matrix pool is enabled.

func IsParallelEnabled

func IsParallelEnabled() bool

IsParallelEnabled returns true if parallel processing is enabled.

func IsPoolingEnabled

func IsPoolingEnabled() bool

IsPoolingEnabled returns true if memory pooling is enabled.

func IsThinkingNetError

func IsThinkingNetError(err error) bool

IsThinkingNetError checks if an error is a ThinkingNetError.

func LoadConfig

func LoadConfig(filename string) error

LoadConfig loads configuration from a JSON file.

func MatrixPoolStats

func MatrixPoolStats() map[string]PoolStats

MatrixPoolStats returns statistics about the global matrix pool.

func ParallelExecute

func ParallelExecute(operations []func() error) error

ParallelExecute executes operations in parallel if conditions are met.

func ParallelTensorOperation

func ParallelTensorOperation(tensor Tensor, operation func(startRow, endRow int) error) error

ParallelTensorOperation applies an operation to tensor chunks in parallel.

func PrintConfig

func PrintConfig()

PrintConfig prints the current configuration to stdout.

func PutMatrix

func PutMatrix(matrix *mat.Dense)

PutMatrix returns a matrix to the global pool.

func RecoverFromPanic

func RecoverFromPanic(operation string) error

RecoverFromPanic recovers from panics and converts them to ThinkingNet errors. This function should be called from within a defer function.

func RunQuickBenchmark

func RunQuickBenchmark()

RunQuickBenchmark runs a quick performance benchmark.

func RunUltraFastBenchmark

func RunUltraFastBenchmark()

RunUltraFastBenchmark runs maximum speed benchmarks only.

func SafeExecute

func SafeExecute(operation string, fn func() error) (err error)

SafeExecute executes a function with panic recovery.

func SaveConfig

func SaveConfig(filename string) error

SaveConfig saves the current configuration to a JSON file.

func SetConfig

func SetConfig(config *Config)

SetConfig sets the global configuration.

func SetMatrixPoolEnabled

func SetMatrixPoolEnabled(enabled bool)

SetMatrixPoolEnabled enables or disables the global matrix pool.

func SetOptimizationConfig

func SetOptimizationConfig(config OptimizationConfig)

SetOptimizationConfig sets the global optimization configuration.

func SetParallelConfig

func SetParallelConfig(config ParallelConfig)

SetParallelConfig sets the global parallel configuration.

func UpdateConfig

func UpdateConfig(updates map[string]any) error

UpdateConfig updates specific fields in the global configuration.

func ValidateCompatibleShapes

func ValidateCompatibleShapes(a, b Tensor, operation string) error

ValidateCompatibleShapes validates that two tensors have compatible shapes for broadcasting.

func ValidateCompiled

func ValidateCompiled(compiled bool) error

ValidateCompiled checks if a model has been compiled.

func ValidateDimensions

func ValidateDimensions(a, b Tensor, operation string) error

ValidateDimensions validates that two tensors have compatible dimensions for an operation.

func ValidateInput

func ValidateInput(X Tensor, expectedShape []int) error

ValidateInput validates input tensor dimensions and properties.

func ValidateIntRange

func ValidateIntRange(value, min, max int, name string) error

ValidateIntRange validates that an integer value is within a specified range.

func ValidateMemoryUsage

func ValidateMemoryUsage(tensors []Tensor, operation string) error

ValidateMemoryUsage validates that tensor operations won't exceed memory limits.

func ValidateModelState

func ValidateModelState(compiled, fitted bool, operation string) error

ValidateModelState validates the state of a model before operations.

func ValidateNonEmpty

func ValidateNonEmpty(tensor Tensor, name string) error

ValidateNonEmpty validates that a tensor is not empty.

func ValidateNonNegative

func ValidateNonNegative(value float64, name string) error

ValidateNonNegative validates that a value is non-negative.

func ValidateNonNegativeInt

func ValidateNonNegativeInt(value int, name string) error

ValidateNonNegativeInt validates that an integer value is non-negative.

func ValidateNotFitted

func ValidateNotFitted(fitted bool, componentName string) error

ValidateNotFitted checks if a component has been fitted.

func ValidateOptimizationConfig

func ValidateOptimizationConfig(config map[string]interface{}) error

ValidateOptimizationConfig validates optimizer configuration parameters.

func ValidatePositive

func ValidatePositive(value float64, name string) error

ValidatePositive validates that a value is positive.

func ValidatePositiveInt

func ValidatePositiveInt(value int, name string) error

ValidatePositiveInt validates that an integer value is positive.

func ValidateRange

func ValidateRange(value float64, min, max float64, name string) error

ValidateRange validates that a value is within a specified range.

func ValidateScalar

func ValidateScalar(value float64, name string) error

ValidateScalar validates that a scalar value is finite and within bounds.

func ValidateSliceNotEmpty

func ValidateSliceNotEmpty(slice interface{}, name string) error

ValidateSliceNotEmpty validates that a slice is not empty.

func ValidateSquareMatrix

func ValidateSquareMatrix(tensor Tensor, name string) error

ValidateSquareMatrix validates that a tensor is a square matrix.

func ValidateStringInSet

func ValidateStringInSet(value string, allowedValues []string, name string) error

ValidateStringInSet validates that a string value is in a set of allowed values.

func ValidateTensorFinite

func ValidateTensorFinite(tensor Tensor, name string) error

ValidateTensorFinite validates that a tensor contains only finite values.

func ValidateTrainingData

func ValidateTrainingData(X, y Tensor) error

ValidateTrainingData validates training data consistency.

func ValidateVector

func ValidateVector(tensor Tensor, name string) error

ValidateVector validates that a tensor is a vector.

Types

type Activation

type Activation interface {
	// Forward applies the activation function
	Forward(x float64) float64

	// Backward computes the derivative
	Backward(x float64) float64

	// Name returns the activation function name
	Name() string
}

Activation represents an activation function.

type BaseCallback

type BaseCallback struct{}

BaseCallback provides default implementations for Callback interface.

func (*BaseCallback) OnBatchBegin

func (cb *BaseCallback) OnBatchBegin(batch int)

func (*BaseCallback) OnBatchEnd

func (cb *BaseCallback) OnBatchEnd(batch int, loss float64)

func (*BaseCallback) OnEpochBegin

func (cb *BaseCallback) OnEpochBegin(epoch int)

func (*BaseCallback) OnEpochEnd

func (cb *BaseCallback) OnEpochEnd(epoch, maxEpochs int, loss float64, metrics map[string]float64)

func (*BaseCallback) OnTrainBegin

func (cb *BaseCallback) OnTrainBegin()

func (*BaseCallback) OnTrainEnd

func (cb *BaseCallback) OnTrainEnd()

type BatchProcessor

type BatchProcessor struct {
	// contains filtered or unexported fields
}

BatchProcessor provides efficient batch processing capabilities.

func GetBatchProcessor

func GetBatchProcessor() *BatchProcessor

GetBatchProcessor returns the global batch processor.

func NewBatchProcessor

func NewBatchProcessor() *BatchProcessor

NewBatchProcessor creates a new batch processor.

func (*BatchProcessor) ProcessBatches

func (bp *BatchProcessor) ProcessBatches(inputs []Tensor, processor func(Tensor) Tensor) []Tensor

ProcessBatches processes multiple tensors in parallel.

type BenchmarkResult

type BenchmarkResult struct {
	Name            string
	Duration        time.Duration
	OperationsCount int64
	OpsPerSecond    float64
	MemoryUsed      int64
	Allocations     int64
	Speedup         float64 // Compared to baseline
}

BenchmarkResult holds the results of a performance benchmark.

type BenchmarkSuite

type BenchmarkSuite struct {
	// contains filtered or unexported fields
}

BenchmarkSuite provides comprehensive performance benchmarking for ThinkingNet operations.

func GetBenchmarkSuite

func GetBenchmarkSuite() *BenchmarkSuite

GetBenchmarkSuite returns the global benchmark suite.

func NewBenchmarkSuite

func NewBenchmarkSuite() *BenchmarkSuite

NewBenchmarkSuite creates a new benchmark suite.

func (*BenchmarkSuite) BenchmarkActivationFunctions

func (bs *BenchmarkSuite) BenchmarkActivationFunctions(size int, iterations int) map[string]*BenchmarkResult

BenchmarkActivationFunctions benchmarks activation function performance.

func (*BenchmarkSuite) BenchmarkBatchProcessing

func (bs *BenchmarkSuite) BenchmarkBatchProcessing(batchSize int, tensorSize int) *BenchmarkResult

BenchmarkBatchProcessing benchmarks batch processing performance.

func (*BenchmarkSuite) BenchmarkHighPerformanceOperations

func (bs *BenchmarkSuite) BenchmarkHighPerformanceOperations(numOperations int64) *BenchmarkResult

BenchmarkHighPerformanceOperations benchmarks the high-performance processor.

func (*BenchmarkSuite) BenchmarkMatrixOperations

func (bs *BenchmarkSuite) BenchmarkMatrixOperations(size int, iterations int) *BenchmarkResult

BenchmarkMatrixOperations benchmarks matrix multiplication performance.

func (*BenchmarkSuite) BenchmarkMemoryPooling

func (bs *BenchmarkSuite) BenchmarkMemoryPooling(numMatrices int, matrixSize int) *BenchmarkResult

BenchmarkMemoryPooling benchmarks memory pool performance.

func (*BenchmarkSuite) BenchmarkUltraFastActivations

func (bs *BenchmarkSuite) BenchmarkUltraFastActivations(size int, iterations int) map[string]*BenchmarkResult

BenchmarkUltraFastActivations benchmarks ultra-fast activation functions.

func (*BenchmarkSuite) BenchmarkUltraFastOperations

func (bs *BenchmarkSuite) BenchmarkUltraFastOperations(numOperations int64) *BenchmarkResult

BenchmarkUltraFastOperations benchmarks the ultra-fast processor (maximum speed).

func (*BenchmarkSuite) CompareWithBaseline

func (bs *BenchmarkSuite) CompareWithBaseline(baseline map[string]*BenchmarkResult)

CompareWithBaseline compares current results with baseline performance.

func (*BenchmarkSuite) GetResults

func (bs *BenchmarkSuite) GetResults() map[string]*BenchmarkResult

GetResults returns all benchmark results.

func (*BenchmarkSuite) PrintResults

func (bs *BenchmarkSuite) PrintResults()

PrintResults prints benchmark results in a formatted table.

func (*BenchmarkSuite) RunComprehensiveBenchmark

func (bs *BenchmarkSuite) RunComprehensiveBenchmark() map[string]*BenchmarkResult

RunComprehensiveBenchmark runs all benchmarks and returns a summary.

type BilingualMessage

type BilingualMessage struct {
	Arabic  string `json:"arabic"`
	English string `json:"english"`
	Tip     string `json:"tip,omitempty"` // Helpful tip for resolving the error
}

BilingualMessage represents an error message in both Arabic and English.

type CacheOptimizer

type CacheOptimizer struct {
	// contains filtered or unexported fields
}

CacheOptimizer provides cache-aware optimizations.

func GetCacheOptimizer

func GetCacheOptimizer() *CacheOptimizer

GetCacheOptimizer returns the global cache optimizer instance.

func NewCacheOptimizer

func NewCacheOptimizer() *CacheOptimizer

NewCacheOptimizer creates a new cache optimizer.

func (*CacheOptimizer) OptimalBlockSize

func (co *CacheOptimizer) OptimalBlockSize(elementSize int) int

OptimalBlockSize calculates optimal block size for cache efficiency.

func (*CacheOptimizer) PrefetchHint

func (co *CacheOptimizer) PrefetchHint(data []float64, index int, distance int)

PrefetchHint provides prefetch hints for better memory access patterns.

type Callback

type Callback interface {
	OnTrainBegin()
	OnTrainEnd()
	OnEpochBegin(epoch int)
	OnEpochEnd(epoch, maxEpochs int, loss float64, metrics map[string]float64)
	OnBatchBegin(batch int)
	OnBatchEnd(batch int, loss float64)
}

Callback interface for training callbacks.

type Classifier

type Classifier interface {
	// Fit trains the classifier
	Fit(X, y Tensor) error

	// Predict makes class predictions
	Predict(X Tensor) (Tensor, error)

	// PredictProba predicts class probabilities
	PredictProba(X Tensor) (Tensor, error)

	// Score returns the accuracy score
	Score(X, y Tensor) (float64, error)

	// Name returns the classifier name
	Name() string
}

Classifier represents a classification algorithm.

type Clusterer

type Clusterer interface {
	// Fit learns cluster parameters from data
	Fit(X Tensor) error

	// Predict assigns cluster labels to data
	Predict(X Tensor) ([]int, error)

	// FitPredict fits and predicts in one step
	FitPredict(X Tensor) ([]int, error)

	// ClusterCenters returns the cluster centers
	ClusterCenters() Tensor

	// Name returns the clusterer name
	Name() string
}

Clusterer represents a clustering algorithm.

type Config

type Config struct {
	// Numerical precision settings
	Epsilon  float64 `json:"epsilon"`
	MaxFloat float64 `json:"max_float"`
	MinFloat float64 `json:"min_float"`

	// Memory management
	EnablePooling bool `json:"enable_pooling"`
	PoolSize      int  `json:"pool_size"`

	// Parallel processing
	MaxWorkers     int  `json:"max_workers"`
	EnableParallel bool `json:"enable_parallel"`

	// Debugging and logging
	DebugMode bool   `json:"debug_mode"`
	LogLevel  string `json:"log_level"`

	// Random seed for reproducibility
	GlobalSeed int64 `json:"global_seed"`

	// Performance settings
	UseBLAS        bool `json:"use_blas"`
	OptimizeMemory bool `json:"optimize_memory"`
}

Config represents the global library configuration.

func DefaultConfig

func DefaultConfig() *Config

DefaultConfig returns the default configuration.

func GetConfig

func GetConfig() *Config

GetConfig returns the current global configuration.

func NewConfig

func NewConfig(options ...ConfigOption) *Config

NewConfig creates a new configuration with options.

type ConfigOption

type ConfigOption func(*Config)

ConfigOption represents a functional option for configuration.

func WithDebug

func WithDebug(enabled bool) ConfigOption

WithDebug enables or disables debug mode.

func WithEpsilon

func WithEpsilon(epsilon float64) ConfigOption

WithEpsilon sets the numerical epsilon.

func WithGlobalSeed

func WithGlobalSeed(seed int64) ConfigOption

WithGlobalSeed sets the global random seed.

func WithLogLevel

func WithLogLevel(level string) ConfigOption

WithLogLevel sets the log level.

func WithParallel

func WithParallel(enabled bool) ConfigOption

WithParallel enables or disables parallel processing.

func WithPooling

func WithPooling(enabled bool) ConfigOption

WithPooling enables or disables memory pooling.

type DataSplit

type DataSplit struct {
	XTrain Tensor
	XVal   Tensor
	XTest  Tensor
	YTrain Tensor
	YVal   Tensor
	YTest  Tensor
}

DataSplit represents a train/validation/test split.

type Dataset

type Dataset struct {
	X            Tensor
	Y            Tensor
	FeatureNames []string
	TargetNames  []string
	Description  string
}

Dataset represents a machine learning dataset.

type DenseTensor

type DenseTensor struct {
	// contains filtered or unexported fields
}

DenseTensor implements the Tensor interface using gonum's Dense matrix.

func NewOnesTensor

func NewOnesTensor(rows, cols int) *DenseTensor

NewOnesTensor creates a tensor filled with ones.

func NewTensor

func NewTensor(data *mat.Dense) *DenseTensor

NewTensor creates a new tensor from a gonum Dense matrix.

func NewTensorFromData

func NewTensorFromData(rows, cols int, data []float64) *DenseTensor

NewTensorFromData creates a new tensor with given dimensions and data.

func NewTensorFromSlice

func NewTensorFromSlice(data [][]float64) *DenseTensor

NewTensorFromSlice creates a new tensor from a 2D slice.

func NewZerosTensor

func NewZerosTensor(rows, cols int) *DenseTensor

NewZerosTensor creates a tensor filled with zeros. Returns an empty tensor if rows or cols is 0.

func (*DenseTensor) Abs

func (t *DenseTensor) Abs() Tensor

Abs computes the absolute value of each element.

func (*DenseTensor) Add

func (t *DenseTensor) Add(other Tensor) Tensor

Add performs element-wise addition.

func (*DenseTensor) AddScalar

func (t *DenseTensor) AddScalar(scalar float64) Tensor

AddScalar adds a scalar value to all elements.

func (*DenseTensor) Apply

func (t *DenseTensor) Apply(fn func(i, j int, v float64) float64) Tensor

Apply applies a function element-wise to the tensor.

func (*DenseTensor) At

func (t *DenseTensor) At(i, j int) float64

At returns the value at position (i, j).

func (*DenseTensor) Clamp

func (t *DenseTensor) Clamp(min, max float64) Tensor

Clamp constrains all elements to be within [min, max].

func (*DenseTensor) Col

func (t *DenseTensor) Col(j int) Tensor

Col returns a specific column as a new tensor.

func (*DenseTensor) Copy

func (t *DenseTensor) Copy() Tensor

Copy creates a deep copy of the tensor.

func (*DenseTensor) Diagonal

func (t *DenseTensor) Diagonal() Tensor

Diagonal returns the diagonal elements as a vector.

func (*DenseTensor) Dims

func (t *DenseTensor) Dims() (int, int)

Dims returns the dimensions of the tensor.

func (*DenseTensor) Div

func (t *DenseTensor) Div(other Tensor) Tensor

Div performs element-wise division.

func (*DenseTensor) DivScalar

func (t *DenseTensor) DivScalar(scalar float64) Tensor

DivScalar divides all elements by a scalar value.

func (*DenseTensor) Dot

func (t *DenseTensor) Dot(other Tensor) float64

Dot performs dot product for vectors or matrix multiplication for matrices.

func (*DenseTensor) Equal

func (t *DenseTensor) Equal(other Tensor) bool

Equal checks if two tensors are element-wise equal within epsilon tolerance.

func (*DenseTensor) Exp

func (t *DenseTensor) Exp() Tensor

Exp computes the exponential of each element with overflow protection.

func (*DenseTensor) Fill

func (t *DenseTensor) Fill(value float64)

Fill sets all elements to the specified value.

func (*DenseTensor) Flatten

func (t *DenseTensor) Flatten() Tensor

Flatten returns a new tensor with shape (1, rows*cols).

func (*DenseTensor) HasInf

func (t *DenseTensor) HasInf() bool

HasInf checks if the tensor contains any infinite values.

func (*DenseTensor) HasNaN

func (t *DenseTensor) HasNaN() bool

HasNaN checks if the tensor contains any NaN values.

func (*DenseTensor) IsEmpty

func (t *DenseTensor) IsEmpty() bool

IsEmpty returns true if the tensor has zero elements.

func (*DenseTensor) IsFinite

func (t *DenseTensor) IsFinite() bool

IsFinite checks if all values in the tensor are finite.

func (*DenseTensor) IsSquare

func (t *DenseTensor) IsSquare() bool

IsSquare returns true if the tensor is square.

func (*DenseTensor) IsVector

func (t *DenseTensor) IsVector() bool

IsVector returns true if the tensor is a vector (single row or column).

func (*DenseTensor) Log

func (t *DenseTensor) Log() Tensor

Log computes the natural logarithm of each element with numerical stability.

func (*DenseTensor) Max

func (t *DenseTensor) Max() float64

Max returns the maximum element.

func (*DenseTensor) Mean

func (t *DenseTensor) Mean() float64

Mean computes the mean of all elements.

func (*DenseTensor) Min

func (t *DenseTensor) Min() float64

Min returns the minimum element.

func (*DenseTensor) Mul

func (t *DenseTensor) Mul(other Tensor) Tensor

Mul performs matrix multiplication.

func (*DenseTensor) MulElem

func (t *DenseTensor) MulElem(other Tensor) Tensor

MulElem performs element-wise multiplication.

func (*DenseTensor) Name

func (t *DenseTensor) Name() string

Name returns the tensor name.

func (*DenseTensor) Norm

func (t *DenseTensor) Norm() float64

Norm returns the Frobenius norm of the tensor.

func (*DenseTensor) Pow

func (t *DenseTensor) Pow(power float64) Tensor

Pow raises each element to the given power.

func (*DenseTensor) RawMatrix

func (t *DenseTensor) RawMatrix() *mat.Dense

RawMatrix returns the underlying gonum matrix.

func (*DenseTensor) Release

func (t *DenseTensor) Release()

Release returns the tensor's matrix to the pool for reuse.

func (*DenseTensor) Reshape

func (t *DenseTensor) Reshape(newRows, newCols int) Tensor

Reshape returns a new tensor with the specified dimensions.

func (*DenseTensor) Row

func (t *DenseTensor) Row(i int) Tensor

Row returns a specific row as a new tensor.

func (*DenseTensor) SafeOperation

func (t *DenseTensor) SafeOperation(operation string, fn func() Tensor) (Tensor, error)

SafeOperation performs an operation with error recovery.

func (*DenseTensor) Scale

func (t *DenseTensor) Scale(scalar float64) Tensor

Scale multiplies all elements by a scalar.

func (*DenseTensor) Set

func (t *DenseTensor) Set(i, j int, v float64)

Set sets the value at position (i, j).

func (*DenseTensor) SetCol

func (t *DenseTensor) SetCol(j int, data []float64)

SetCol sets a specific column.

func (*DenseTensor) SetName

func (t *DenseTensor) SetName(name string)

SetName sets the tensor name.

func (*DenseTensor) SetRow

func (t *DenseTensor) SetRow(i int, data []float64)

SetRow sets a specific row.

func (*DenseTensor) Shape

func (t *DenseTensor) Shape() []int

Shape returns the shape as a slice.

func (*DenseTensor) Sign

func (t *DenseTensor) Sign() Tensor

Sign returns the sign of each element (-1, 0, or 1).

func (*DenseTensor) Slice

func (t *DenseTensor) Slice(r0, r1, c0, c1 int) Tensor

Slice returns a slice of the tensor.

func (*DenseTensor) Sqrt

func (t *DenseTensor) Sqrt() Tensor

Sqrt computes the square root of each element.

func (*DenseTensor) Std

func (t *DenseTensor) Std() float64

Std computes the standard deviation of all elements.

func (*DenseTensor) String

func (t *DenseTensor) String() string

String returns a string representation of the tensor.

func (*DenseTensor) Sub

func (t *DenseTensor) Sub(other Tensor) Tensor

Sub performs element-wise subtraction.

func (*DenseTensor) SubScalar

func (t *DenseTensor) SubScalar(scalar float64) Tensor

SubScalar subtracts a scalar value from all elements.

func (*DenseTensor) Sum

func (t *DenseTensor) Sum() float64

Sum returns the sum of all elements.

func (*DenseTensor) T

func (t *DenseTensor) T() Tensor

T returns the transpose.

func (*DenseTensor) Trace

func (t *DenseTensor) Trace() float64

Trace computes the trace (sum of diagonal elements) for square matrices.

func (*DenseTensor) Validate

func (t *DenseTensor) Validate() error

Validate performs comprehensive validation of the tensor.

func (*DenseTensor) Zero

func (t *DenseTensor) Zero()

Zero sets all elements to zero.

type EarlyStoppingConfig

type EarlyStoppingConfig struct {
	Enabled  bool    `json:"enabled"`
	Monitor  string  `json:"monitor"` // "loss", "val_loss", "accuracy", etc.
	Patience int     `json:"patience"`
	MinDelta float64 `json:"min_delta"`
	Mode     string  `json:"mode"` // "min" or "max"
}

EarlyStoppingConfig configures early stopping behavior.

type Encoder

type Encoder interface {
	// Fit learns the encoding from categorical data
	Fit(data []string) error

	// Transform encodes categorical data to numerical
	Transform(data []string) (Tensor, error)

	// FitTransform fits and transforms in one step
	FitTransform(data []string) (Tensor, error)

	// Classes returns the learned classes
	Classes() []string

	// IsFitted returns true if the encoder has been fitted
	IsFitted() bool

	// Name returns the encoder name
	Name() string
}

Encoder represents a categorical data encoder.

type ErrorRecovery

type ErrorRecovery struct {
	// contains filtered or unexported fields
}

ErrorRecovery provides mechanisms for handling and recovering from errors.

func NewErrorRecovery

func NewErrorRecovery(config ErrorRecoveryConfig) *ErrorRecovery

NewErrorRecovery creates a new error recovery instance.

func (*ErrorRecovery) GetErrorRate

func (er *ErrorRecovery) GetErrorRate(operation string) float64

GetErrorRate returns the current error rate for an operation.

func (*ErrorRecovery) RetryWithBackoff

func (er *ErrorRecovery) RetryWithBackoff(operation string, fn func() error) error

RetryWithBackoff executes a function with retry logic and exponential backoff.

func (*ErrorRecovery) SafeTensorOperation

func (er *ErrorRecovery) SafeTensorOperation(operation string, fn func() Tensor) (Tensor, error)

SafeTensorOperation performs a tensor operation with error recovery.

func (*ErrorRecovery) ShouldCircuitBreak

func (er *ErrorRecovery) ShouldCircuitBreak(operation string) bool

ShouldCircuitBreak determines if an operation should be circuit-broken due to high error rate.

type ErrorRecoveryConfig

type ErrorRecoveryConfig struct {
	MaxRetries     int           `json:"max_retries"`
	RetryDelay     time.Duration `json:"retry_delay"`
	BackoffFactor  float64       `json:"backoff_factor"`
	EnableFallback bool          `json:"enable_fallback"`
	LogErrors      bool          `json:"log_errors"`
	FailFast       bool          `json:"fail_fast"`
	TolerateNaN    bool          `json:"tolerate_nan"`
	TolerateInf    bool          `json:"tolerate_inf"`
	MaxErrorRate   float64       `json:"max_error_rate"`
	ErrorWindow    time.Duration `json:"error_window"`
}

ErrorRecoveryConfig holds configuration for error recovery mechanisms.

func DefaultErrorRecoveryConfig

func DefaultErrorRecoveryConfig() ErrorRecoveryConfig

DefaultErrorRecoveryConfig returns a default error recovery configuration.

type ErrorType

type ErrorType int

ErrorType represents different types of errors in the library.

const (
	// ErrInvalidInput indicates invalid input parameters
	ErrInvalidInput ErrorType = iota

	// ErrDimensionMismatch indicates incompatible tensor dimensions
	ErrDimensionMismatch

	// ErrNotFitted indicates a component hasn't been fitted/trained
	ErrNotFitted

	// ErrNumericalInstability indicates numerical computation issues
	ErrNumericalInstability

	// ErrConfigurationError indicates invalid configuration
	ErrConfigurationError

	// ErrModelNotCompiled indicates model hasn't been compiled
	ErrModelNotCompiled

	// ErrFileIO indicates file input/output errors
	ErrFileIO

	// ErrUnsupportedOperation indicates unsupported operations
	ErrUnsupportedOperation

	// ErrConvergence indicates convergence failures
	ErrConvergence

	// ErrMemory indicates memory allocation issues
	ErrMemory
)

func GetErrorType

func GetErrorType(err error) (ErrorType, bool)

GetErrorType returns the error type if it's a ThinkingNetError.

func (ErrorType) String

func (et ErrorType) String() string

String returns a string representation of the error type.

type FastTensorOperations

type FastTensorOperations struct {
	// contains filtered or unexported fields
}

FastTensorOperations provides optimized tensor operations.

func GetFastTensorOperations

func GetFastTensorOperations() *FastTensorOperations

GetFastTensorOperations returns the global fast tensor operations instance.

func NewFastTensorOperations

func NewFastTensorOperations(config OptimizationConfig) *FastTensorOperations

NewFastTensorOperations creates a new fast tensor operations instance.

func (*FastTensorOperations) FastAdd

func (fto *FastTensorOperations) FastAdd(a, b Tensor, result Tensor) error

FastAdd performs optimized element-wise addition.

func (*FastTensorOperations) FastMatMul

func (fto *FastTensorOperations) FastMatMul(a, b Tensor) (Tensor, error)

FastMatMul performs optimized matrix multiplication.

type GradientClipping

type GradientClipping struct {
	MaxNorm    float64 `json:"max_norm"`
	ClipValue  float64 `json:"clip_value"`
	Strategy   string  `json:"strategy"` // "norm", "value", "adaptive"
	Percentile float64 `json:"percentile"`
}

GradientClipping provides various gradient clipping strategies.

func (*GradientClipping) ClipGradients

func (gc *GradientClipping) ClipGradients(gradients []Tensor) error

ClipGradients applies gradient clipping using the specified strategy.

type HighPerformanceProcessor

type HighPerformanceProcessor struct {
	// contains filtered or unexported fields
}

HighPerformanceProcessor provides ultra-fast operations inspired by py.fast.calc.py

func GetHighPerformanceProcessor

func GetHighPerformanceProcessor() *HighPerformanceProcessor

GetHighPerformanceProcessor returns the global high-performance processor.

func NewHighPerformanceProcessor

func NewHighPerformanceProcessor(numRegisters int) *HighPerformanceProcessor

NewHighPerformanceProcessor creates a new high-performance processor.

func (*HighPerformanceProcessor) PerformOperations

func (hpp *HighPerformanceProcessor) PerformOperations(numOperations int64) float64

PerformOperations executes high-throughput operations in parallel.

type History

type History struct {
	Epoch      []int                `json:"epoch"`
	Loss       []float64            `json:"loss"`
	Metrics    map[string][]float64 `json:"metrics"`
	ValLoss    []float64            `json:"val_loss"`
	ValMetrics map[string][]float64 `json:"val_metrics"`
	Duration   time.Duration        `json:"duration"`
	BestEpoch  int                  `json:"best_epoch"`
	BestScore  float64              `json:"best_score"`
}

History tracks training progress.

type InPlaceOperations

type InPlaceOperations struct{}

InPlaceOperations provides in-place tensor operations to reduce memory allocations.

func GetInPlaceOperations

func GetInPlaceOperations() *InPlaceOperations

GetInPlaceOperations returns the global in-place operations instance.

func NewInPlaceOperations

func NewInPlaceOperations() *InPlaceOperations

NewInPlaceOperations creates a new in-place operations instance.

func (*InPlaceOperations) AddInPlace

func (ipo *InPlaceOperations) AddInPlace(a, b Tensor) error

AddInPlace performs in-place addition: a = a + b.

func (*InPlaceOperations) MulElemInPlace

func (ipo *InPlaceOperations) MulElemInPlace(a, b Tensor) error

MulElemInPlace performs in-place element-wise multiplication: a = a * b.

func (*InPlaceOperations) ScaleInPlace

func (ipo *InPlaceOperations) ScaleInPlace(a Tensor, scalar float64) error

ScaleInPlace performs in-place scaling: a = a * scalar.

func (*InPlaceOperations) SubInPlace

func (ipo *InPlaceOperations) SubInPlace(a, b Tensor) error

SubInPlace performs in-place subtraction: a = a - b.

type Job

type Job interface {
	Execute() error
}

Job represents a unit of work to be processed.

type Layer

type Layer interface {
	// Forward performs the forward pass
	Forward(input Tensor) (Tensor, error)

	// Backward performs the backward pass and returns input gradients
	Backward(gradient Tensor) (Tensor, error)

	// Parameters returns all trainable parameters
	Parameters() []Tensor

	// Gradients returns gradients for all parameters
	Gradients() []Tensor

	// IsTrainable returns true if the layer has trainable parameters
	IsTrainable() bool

	// Name returns the layer name
	Name() string

	// SetName sets the layer name
	SetName(name string)

	// OutputShape returns the output shape given input shape
	OutputShape(inputShape []int) ([]int, error)

	// ParameterCount returns the number of trainable parameters
	ParameterCount() int
}

Layer represents a neural network layer.

type LayerConfig

type LayerConfig struct {
	Type       string         `json:"type"`
	Name       string         `json:"name"`
	Parameters map[string]any `json:"parameters"`
}

LayerConfig describes a layer configuration.

type Loss

type Loss interface {
	// Compute calculates the loss value
	Compute(yTrue, yPred Tensor) float64

	// Gradient computes the gradient of the loss
	Gradient(yTrue, yPred Tensor) Tensor

	// Name returns the loss function name
	Name() string
}

Loss represents a loss function.

type MatrixPool

type MatrixPool struct {
	// contains filtered or unexported fields
}

MatrixPool provides memory-efficient matrix reuse to reduce allocations.

func NewMatrixPool

func NewMatrixPool() *MatrixPool

NewMatrixPool creates a new matrix pool.

func NewMatrixPoolWithConfig

func NewMatrixPoolWithConfig(maxSize int, enabled bool) *MatrixPool

NewMatrixPoolWithConfig creates a new matrix pool with configuration.

func (*MatrixPool) Clear

func (p *MatrixPool) Clear()

Clear clears all pools.

func (*MatrixPool) Get

func (p *MatrixPool) Get(rows, cols int) *mat.Dense

Get retrieves a matrix from the pool or creates a new one.

func (*MatrixPool) IsEnabled

func (p *MatrixPool) IsEnabled() bool

IsEnabled returns whether the pool is enabled.

func (*MatrixPool) Put

func (p *MatrixPool) Put(matrix *mat.Dense)

Put returns a matrix to the pool for reuse.

func (*MatrixPool) SetEnabled

func (p *MatrixPool) SetEnabled(enabled bool)

SetEnabled enables or disables the pool.

func (*MatrixPool) Stats

func (p *MatrixPool) Stats() map[string]PoolStats

Stats returns statistics about the pool usage.

type MemoryLayout

type MemoryLayout struct {
	// contains filtered or unexported fields
}

MemoryLayout provides memory layout optimizations.

func NewMemoryLayout

func NewMemoryLayout() *MemoryLayout

NewMemoryLayout creates a new memory layout optimizer.

func (*MemoryLayout) AlignedAlloc

func (ml *MemoryLayout) AlignedAlloc(size int) []float64

AlignedAlloc allocates aligned memory for better SIMD performance.

type Metrics

type Metrics struct {
	Accuracy  float64 `json:"accuracy,omitempty"`
	Precision float64 `json:"precision,omitempty"`
	Recall    float64 `json:"recall,omitempty"`
	F1Score   float64 `json:"f1_score,omitempty"`
	ROCAUC    float64 `json:"roc_auc,omitempty"`
	MSE       float64 `json:"mse,omitempty"`
	RMSE      float64 `json:"rmse,omitempty"`
	MAE       float64 `json:"mae,omitempty"`
	R2Score   float64 `json:"r2_score,omitempty"`
}

Metrics holds evaluation metrics.

type Model

type Model interface {
	// Forward performs forward pass through the model
	Forward(input Tensor) (Tensor, error)

	// Backward performs backward pass
	Backward(loss Loss, yTrue, yPred Tensor) error

	// Fit trains the model
	Fit(X, y Tensor, config TrainingConfig) (*History, error)

	// Predict makes predictions
	Predict(X Tensor) (Tensor, error)

	// Evaluate evaluates the model performance
	Evaluate(X, y Tensor) (*Metrics, error)

	// Summary returns a string representation of the model
	Summary() string

	// Save saves the model to a file
	Save(path string) error

	// Load loads the model from a file
	Load(path string) error

	// Compile compiles the model with optimizer and loss
	Compile(optimizer Optimizer, loss Loss) error

	// AddLayer adds a layer to the model
	AddLayer(layer Layer) error

	// Layers returns all layers in the model
	Layers() []Layer
}

Model represents a complete machine learning model.

type ModelArchitecture

type ModelArchitecture struct {
	Type   string        `json:"type"`
	Layers []LayerConfig `json:"layers"`
}

ModelArchitecture describes the model structure.

type ModelConfig

type ModelConfig struct {
	Name       string           `json:"name"`
	Seed       int64            `json:"seed"`
	Verbose    bool             `json:"verbose"`
	Validation ValidationConfig `json:"validation"`
}

ModelConfig holds model configuration.

func NewModelConfig

func NewModelConfig(options ...ModelOption) *ModelConfig

NewModelConfig creates a new model configuration with options.

type ModelOption

type ModelOption func(*ModelConfig)

ModelOption represents a functional option for model configuration.

func WithName

func WithName(name string) ModelOption

WithName sets the model name.

func WithSeed

func WithSeed(seed int64) ModelOption

WithSeed sets the random seed.

func WithValidation

func WithValidation(split float64) ModelOption

WithValidation sets validation configuration.

func WithVerbose

func WithVerbose(verbose bool) ModelOption

WithVerbose sets verbose mode.

type ModelState

type ModelState struct {
	Architecture ModelArchitecture `json:"architecture"`
	Weights      [][]float64       `json:"weights"`
	Config       ModelConfig       `json:"config"`
	History      *History          `json:"history,omitempty"`
	Metadata     map[string]any    `json:"metadata"`
	Version      string            `json:"version"`
	Timestamp    time.Time         `json:"timestamp"`
}

ModelState represents the complete state of a model for persistence.

type OptimizationConfig

type OptimizationConfig struct {
	EnableSIMD          bool
	EnableVectorization bool
	EnableCaching       bool
	CacheSize           int
	EnableInPlace       bool
	MinParallelSize     int
}

OptimizationConfig holds configuration for performance optimizations.

func DefaultOptimizationConfig

func DefaultOptimizationConfig() OptimizationConfig

DefaultOptimizationConfig returns default optimization settings.

func GetOptimizationConfig

func GetOptimizationConfig() OptimizationConfig

GetOptimizationConfig returns the current optimization configuration.

type Optimizer

type Optimizer interface {
	// Update updates parameters using gradients
	Update(params []Tensor, grads []Tensor)

	// Step increments the optimizer step counter
	Step()

	// Reset resets the optimizer state
	Reset()

	// Config returns the optimizer configuration
	Config() OptimizerConfig

	// Name returns the optimizer name
	Name() string

	// LearningRate returns the current learning rate
	LearningRate() float64

	// SetLearningRate sets the learning rate
	SetLearningRate(lr float64)
}

Optimizer represents an optimization algorithm.

type OptimizerConfig

type OptimizerConfig struct {
	Name         string         `json:"name"`
	LearningRate float64        `json:"learning_rate"`
	Parameters   map[string]any `json:"parameters"`
}

OptimizerConfig holds optimizer configuration.

type ParallelActivationProcessor

type ParallelActivationProcessor struct {
	// contains filtered or unexported fields
}

ParallelActivationProcessor provides optimized activation function processing.

func GetParallelActivationProcessor

func GetParallelActivationProcessor() *ParallelActivationProcessor

GetParallelActivationProcessor returns the global parallel activation processor.

func NewParallelActivationProcessor

func NewParallelActivationProcessor() *ParallelActivationProcessor

NewParallelActivationProcessor creates a new parallel activation processor.

func (*ParallelActivationProcessor) ProcessReLU

func (pap *ParallelActivationProcessor) ProcessReLU(input, output []float64)

ProcessReLU applies ReLU activation in parallel.

func (*ParallelActivationProcessor) ProcessSigmoid

func (pap *ParallelActivationProcessor) ProcessSigmoid(input, output []float64)

ProcessSigmoid applies sigmoid activation in parallel with overflow protection.

func (*ParallelActivationProcessor) ProcessTanh

func (pap *ParallelActivationProcessor) ProcessTanh(input, output []float64)

ProcessTanh applies tanh activation in parallel.

type ParallelConfig

type ParallelConfig struct {
	Enabled    bool
	NumWorkers int
	ChunkSize  int
	MinSize    int // Minimum size to use parallel processing
}

ParallelConfig holds configuration for parallel operations.

func DefaultParallelConfig

func DefaultParallelConfig() ParallelConfig

DefaultParallelConfig returns default parallel configuration.

func GetParallelConfig

func GetParallelConfig() ParallelConfig

GetParallelConfig returns the current parallel configuration.

type PerformanceMetric

type PerformanceMetric struct {
	Count       int64
	TotalTime   int64 // nanoseconds
	MinTime     int64
	MaxTime     int64
	Allocations int64
	Bytes       int64
}

PerformanceMetric holds performance data for an operation.

type PerformanceProfiler

type PerformanceProfiler struct {
	// contains filtered or unexported fields
}

PerformanceProfiler tracks performance metrics.

func GetPerformanceProfiler

func GetPerformanceProfiler() *PerformanceProfiler

GetPerformanceProfiler returns the global performance profiler instance.

func NewPerformanceProfiler

func NewPerformanceProfiler() *PerformanceProfiler

NewPerformanceProfiler creates a new performance profiler.

func (*PerformanceProfiler) GetMetrics

func (pp *PerformanceProfiler) GetMetrics() map[string]PerformanceMetric

GetMetrics returns all recorded metrics.

func (*PerformanceProfiler) Reset

func (pp *PerformanceProfiler) Reset()

Reset clears all metrics.

func (*PerformanceProfiler) StartProfile

func (pp *PerformanceProfiler) StartProfile(operation string) *ProfileSession

StartProfile begins profiling an operation.

type PoolStats

type PoolStats struct {
	Gets    int64
	Puts    int64
	Creates int64
	Hits    int64
	Misses  int64
	// contains filtered or unexported fields
}

PoolStats tracks usage statistics for a pool.

type Preprocessor

type Preprocessor interface {
	// Fit learns parameters from the data
	Fit(data Tensor) error

	// Transform applies the transformation
	Transform(data Tensor) (Tensor, error)

	// FitTransform fits and transforms in one step
	FitTransform(data Tensor) (Tensor, error)

	// InverseTransform reverses the transformation
	InverseTransform(data Tensor) (Tensor, error)

	// IsFitted returns true if the preprocessor has been fitted
	IsFitted() bool

	// Name returns the preprocessor name
	Name() string
}

Preprocessor represents a data preprocessing component.

type ProfileSession

type ProfileSession struct {
	// contains filtered or unexported fields
}

ProfileSession represents an active profiling session.

func (*ProfileSession) End

func (ps *ProfileSession) End()

End ends the profiling session and records metrics.

type Regressor

type Regressor interface {
	// Fit trains the regressor
	Fit(X, y Tensor) error

	// Predict makes predictions
	Predict(X Tensor) (Tensor, error)

	// Score returns the R² score
	Score(X, y Tensor) (float64, error)

	// Name returns the regressor name
	Name() string
}

Regressor represents a regression algorithm.

type Tensor

type Tensor interface {
	// Basic operations
	Dims() (int, int)
	At(i, j int) float64
	Set(i, j int, v float64)
	Copy() Tensor

	// Arithmetic operations
	Add(other Tensor) Tensor
	Sub(other Tensor) Tensor
	Mul(other Tensor) Tensor
	MulElem(other Tensor) Tensor
	Div(other Tensor) Tensor
	Scale(scalar float64) Tensor

	// Mathematical functions
	Pow(power float64) Tensor
	Sqrt() Tensor
	Exp() Tensor
	Log() Tensor
	Abs() Tensor
	Sign() Tensor
	Clamp(min, max float64) Tensor

	// Linear algebra
	T() Tensor

	// Statistics
	Sum() float64
	Mean() float64
	Std() float64
	Max() float64
	Min() float64
	Norm() float64

	// Shape operations
	Reshape(newRows, newCols int) Tensor
	Flatten() Tensor
	Shape() []int

	// Utility operations
	Apply(fn func(i, j int, v float64) float64) Tensor
	Equal(other Tensor) bool
	Fill(value float64)
	Zero()
	Release()

	// Slicing and indexing
	Row(i int) Tensor
	Col(j int) Tensor
	Slice(r0, r1, c0, c1 int) Tensor
	SetRow(i int, data []float64)
	SetCol(j int, data []float64)

	// Properties
	IsEmpty() bool
	IsSquare() bool
	IsVector() bool

	// Metadata
	Name() string
	SetName(name string)
	String() string

	// Additional operations
	Dot(other Tensor) float64
	AddScalar(scalar float64) Tensor
	SubScalar(scalar float64) Tensor
	DivScalar(scalar float64) Tensor
	Trace() float64
	Diagonal() Tensor

	// Validation and checks
	Validate() error
	HasNaN() bool
	HasInf() bool
	IsFinite() bool

	// Low-level access
	RawMatrix() *mat.Dense
}

Tensor represents a multi-dimensional array with mathematical operations.

func CleanNaNInf

func CleanNaNInf(tensor Tensor, strategy string) (Tensor, error)

CleanNaNInf cleans NaN and Inf values from a tensor using various strategies.

func EasySplit

func EasySplit(X, y Tensor, testSize float64) (XTrain, XTest, yTrain, yTest Tensor)

EasySplit splits data into training and testing sets with sensible defaults. This is a convenience wrapper around the preprocessing.TrainTestSplit function.

func EasyTensor

func EasyTensor(data [][]float64) Tensor

EasyTensor creates a tensor from a 2D slice with simple error handling. This is a convenience function that provides better error messages for common use cases.

func OptimizedMatMul

func OptimizedMatMul(a, b Tensor) Tensor

OptimizedMatMul performs optimized matrix multiplication.

func OptimizedTensorAdd

func OptimizedTensorAdd(a, b Tensor) Tensor

OptimizedTensorAdd performs optimized tensor addition.

func ParallelBatchProcess

func ParallelBatchProcess(batches []Tensor, processor func(Tensor) (Tensor, error)) ([]Tensor, error)

ParallelBatchProcess processes batches in parallel.

func ParallelElementWiseOperation

func ParallelElementWiseOperation(a, b Tensor, operation func(float64, float64) float64) (Tensor, error)

ParallelElementWiseOperation performs element-wise operations in parallel.

func ParallelMatrixMultiply

func ParallelMatrixMultiply(a, b Tensor) (Tensor, error)

ParallelMatrixMultiply performs parallel matrix multiplication for large matrices.

func ValidateAndClean

func ValidateAndClean(tensor Tensor, name string, cleanStrategy string) (Tensor, error)

ValidateAndClean validates a tensor and applies cleaning if necessary.

type TensorJob

type TensorJob struct {
	Operation func() error
	Result    chan error
}

TensorJob represents a tensor operation job.

func (*TensorJob) Execute

func (tj *TensorJob) Execute() error

Execute runs the tensor operation.

type ThinkingNetError

type ThinkingNetError struct {
	Type    ErrorType        `json:"type"`
	Message BilingualMessage `json:"message"`
	Context map[string]any   `json:"context,omitempty"`
	Cause   error            `json:"-"` // Original error, not serialized
}

ThinkingNetError represents a structured error in the ThinkingNet library.

func NewBilingualError

func NewBilingualError(errType ErrorType, arabic, english, tip string) *ThinkingNetError

NewBilingualError creates a new ThinkingNetError with bilingual messages.

func NewBilingualErrorWithCause

func NewBilingualErrorWithCause(errType ErrorType, arabic, english, tip string, cause error) *ThinkingNetError

NewBilingualErrorWithCause creates a new ThinkingNetError with bilingual messages and underlying cause.

func NewCommonError

func NewCommonError(errType ErrorType, messageKey string) *ThinkingNetError

NewCommonError creates a new ThinkingNetError using predefined common messages.

func NewCommonErrorWithCause

func NewCommonErrorWithCause(errType ErrorType, messageKey string, cause error) *ThinkingNetError

NewCommonErrorWithCause creates a new ThinkingNetError using predefined common messages with underlying cause.

func NewError

func NewError(errType ErrorType, message string) *ThinkingNetError

NewError creates a new ThinkingNetError with English message only (for backward compatibility).

func NewErrorWithCause

func NewErrorWithCause(errType ErrorType, message string, cause error) *ThinkingNetError

NewErrorWithCause creates a new ThinkingNetError with an underlying cause.

func (*ThinkingNetError) Error

func (e *ThinkingNetError) Error() string

Error implements the error interface.

func (*ThinkingNetError) ErrorArabic

func (e *ThinkingNetError) ErrorArabic() string

ErrorArabic returns the Arabic error message.

func (*ThinkingNetError) ErrorEnglish

func (e *ThinkingNetError) ErrorEnglish() string

ErrorEnglish returns the English error message.

func (*ThinkingNetError) GetTip

func (e *ThinkingNetError) GetTip() string

GetTip returns the helpful tip for resolving the error.

func (*ThinkingNetError) Unwrap

func (e *ThinkingNetError) Unwrap() error

Unwrap returns the underlying error.

func (*ThinkingNetError) WithContext

func (e *ThinkingNetError) WithContext(key string, value any) *ThinkingNetError

WithContext adds context information to the error.

type TrainingConfig

type TrainingConfig struct {
	Epochs          int                 `json:"epochs"`
	BatchSize       int                 `json:"batch_size"`
	LearningRate    float64             `json:"learning_rate"`
	ValidationSplit float64             `json:"validation_split"`
	EarlyStopping   EarlyStoppingConfig `json:"early_stopping"`
	Callbacks       []Callback          `json:"-"` // Not serializable
	Metrics         []string            `json:"metrics"`
	Verbose         int                 `json:"verbose"`
	Shuffle         bool                `json:"shuffle"`
	Seed            int64               `json:"seed"`
}

TrainingConfig holds configuration for model training.

func NewTrainingConfig

func NewTrainingConfig() *TrainingConfig

NewTrainingConfig creates a default training configuration.

type UltraFastActivationProcessor

type UltraFastActivationProcessor struct {
	// contains filtered or unexported fields
}

UltraFastActivationProcessor provides maximum speed activation functions using lookup tables.

func GetUltraFastActivationProcessor

func GetUltraFastActivationProcessor() *UltraFastActivationProcessor

GetUltraFastActivationProcessor returns the global ultra-fast activation processor.

func NewUltraFastActivationProcessor

func NewUltraFastActivationProcessor() *UltraFastActivationProcessor

NewUltraFastActivationProcessor creates ultra-fast activation processor with lookup tables.

func (*UltraFastActivationProcessor) UltraFastReLU

func (ufap *UltraFastActivationProcessor) UltraFastReLU(input, output []float64)

UltraFastReLU applies ReLU using bitwise operations for maximum speed.

func (*UltraFastActivationProcessor) UltraFastSigmoid

func (ufap *UltraFastActivationProcessor) UltraFastSigmoid(input, output []float64)

UltraFastSigmoid applies sigmoid using pre-computed lookup table.

func (*UltraFastActivationProcessor) UltraFastTanh

func (ufap *UltraFastActivationProcessor) UltraFastTanh(input, output []float64)

UltraFastTanh applies tanh using pre-computed lookup table.

type UltraFastProcessor

type UltraFastProcessor struct {
	// contains filtered or unexported fields
}

UltraFastProcessor provides maximum speed operations using uint8 and bitwise ops

func GetUltraFastProcessor

func GetUltraFastProcessor() *UltraFastProcessor

GetUltraFastProcessor returns the global ultra-fast processor (maximum speed).

func NewUltraFastProcessor

func NewUltraFastProcessor(numRegisters int) *UltraFastProcessor

NewUltraFastProcessor creates the fastest possible processor using uint8 operations.

func (*UltraFastProcessor) PerformUltraFastOperations

func (ufp *UltraFastProcessor) PerformUltraFastOperations(numOperations int64) float64

PerformUltraFastOperations executes maximum speed operations using bitwise ops.

type UltraFastVectorOps

type UltraFastVectorOps struct {
	// contains filtered or unexported fields
}

UltraFastVectorOps provides maximum speed vectorized operations using unsafe pointers.

func GetUltraFastVectorOps

func GetUltraFastVectorOps() *UltraFastVectorOps

GetUltraFastVectorOps returns the global ultra-fast vector operations processor.

func NewUltraFastVectorOps

func NewUltraFastVectorOps() *UltraFastVectorOps

NewUltraFastVectorOps creates ultra-fast vectorized operations.

func (*UltraFastVectorOps) ParallelUltraFastAdd

func (ufvo *UltraFastVectorOps) ParallelUltraFastAdd(a, b []float64) []float64

ParallelUltraFastAdd performs parallel ultra-fast vector addition.

func (*UltraFastVectorOps) UnsafeVectorAdd

func (ufvo *UltraFastVectorOps) UnsafeVectorAdd(a, b []float64) []float64

UnsafeVectorAdd performs ultra-fast vector addition using unsafe pointers and 8-element unrolling.

type ValidationConfig

type ValidationConfig struct {
	Split   float64 `json:"split"`
	Method  string  `json:"method"` // "split", "kfold", "stratified"
	Folds   int     `json:"folds"`
	Shuffle bool    `json:"shuffle"`
	Seed    int64   `json:"seed"`
}

ValidationConfig holds validation configuration.

type VectorizedOperations

type VectorizedOperations struct {
	// contains filtered or unexported fields
}

VectorizedOperations provides SIMD-like operations for better performance.

func GetVectorizedOperations

func GetVectorizedOperations() *VectorizedOperations

GetVectorizedOperations returns the global vectorized operations processor.

func NewVectorizedOperations

func NewVectorizedOperations() *VectorizedOperations

NewVectorizedOperations creates a new vectorized operations processor.

func (*VectorizedOperations) VectorAdd

func (vo *VectorizedOperations) VectorAdd(a, b []float64) []float64

VectorAdd performs optimized vector addition with loop unrolling.

func (*VectorizedOperations) VectorMul

func (vo *VectorizedOperations) VectorMul(a, b []float64) []float64

VectorMul performs optimized vector multiplication with loop unrolling.

type WorkerPool

type WorkerPool struct {
	// contains filtered or unexported fields
}

WorkerPool manages a pool of workers for parallel processing.

func NewWorkerPool

func NewWorkerPool(numWorkers int) *WorkerPool

NewWorkerPool creates a new worker pool.

func (*WorkerPool) Start

func (wp *WorkerPool) Start()

Start starts the worker pool.

func (*WorkerPool) Stop

func (wp *WorkerPool) Stop()

Stop stops the worker pool.

func (*WorkerPool) Submit

func (wp *WorkerPool) Submit(job Job) error

Submit submits a job to the worker pool.

Jump to

Keyboard shortcuts

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