Documentation
¶
Overview ¶
Package errors provides error handling and warning systems for the entire project. Inspired by scikit-learn's warning and exception system, it provides structured error information.
Example ¶
Example demonstrates Go 1.13+ error wrapping
package main
import (
"errors"
"fmt"
)
func main() {
// Create a base error
baseErr := fmt.Errorf("invalid input value")
// Wrap the error with context using Go 1.13+ syntax
wrappedErr := fmt.Errorf("model validation failed: %w", baseErr)
// Further wrap with operation context
opErr := fmt.Errorf("LinearRegression.Fit: %w", wrappedErr)
// Use errors.Is to check for specific error types
if errors.Is(opErr, baseErr) {
fmt.Println("Found base error in chain")
}
// Unwrap errors to get the underlying cause
unwrapped := errors.Unwrap(opErr)
fmt.Printf("Unwrapped: %v\n", unwrapped)
}
Output: Found base error in chain Unwrapped: model validation failed: invalid input value
Example (CustomErrorTypes) ¶
Example_customErrorTypes demonstrates custom error type handling
package main
import (
"errors"
"fmt"
scigoErrors "github.com/YuminosukeSato/scigo/pkg/errors"
)
func main() {
// Create a custom error using our error constructors
dimErr := scigoErrors.NewDimensionError("Transform", 5, 3, 1)
// Wrap it with additional context
wrappedErr := fmt.Errorf("preprocessing failed: %w", dimErr)
// Check if error is of specific type using errors.As
var dimensionErr *scigoErrors.DimensionError
if errors.As(wrappedErr, &dimensionErr) {
fmt.Printf("Dimension error: expected %d, got %d\n",
dimensionErr.Expected, dimensionErr.Got)
}
}
Output: Dimension error: expected 5, got 3
Example (ErrorChaining) ¶
Example_errorChaining demonstrates practical error chaining in ML operations
package main
import (
"errors"
"fmt"
)
func main() {
// Simulate a machine learning pipeline error
simulateMLError := func() error {
// Simulate data validation error
dataErr := fmt.Errorf("invalid data format")
// Wrap with preprocessing context
prepErr := fmt.Errorf("data preprocessing failed: %w", dataErr)
// Wrap with model training context
trainErr := fmt.Errorf("model training failed: %w", prepErr)
return trainErr
}
err := simulateMLError()
// Print the full error chain
fmt.Printf("Error: %v\n", err)
// Walk through the error chain
current := err
level := 0
for current != nil {
fmt.Printf("Level %d: %v\n", level, current)
current = errors.Unwrap(current)
level++
}
}
Output: Error: model training failed: data preprocessing failed: invalid data format Level 0: model training failed: data preprocessing failed: invalid data format Level 1: data preprocessing failed: invalid data format Level 2: invalid data format
Example (ErrorComparison) ¶
Example_errorComparison demonstrates error comparison patterns
package main
import (
"errors"
"fmt"
scigoErrors "github.com/YuminosukeSato/scigo/pkg/errors"
)
func main() {
// Create different types of errors
notFittedErr := scigoErrors.NewNotFittedError("LinearRegression", "Predict")
valueErr := scigoErrors.NewValueError("StandardScaler", "negative values not supported")
// Create a sentinel error for comparison
var customErr = errors.New("custom processing error")
wrappedCustom := fmt.Errorf("operation failed: %w", customErr)
// Use errors.Is for sentinel error checking
if errors.Is(wrappedCustom, customErr) {
fmt.Println("Custom error detected")
}
// Use errors.As for type assertions
var notFitted *scigoErrors.NotFittedError
if errors.As(notFittedErr, ¬Fitted) {
fmt.Printf("Model %s is not fitted for %s\n",
notFitted.ModelName, notFitted.Method)
}
var valErr *scigoErrors.ValueError
if errors.As(valueErr, &valErr) {
fmt.Printf("Value error in %s: %s\n", valErr.Op, valErr.Message)
}
}
Output: Custom error detected Model LinearRegression is not fitted for Predict Value error in StandardScaler: negative values not supported
Example (ErrorLogging) ¶
Example_errorLogging demonstrates structured error logging
package main
import (
"fmt"
"log"
scigoErrors "github.com/YuminosukeSato/scigo/pkg/errors"
)
func main() {
// Create a complex error with context
baseErr := scigoErrors.NewModelError("SGD", "convergence failure",
scigoErrors.ErrNotImplemented)
// Wrap with operation context
opErr := fmt.Errorf("online learning iteration 150: %w", baseErr)
// Log different levels of detail
log.Printf("Simple: %v", opErr)
log.Printf("Detailed: %+v", opErr) // This would show stack trace with cockroachdb/errors
// For production, you'd use structured logging
fmt.Printf("Error occurred in online learning: %v\n", opErr)
}
Output: Error occurred in online learning: online learning iteration 150: goml: SGD: convergence failure: not implemented
Index ¶
- Variables
- func As(err error, target interface{}) bool
- func CheckMatrix(operation string, matrix interface{ ... }, rows, cols, iteration int) error
- func CheckNumericalStability(operation string, values []float64, iteration int) error
- func CheckScalar(operation string, value float64, iteration int) error
- func ClipGradient(gradient []float64, maxNorm float64) []float64
- func ClipValue(value, min, max float64) float64
- func Is(err, target error) bool
- func LogSumExp(values []float64) float64
- func New(message string) error
- func NewDimensionError(op string, expected, got, axis int) error
- func NewInputShapeError(phase string, expected, got []int) error
- func NewModelError(op, kind string, err error) error
- func NewNotFittedError(modelName, method string) error
- func NewNumericalInstabilityError(operation string, values []float64, iteration int) error
- func NewValidationError(param, reason string, value interface{}) error
- func NewValueError(op, message string) error
- func Newf(format string, args ...interface{}) error
- func Recover(err *error, operation string)
- func SafeDivide(numerator, denominator float64) float64
- func SafeExecute(operation string, fn func() error) (err error)
- func SetWarningHandler(handler func(w error))
- func SetZerologWarnFunc(warnFunc func(warning error))
- func StabilizeExp(value float64) float64
- func StabilizeLog(value float64) float64
- func Warn(w error)
- func WithStack(err error) error
- func Wrap(err error, message string) error
- func Wrapf(err error, format string, args ...interface{}) error
- type CatastrophicForgettingWarning
- type ConvergenceWarning
- type DataConversionWarning
- type DimensionError
- type InputShapeError
- type ModelDriftWarning
- type ModelError
- type NotFittedError
- type NumericalInstabilityError
- type PanicError
- type UndefinedMetricWarning
- type ValidationError
- type ValueError
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var ( // ErrNotImplemented は機能が未実装の場合のエラーです。 ErrNotImplemented = New("not implemented") // ErrEmptyData は空のデータが渡された場合のエラーです。 ErrEmptyData = New("empty data") // ErrSingularMatrix は特異行列の場合のエラーです。 ErrSingularMatrix = New("singular matrix") )
Functions ¶
func CheckMatrix ¶
func CheckMatrix(operation string, matrix interface{ At(int, int) float64 }, rows, cols, iteration int) error
CheckMatrix checks all values in a matrix for numerical instability.
func CheckNumericalStability ¶
CheckNumericalStability checks if values contain NaN or Inf and returns an error if numerical instability is detected.
func CheckScalar ¶
CheckScalar checks a single scalar value for numerical instability.
func ClipGradient ¶
ClipGradient clips gradient values to prevent explosion.
func NewDimensionError ¶
NewDimensionError creates a new DimensionError with stack trace.
func NewInputShapeError ¶
NewInputShapeError は新しいInputShapeErrorを作成します。
func NewModelError ¶
NewModelError creates a new ModelError with stack trace.
func NewNotFittedError ¶
NewNotFittedError creates a new NotFittedError with stack trace.
func NewNumericalInstabilityError ¶
NewNumericalInstabilityError creates a new NumericalInstabilityError.
func NewValidationError ¶
NewValidationError creates a new ValidationError with stack trace.
func NewValueError ¶
NewValueError creates a new ValueError with stack trace.
func Recover ¶
Recover is a utility function to be used with defer to recover from panics and convert them into errors. It includes stack trace information for debugging.
This function should be called with a pointer to the error return value of the function where it's used.
Usage:
func SomeMethod() (err error) {
defer Recover(&err, "SomeMethod")
// ... method implementation ...
return nil
}
If a panic occurs, it will be converted to a PanicError and assigned to err. If the function already has an error, the panic information will be wrapped.
func SafeDivide ¶
SafeDivide performs division with protection against division by zero. Returns 0 if denominator is zero or close to zero.
func SafeExecute ¶
SafeExecute executes a function and recovers from any panic, converting it to an error. This is useful for wrapping dangerous operations that might panic.
Parameters:
- operation: A descriptive name for the operation being performed
- fn: The function to execute safely
Returns:
- error: nil if successful, PanicError if panic occurred, or original error from fn
Example:
err := SafeExecute("matrix inversion", func() error {
// ... potentially panicking code ...
return someOperation()
})
func SetWarningHandler ¶
func SetWarningHandler(handler func(w error))
SetWarningHandler sets the warning handler for the entire GoML library. This allows you to control how custom warnings like ConvergenceWarning are handled.
Example:
errors.SetWarningHandler(func(w error) {
// Ignore warnings
})
func SetZerologWarnFunc ¶
func SetZerologWarnFunc(warnFunc func(warning error))
SetZerologWarnFunc sets the zerolog warning function (to avoid circular import).
func StabilizeExp ¶
StabilizeExp computes exp with protection against overflow. Clips the input to prevent exp from returning Inf.
func StabilizeLog ¶
StabilizeLog computes log with protection against log(0). Returns log(max(value, epsilon)) where epsilon is a small positive number.
Types ¶
type CatastrophicForgettingWarning ¶
type CatastrophicForgettingWarning struct {
OldPerformance float64 // 以前のパフォーマンス
NewPerformance float64 // 現在のパフォーマンス
DropRate float64 // 性能低下率
Metric string // 使用したメトリクス(例: "accuracy", "f1_score")
}
CatastrophicForgettingWarning は破滅的忘却が発生した可能性がある場合の警告です。
func NewCatastrophicForgettingWarning ¶
func NewCatastrophicForgettingWarning(metric string, oldPerf, newPerf float64) *CatastrophicForgettingWarning
NewCatastrophicForgettingWarning は新しいCatastrophicForgettingWarningを作成します。
func (*CatastrophicForgettingWarning) Error ¶
func (w *CatastrophicForgettingWarning) Error() string
type ConvergenceWarning ¶
ConvergenceWarning is a warning raised when optimization algorithms fail to converge.
func NewConvergenceWarning ¶
func NewConvergenceWarning(algorithm string, iterations int, message string) *ConvergenceWarning
NewConvergenceWarning creates a new ConvergenceWarning.
func (*ConvergenceWarning) Error ¶
func (w *ConvergenceWarning) Error() string
func (*ConvergenceWarning) MarshalZerologObject ¶
func (w *ConvergenceWarning) MarshalZerologObject(e *zerolog.Event)
MarshalZerologObject adds structured warning information to zerolog events.
type DataConversionWarning ¶
DataConversionWarning is a warning raised when data types are implicitly converted.
func NewDataConversionWarning ¶
func NewDataConversionWarning(from, to, reason string) *DataConversionWarning
NewDataConversionWarning creates a new DataConversionWarning.
func (*DataConversionWarning) Error ¶
func (w *DataConversionWarning) Error() string
func (*DataConversionWarning) MarshalZerologObject ¶
func (w *DataConversionWarning) MarshalZerologObject(e *zerolog.Event)
MarshalZerologObject adds structured warning information to zerolog events.
type DimensionError ¶
type DimensionError struct {
Op string
Expected int
Got int
Axis int // 0 for rows, 1 for columns/features
}
DimensionError is an error raised when input data dimensions don't match expected values.
func (*DimensionError) Error ¶
func (e *DimensionError) Error() string
func (*DimensionError) MarshalZerologObject ¶
func (e *DimensionError) MarshalZerologObject(event *zerolog.Event)
MarshalZerologObject adds structured error information to zerolog events.
type InputShapeError ¶
type InputShapeError struct {
Phase string // "training", "prediction", "transform"
Expected []int // 期待される形状
Got []int // 実際の形状
Feature string // 問題のある特徴量名(オプション)
}
InputShapeError は入力データの形状が期待と異なる場合のエラーです。 DimensionErrorより詳細で、訓練時と推論時の不整合を検出します。
func (*InputShapeError) Error ¶
func (e *InputShapeError) Error() string
type ModelDriftWarning ¶
type ModelDriftWarning struct {
DriftScore float64 // ドリフトスコア(検出器により異なる)
Threshold float64 // 閾値
Detector string // 使用したドリフト検出器(例: "DDM", "ADWIN")
Action string // 推奨アクション("reset", "alert", "retrain")
Timestamp int64 // ドリフト検出時のタイムスタンプ(Unix時間)
}
ModelDriftWarning はモデルドリフトが検出された場合の警告です。
func NewModelDriftWarning ¶
func NewModelDriftWarning(detector string, score, threshold float64, action string) *ModelDriftWarning
NewModelDriftWarning は新しいModelDriftWarningを作成します。
func (*ModelDriftWarning) Error ¶
func (w *ModelDriftWarning) Error() string
type ModelError ¶
ModelError is a general error related to machine learning models.
func (*ModelError) Error ¶
func (e *ModelError) Error() string
func (*ModelError) Unwrap ¶
func (e *ModelError) Unwrap() error
type NotFittedError ¶
NotFittedError is an error raised when calling `Predict` or `Transform` on an unfitted model.
func (*NotFittedError) Error ¶
func (e *NotFittedError) Error() string
func (*NotFittedError) MarshalZerologObject ¶
func (e *NotFittedError) MarshalZerologObject(event *zerolog.Event)
MarshalZerologObject adds structured error information to zerolog events.
type NumericalInstabilityError ¶
type NumericalInstabilityError struct {
Operation string // Operation where error occurred (e.g., "gradient_update", "loss_calculation")
Values []float64 // Problematic values
Context map[string]interface{} // Additional context for debugging
Iteration int // Iteration number where error occurred
}
NumericalInstabilityError is an error raised when numerical computation becomes unstable. It detects NaN, Inf, overflow, underflow, etc.
func (*NumericalInstabilityError) Error ¶
func (e *NumericalInstabilityError) Error() string
type PanicError ¶
type PanicError struct {
// PanicValue is the original value passed to panic()
PanicValue interface{}
// StackTrace contains the stack trace at the time of panic
StackTrace string
// Operation identifies where the panic was recovered
Operation string
}
PanicError represents an error that was created from a recovered panic. It includes the original panic value and stack trace information.
func NewPanicError ¶
func NewPanicError(operation string, panicValue interface{}) *PanicError
NewPanicError creates a new PanicError with the given operation context and panic value.
func (*PanicError) Error ¶
func (e *PanicError) Error() string
Error implements the error interface for PanicError.
func (*PanicError) String ¶
func (e *PanicError) String() string
String provides detailed information including stack trace.
func (*PanicError) Unwrap ¶
func (e *PanicError) Unwrap() error
Unwrap returns nil as PanicError doesn't wrap another error by default.
type UndefinedMetricWarning ¶
type UndefinedMetricWarning struct {
Metric string
Condition string
Result float64 // Value returned under this condition
}
UndefinedMetricWarning is a warning raised when metrics cannot be calculated. For example, when calculating precision with no positive class predictions.
func NewUndefinedMetricWarning ¶
func NewUndefinedMetricWarning(metric, condition string, result float64) *UndefinedMetricWarning
NewUndefinedMetricWarning creates a new UndefinedMetricWarning.
func (*UndefinedMetricWarning) Error ¶
func (w *UndefinedMetricWarning) Error() string
type ValidationError ¶
ValidationError is an error raised when input parameter validation fails. It indicates more specific validation logic failures than `ValueError`.
func (*ValidationError) Error ¶
func (e *ValidationError) Error() string
func (*ValidationError) MarshalZerologObject ¶
func (e *ValidationError) MarshalZerologObject(event *zerolog.Event)
MarshalZerologObject adds structured error information to zerolog events.
type ValueError ¶
ValueError is an error raised when argument values are inappropriate or invalid. For example, passing negative numbers to a `log` function.
func (*ValueError) Error ¶
func (e *ValueError) Error() string