From d3392126d9028cda28128f6c72b9891dfa563d62 Mon Sep 17 00:00:00 2001 From: Vladislav Sarychev Date: Wed, 26 Nov 2025 17:22:02 +0700 Subject: [PATCH 1/3] first trie v1 --- .idea/vcs.xml | 6 ++++++ main.go | 12 ------------ 2 files changed, 6 insertions(+), 12 deletions(-) create mode 100644 .idea/vcs.xml diff --git a/.idea/vcs.xml b/.idea/vcs.xml new file mode 100644 index 0000000..94a25f7 --- /dev/null +++ b/.idea/vcs.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/main.go b/main.go index 05c0654..bf4b3a2 100644 --- a/main.go +++ b/main.go @@ -15,14 +15,6 @@ type Matrix [][]float64 func (v Vector) Copy() Vector { c := make(Vector, len(v)); copy(c, v); return c } func Zeros(n int) Vector { return make(Vector, n) } -func Eye(n int) Matrix { - m := make(Matrix, n) - for i := range m { - m[i] = make([]float64, n) - m[i][i] = 1 - } - return m -} func (v Vector) Add(u Vector) { for i := range v { v[i] += u[i] @@ -45,10 +37,6 @@ func Dot(a, b Vector) float64 { } return s } -func MatTMat(m Matrix) Matrix { // M^T * M - t := Transpose(m) - return MatMul(t, m) -} func MatVec(m Matrix, x Vector) Vector { y := make(Vector, len(m)) for i := range m { From 066d1771239b55327128bb52ebba981746e874c0 Mon Sep 17 00:00:00 2001 From: Vladislav Sarychev Date: Wed, 26 Nov 2025 21:07:41 +0700 Subject: [PATCH 2/3] first trie v2 --- main.go | 114 +++++++++++++++++++++++++------------------------------- 1 file changed, 51 insertions(+), 63 deletions(-) diff --git a/main.go b/main.go index bf4b3a2..56274fa 100644 --- a/main.go +++ b/main.go @@ -75,7 +75,7 @@ func Transpose(a Matrix) Matrix { return t } -// Решение A x = b (простой Гаусс с частичным выбором) +// Решение A x = b func Solve(A Matrix, b Vector) (Vector, error) { n := len(A) M := make(Matrix, n) @@ -124,46 +124,44 @@ func Solve(A Matrix, b Vector) (Vector, error) { /********** ИНТЕРФЕЙСЫ **********/ // Functions -type ParametricFunction interface { - Bind(params Vector) Function +type IParametricFunction interface { + Bind(params Vector) IFunction } -type Function interface { +type IFunction interface { Value(x Vector) float64 } -type DifferentiableFunction interface { - Function - // ∂f(x)/∂θ (градиент по параметрам исходной ParametricFunction) +type IDifferentiableFunction interface { + IFunction Gradient(x Vector) Vector } // Functionals -type Functional interface { - Value(f Function) float64 +type IFunctional interface { + Value(f IFunction) float64 } type DifferentiableFunctional interface { - Functional - // ∂J/∂θ для f, которая умеет ∂f/∂θ - Gradient(f DifferentiableFunction) Vector + IFunctional + Gradient(f IDifferentiableFunction) Vector } -type LeastSquaresFunctional interface { - Functional - Residual(f Function) Vector - Jacobian(f DifferentiableFunction) Matrix // ∂r_i/∂θ +type ILeastSquaresFunctional interface { + IFunctional + Residual(f IFunction) Vector + Jacobian(f IDifferentiableFunction) Matrix } // Оптимизатор -type Optimizator interface { - Minimize(obj Functional, fn ParametricFunction, initial Vector, min, max Vector) Vector +type IOptimizator interface { + Minimize(obj IFunctional, fn IParametricFunction, initial Vector, min, max Vector) Vector } /********** ФУНКЦИИ **********/ -// 1) Линейная в R^n: f(x)=w·x + b, параметры θ=[w,b] +// 1) Линейная в n-мерном пространстве type LinearN struct { n int } -type boundLinear struct{ theta Vector } // [w..., b] -func (p LinearN) Bind(params Vector) Function { return &boundLinear{theta: params.Copy()} } +type boundLinear struct{ theta Vector } // [w..., b] +func (p LinearN) Bind(params Vector) IFunction { return &boundLinear{theta: params.Copy()} } func (b *boundLinear) Value(x Vector) float64 { w := b.theta[:len(b.theta)-1] bias := b.theta[len(b.theta)-1] @@ -176,12 +174,12 @@ func (b *boundLinear) Gradient(x Vector) Vector { return g } -// 2) Полином степени n в R¹: f(x)=Σ a_k x^k (НЕ DifferentiableFunction по заданию) +// 2) Полином n-ой степени в одномерном пространстве type Poly1D struct { deg int } -type boundPoly struct{ a Vector } // a0..an -func (p Poly1D) Bind(params Vector) Function { return &boundPoly{a: params.Copy()} } +type boundPoly struct{ a Vector } // a0..an +func (p Poly1D) Bind(params Vector) IFunction { return &boundPoly{a: params.Copy()} } func (b *boundPoly) Value(x Vector) float64 { x1 := x[0] pwr := 1.0 @@ -193,7 +191,7 @@ func (b *boundPoly) Value(x Vector) float64 { return s } -// 3) Кусочно-линейная 1D: узлы фиксированы, параметры — значения в узлах (DifferentiableFunction) +// 3) Кусочно-линейная функция type PiecewiseLinear1D struct { knots Vector // фиксированные x-узлы } @@ -202,7 +200,7 @@ type boundPWL struct { y Vector // параметры (значения в узлах) } -func (p PiecewiseLinear1D) Bind(params Vector) Function { +func (p PiecewiseLinear1D) Bind(params Vector) IFunction { // предполагаем, что len(params)==len(knots) return &boundPWL{knots: p.knots, y: params.Copy()} } @@ -231,23 +229,19 @@ func (b *boundPWL) Gradient(x Vector) Vector { return g } -// 4) Кубический сплайн 1D (для простоты: натянутые отрезки; только Value) +// 4) Кубический сплайн type CubicSpline1D struct { knots Vector // x - coef Matrix // коэффициенты на каждом интервале [a,b]: c0+c1*h+c2*h^2+c3*h^3 + coef Matrix } type boundSpline struct{ sp CubicSpline1D } -func (s CubicSpline1D) Bind(params Vector) Function { - // params — значения в узлах; коэффициенты считаем (натуральный сплайн) +func (s CubicSpline1D) Bind(params Vector) IFunction { n := len(s.knots) y := params.Copy() - // простая C2-аппроксимация (здесь — “not-a-knot” упрощённо) - // Для краткости используем линейную интерполяцию и поднимаем до куба с нулевыми вторыми производными. coef := make(Matrix, n-1) for i := 0; i < n-1; i++ { h := s.knots[i+1] - s.knots[i] - // Возьмём куб, совпадающий значениями и нулевыми втор.производными c0 := y[i] c1 := (y[i+1] - y[i]) / h c2 := 0.0 @@ -277,10 +271,10 @@ type Samples struct { Y Vector } -// L1: sum |r_i| (субградиент sign) +// L1 type L1Functional struct{ Data Samples } -func (f L1Functional) Value(fn Function) float64 { +func (f L1Functional) Value(fn IFunction) float64 { s := 0.0 for i := range f.Data.X { r := fn.Value(f.Data.X[i]) - f.Data.Y[i] @@ -288,8 +282,7 @@ func (f L1Functional) Value(fn Function) float64 { } return s } -func (f L1Functional) Gradient(fn DifferentiableFunction) Vector { - // θ-размер берём из градиента первого примера +func (f L1Functional) Gradient(fn IDifferentiableFunction) Vector { g := fn.Gradient(f.Data.X[0]) grad := Zeros(len(g)) for i := range f.Data.X { @@ -299,7 +292,7 @@ func (f L1Functional) Gradient(fn DifferentiableFunction) Vector { sign = 1 } else if r < 0 { sign = -1 - } // r==0 ⇒ 0 (субградиент) + } gi := fn.Gradient(f.Data.X[i]) for j := range grad { grad[j] += sign * gi[j] @@ -308,10 +301,10 @@ func (f L1Functional) Gradient(fn DifferentiableFunction) Vector { return grad } -// L2: sum r_i^2 + LS-атрибуты +// L2 type L2Functional struct{ Data Samples } -func (f L2Functional) Value(fn Function) float64 { +func (f L2Functional) Value(fn IFunction) float64 { s := 0.0 for i := range f.Data.X { r := fn.Value(f.Data.X[i]) - f.Data.Y[i] @@ -319,7 +312,7 @@ func (f L2Functional) Value(fn Function) float64 { } return s } -func (f L2Functional) Gradient(fn DifferentiableFunction) Vector { +func (f L2Functional) Gradient(fn IDifferentiableFunction) Vector { grad := Zeros(len(fn.Gradient(f.Data.X[0]))) for i := range f.Data.X { r := fn.Value(f.Data.X[i]) - f.Data.Y[i] @@ -330,14 +323,14 @@ func (f L2Functional) Gradient(fn DifferentiableFunction) Vector { } return grad } -func (f L2Functional) Residual(fn Function) Vector { +func (f L2Functional) Residual(fn IFunction) Vector { r := make(Vector, len(f.Data.X)) for i := range f.Data.X { r[i] = fn.Value(f.Data.X[i]) - f.Data.Y[i] } return r } -func (f L2Functional) Jacobian(fn DifferentiableFunction) Matrix { +func (f L2Functional) Jacobian(fn IDifferentiableFunction) Matrix { m := len(f.Data.X) p := len(fn.Gradient(f.Data.X[0])) J := make(Matrix, m) @@ -350,10 +343,10 @@ func (f L2Functional) Jacobian(fn DifferentiableFunction) Matrix { return J } -// Linf: max |r_i| +// Linf type LinfFunctional struct{ Data Samples } -func (f LinfFunctional) Value(fn Function) float64 { +func (f LinfFunctional) Value(fn IFunction) float64 { mx := 0.0 for i := range f.Data.X { r := math.Abs(fn.Value(f.Data.X[i]) - f.Data.Y[i]) @@ -364,13 +357,13 @@ func (f LinfFunctional) Value(fn Function) float64 { return mx } -// Численный интеграл по [a,b] (1D), усреднённый (трапеции) +// Численный интеграл type IntegralFunctional struct { A, B float64 N int } -func (f IntegralFunctional) Value(fn Function) float64 { +func (f IntegralFunctional) Value(fn IFunction) float64 { if f.N <= 0 { f.N = 256 } @@ -389,14 +382,14 @@ func (f IntegralFunctional) Value(fn Function) float64 { /********** ОПТИМИЗАТОРЫ **********/ -// 1) Имитация отжига (универсальный) +// 1) Имитация отжига type Annealing struct { Iter int T0 float64 Step float64 } -func (a Annealing) Minimize(obj Functional, pf ParametricFunction, initial Vector, min, max Vector) Vector { +func (a Annealing) Minimize(obj IFunctional, pf IParametricFunction, initial Vector, min, max Vector) Vector { rng := rand.New(rand.NewSource(time.Now().UnixNano())) theta := initial.Copy() best := theta.Copy() @@ -416,7 +409,6 @@ func (a Annealing) Minimize(obj Functional, pf ParametricFunction, initial Vecto n := len(theta) for it := 0; it < maxInt(a.Iter, 2000); it++ { - // предложение copy(next, theta) for j := 0; j < n; j++ { next[j] += (rng.Float64()*2 - 1) * step @@ -443,13 +435,13 @@ func (a Annealing) Minimize(obj Functional, pf ParametricFunction, initial Vecto return best } -// 2) Градиентный спуск (требует DifferentiableFunctional) +// 2) Градиентный спуск type GradDescent struct { Iters int LR float64 } -func (gd GradDescent) Minimize(obj Functional, pf ParametricFunction, initial Vector, min, max Vector) Vector { +func (gd GradDescent) Minimize(obj IFunctional, pf IParametricFunction, initial Vector, min, max Vector) Vector { df, ok := obj.(DifferentiableFunctional) if !ok { panic("GradDescent requires DifferentiableFunctional") @@ -462,8 +454,7 @@ func (gd GradDescent) Minimize(obj Functional, pf ParametricFunction, initial Ve iters := maxInt(gd.Iters, 500) for i := 0; i < iters; i++ { - // нужна DifferentiableFunction → пробуем связать с линейной/кусочно-линейной - fn, ok := pf.Bind(theta).(DifferentiableFunction) + fn, ok := pf.Bind(theta).(IDifferentiableFunction) if !ok { panic("bound function is not DifferentiableFunction") } @@ -482,13 +473,13 @@ func (gd GradDescent) Minimize(obj Functional, pf ParametricFunction, initial Ve return theta } -// 3) Гаусса-Ньютона (требует LeastSquaresFunctional) +// 3) Гаусса-Ньютона type GaussNewton struct { Iters int } -func (gn GaussNewton) Minimize(obj Functional, pf ParametricFunction, initial Vector, min, max Vector) Vector { - ls, ok := obj.(LeastSquaresFunctional) +func (gn GaussNewton) Minimize(obj IFunctional, pf IParametricFunction, initial Vector, min, max Vector) Vector { + ls, ok := obj.(ILeastSquaresFunctional) if !ok { panic("Gauss-Newton requires ILeastSquaresFunctional") } @@ -497,7 +488,7 @@ func (gn GaussNewton) Minimize(obj Functional, pf ParametricFunction, initial Ve for k := 0; k < iters; k++ { fn := pf.Bind(theta) - df, ok := fn.(DifferentiableFunction) + df, ok := fn.(IDifferentiableFunction) if !ok { panic("bound function is not DifferentiableFunction") } @@ -522,7 +513,6 @@ func (gn GaussNewton) Minimize(obj Functional, pf ParametricFunction, initial Ve theta[i] = max[i] } } - // простая остановка if math.Sqrt(Dot(delta, delta)) < 1e-8 { break } @@ -533,7 +523,6 @@ func (gn GaussNewton) Minimize(obj Functional, pf ParametricFunction, initial Ve /********** ПРИМЕР ИСПОЛЬЗОВАНИЯ **********/ func main() { - // Данные: y ≈ 2*x1 - 0.5*x2 + 1 data := Samples{ X: []Vector{ {0, 0}, {1, 0}, {0, 1}, {2, -1}, {3, 2}, @@ -541,12 +530,11 @@ func main() { Y: Vector{1, 3, 0.5, 2*2 - 0.5*(-1) + 1, 2*3 - 0.5*2 + 1}, } - // Линейная модель в R^2 → параметры: [w1, w2, b] fn := LinearN{n: 2} fL2 := L2Functional{Data: data} initial := Vector{0, 0, 0} - // 1) Гаусса-Ньютона (для LS) + // 1) Гаусса-Ньютона thetaGN := (GaussNewton{Iters: 20}).Minimize(fL2, fn, initial, nil, nil) fmt.Printf("Gauss-Newton: theta = %.5v, L2 = %.6f\n", thetaGN, fL2.Value(fn.Bind(thetaGN))) @@ -554,7 +542,7 @@ func main() { thetaGD := (GradDescent{Iters: 2000, LR: 0.05}).Minimize(fL2, fn, initial, nil, nil) fmt.Printf("GradientDescent: theta = %.5v, L2 = %.6f\n", thetaGD, fL2.Value(fn.Bind(thetaGD))) - // 3) Отжиг (универсальный) + // 3) Отжиг thetaSA := (Annealing{Iter: 20000, T0: 1.0, Step: 0.2}).Minimize(fL2, fn, initial, nil, nil) fmt.Printf("Annealing: theta = %.5v, L2 = %.6f\n", thetaSA, fL2.Value(fn.Bind(thetaSA))) From c6f7c6d997fd0079ee8a6f1b58b2466694c6f204 Mon Sep 17 00:00:00 2001 From: Vladislav Sarychev Date: Wed, 26 Nov 2025 21:18:36 +0700 Subject: [PATCH 3/3] first trie v3 --- main.go | 106 ++++++++++++++++++++++++++++---------------------------- 1 file changed, 53 insertions(+), 53 deletions(-) diff --git a/main.go b/main.go index 56274fa..60584c2 100644 --- a/main.go +++ b/main.go @@ -10,35 +10,35 @@ import ( /********** БАЗОВЫЕ ТИПЫ **********/ -type Vector []float64 +type IVector []float64 type Matrix [][]float64 -func (v Vector) Copy() Vector { c := make(Vector, len(v)); copy(c, v); return c } -func Zeros(n int) Vector { return make(Vector, n) } -func (v Vector) Add(u Vector) { +func (v IVector) Copy() IVector { c := make(IVector, len(v)); copy(c, v); return c } +func Zeros(n int) IVector { return make(IVector, n) } +func (v IVector) Add(u IVector) { for i := range v { v[i] += u[i] } } -func (v Vector) Sub(u Vector) { +func (v IVector) Sub(u IVector) { for i := range v { v[i] -= u[i] } } -func (v Vector) Scale(a float64) { +func (v IVector) Scale(a float64) { for i := range v { v[i] *= a } } -func Dot(a, b Vector) float64 { +func Dot(a, b IVector) float64 { s := 0.0 for i := range a { s += a[i] * b[i] } return s } -func MatVec(m Matrix, x Vector) Vector { - y := make(Vector, len(m)) +func MatVec(m Matrix, x IVector) IVector { + y := make(IVector, len(m)) for i := range m { s := 0.0 for j := range m[i] { @@ -76,7 +76,7 @@ func Transpose(a Matrix) Matrix { } // Решение A x = b -func Solve(A Matrix, b Vector) (Vector, error) { +func Solve(A Matrix, b IVector) (IVector, error) { n := len(A) M := make(Matrix, n) for i := range M { @@ -114,7 +114,7 @@ func Solve(A Matrix, b Vector) (Vector, error) { } } } - x := make(Vector, n) + x := make(IVector, n) for i := 0; i < n; i++ { x[i] = M[i][n] } @@ -125,14 +125,14 @@ func Solve(A Matrix, b Vector) (Vector, error) { // Functions type IParametricFunction interface { - Bind(params Vector) IFunction + Bind(params IVector) IFunction } type IFunction interface { - Value(x Vector) float64 + Value(x IVector) float64 } type IDifferentiableFunction interface { IFunction - Gradient(x Vector) Vector + Gradient(x IVector) IVector } // Functionals @@ -141,17 +141,17 @@ type IFunctional interface { } type DifferentiableFunctional interface { IFunctional - Gradient(f IDifferentiableFunction) Vector + Gradient(f IDifferentiableFunction) IVector } type ILeastSquaresFunctional interface { IFunctional - Residual(f IFunction) Vector + Residual(f IFunction) IVector Jacobian(f IDifferentiableFunction) Matrix } // Оптимизатор type IOptimizator interface { - Minimize(obj IFunctional, fn IParametricFunction, initial Vector, min, max Vector) Vector + Minimize(obj IFunctional, fn IParametricFunction, initial IVector, min, max IVector) IVector } /********** ФУНКЦИИ **********/ @@ -160,15 +160,15 @@ type IOptimizator interface { type LinearN struct { n int } -type boundLinear struct{ theta Vector } // [w..., b] -func (p LinearN) Bind(params Vector) IFunction { return &boundLinear{theta: params.Copy()} } -func (b *boundLinear) Value(x Vector) float64 { +type boundLinear struct{ theta IVector } // [w..., b] +func (p LinearN) Bind(params IVector) IFunction { return &boundLinear{theta: params.Copy()} } +func (b *boundLinear) Value(x IVector) float64 { w := b.theta[:len(b.theta)-1] bias := b.theta[len(b.theta)-1] return Dot(w, x) + bias } -func (b *boundLinear) Gradient(x Vector) Vector { - g := make(Vector, len(b.theta)) +func (b *boundLinear) Gradient(x IVector) IVector { + g := make(IVector, len(b.theta)) copy(g, x) g[len(g)-1] = 1.0 // ∂f/∂b return g @@ -178,9 +178,9 @@ func (b *boundLinear) Gradient(x Vector) Vector { type Poly1D struct { deg int } -type boundPoly struct{ a Vector } // a0..an -func (p Poly1D) Bind(params Vector) IFunction { return &boundPoly{a: params.Copy()} } -func (b *boundPoly) Value(x Vector) float64 { +type boundPoly struct{ a IVector } // a0..an +func (p Poly1D) Bind(params IVector) IFunction { return &boundPoly{a: params.Copy()} } +func (b *boundPoly) Value(x IVector) float64 { x1 := x[0] pwr := 1.0 s := 0.0 @@ -193,18 +193,18 @@ func (b *boundPoly) Value(x Vector) float64 { // 3) Кусочно-линейная функция type PiecewiseLinear1D struct { - knots Vector // фиксированные x-узлы + knots IVector // фиксированные x-узлы } type boundPWL struct { - knots Vector - y Vector // параметры (значения в узлах) + knots IVector + y IVector // параметры (значения в узлах) } -func (p PiecewiseLinear1D) Bind(params Vector) IFunction { +func (p PiecewiseLinear1D) Bind(params IVector) IFunction { // предполагаем, что len(params)==len(knots) return &boundPWL{knots: p.knots, y: params.Copy()} } -func (b *boundPWL) Value(x Vector) float64 { +func (b *boundPWL) Value(x IVector) float64 { xv := x[0] // найдём отрезок [xi, xi+1] i := 0 @@ -215,7 +215,7 @@ func (b *boundPWL) Value(x Vector) float64 { t := (xv - x0) / (x1 - x0) return (1-t)*b.y[i] + t*b.y[i+1] } -func (b *boundPWL) Gradient(x Vector) Vector { +func (b *boundPWL) Gradient(x IVector) IVector { xv := x[0] i := 0 for i < len(b.knots)-2 && xv > b.knots[i+1] { @@ -223,7 +223,7 @@ func (b *boundPWL) Gradient(x Vector) Vector { } x0, x1 := b.knots[i], b.knots[i+1] t := (xv - x0) / (x1 - x0) - g := make(Vector, len(b.y)) + g := make(IVector, len(b.y)) g[i] = 1 - t g[i+1] = t return g @@ -231,12 +231,12 @@ func (b *boundPWL) Gradient(x Vector) Vector { // 4) Кубический сплайн type CubicSpline1D struct { - knots Vector // x + knots IVector coef Matrix } type boundSpline struct{ sp CubicSpline1D } -func (s CubicSpline1D) Bind(params Vector) IFunction { +func (s CubicSpline1D) Bind(params IVector) IFunction { n := len(s.knots) y := params.Copy() coef := make(Matrix, n-1) @@ -246,13 +246,13 @@ func (s CubicSpline1D) Bind(params Vector) IFunction { c1 := (y[i+1] - y[i]) / h c2 := 0.0 c3 := 0.0 - coef[i] = Vector{c0, c1, c2, c3} + coef[i] = IVector{c0, c1, c2, c3} } cp := s cp.coef = coef return &boundSpline{sp: cp} } -func (b *boundSpline) Value(x Vector) float64 { +func (b *boundSpline) Value(x IVector) float64 { xv := x[0] i := 0 for i < len(b.sp.knots)-2 && xv > b.sp.knots[i+1] { @@ -267,8 +267,8 @@ func (b *boundSpline) Value(x Vector) float64 { // Набор точек (x_i, y_i) type Samples struct { - X []Vector - Y Vector + X []IVector + Y IVector } // L1 @@ -282,7 +282,7 @@ func (f L1Functional) Value(fn IFunction) float64 { } return s } -func (f L1Functional) Gradient(fn IDifferentiableFunction) Vector { +func (f L1Functional) Gradient(fn IDifferentiableFunction) IVector { g := fn.Gradient(f.Data.X[0]) grad := Zeros(len(g)) for i := range f.Data.X { @@ -312,7 +312,7 @@ func (f L2Functional) Value(fn IFunction) float64 { } return s } -func (f L2Functional) Gradient(fn IDifferentiableFunction) Vector { +func (f L2Functional) Gradient(fn IDifferentiableFunction) IVector { grad := Zeros(len(fn.Gradient(f.Data.X[0]))) for i := range f.Data.X { r := fn.Value(f.Data.X[i]) - f.Data.Y[i] @@ -323,8 +323,8 @@ func (f L2Functional) Gradient(fn IDifferentiableFunction) Vector { } return grad } -func (f L2Functional) Residual(fn IFunction) Vector { - r := make(Vector, len(f.Data.X)) +func (f L2Functional) Residual(fn IFunction) IVector { + r := make(IVector, len(f.Data.X)) for i := range f.Data.X { r[i] = fn.Value(f.Data.X[i]) - f.Data.Y[i] } @@ -375,7 +375,7 @@ func (f IntegralFunctional) Value(fn IFunction) float64 { if i == 0 || i == f.N { w = 0.5 } - sum += w * fn.Value(Vector{x}) + sum += w * fn.Value(IVector{x}) } return sum * h } @@ -389,7 +389,7 @@ type Annealing struct { Step float64 } -func (a Annealing) Minimize(obj IFunctional, pf IParametricFunction, initial Vector, min, max Vector) Vector { +func (a Annealing) Minimize(obj IFunctional, pf IParametricFunction, initial IVector, min, max IVector) IVector { rng := rand.New(rand.NewSource(time.Now().UnixNano())) theta := initial.Copy() best := theta.Copy() @@ -441,7 +441,7 @@ type GradDescent struct { LR float64 } -func (gd GradDescent) Minimize(obj IFunctional, pf IParametricFunction, initial Vector, min, max Vector) Vector { +func (gd GradDescent) Minimize(obj IFunctional, pf IParametricFunction, initial IVector, min, max IVector) IVector { df, ok := obj.(DifferentiableFunctional) if !ok { panic("GradDescent requires DifferentiableFunctional") @@ -478,7 +478,7 @@ type GaussNewton struct { Iters int } -func (gn GaussNewton) Minimize(obj IFunctional, pf IParametricFunction, initial Vector, min, max Vector) Vector { +func (gn GaussNewton) Minimize(obj IFunctional, pf IParametricFunction, initial IVector, min, max IVector) IVector { ls, ok := obj.(ILeastSquaresFunctional) if !ok { panic("Gauss-Newton requires ILeastSquaresFunctional") @@ -524,16 +524,16 @@ func (gn GaussNewton) Minimize(obj IFunctional, pf IParametricFunction, initial func main() { data := Samples{ - X: []Vector{ + X: []IVector{ {0, 0}, {1, 0}, {0, 1}, {2, -1}, {3, 2}, }, - Y: Vector{1, 3, 0.5, 2*2 - 0.5*(-1) + 1, 2*3 - 0.5*2 + 1}, + Y: IVector{1, 3, 0.5, 2*2 - 0.5*(-1) + 1, 2*3 - 0.5*2 + 1}, } fn := LinearN{n: 2} fL2 := L2Functional{Data: data} - initial := Vector{0, 0, 0} + initial := IVector{0, 0, 0} // 1) Гаусса-Ньютона thetaGN := (GaussNewton{Iters: 20}).Minimize(fL2, fn, initial, nil, nil) fmt.Printf("Gauss-Newton: theta = %.5v, L2 = %.6f\n", thetaGN, fL2.Value(fn.Bind(thetaGN))) @@ -547,14 +547,14 @@ func main() { fmt.Printf("Annealing: theta = %.5v, L2 = %.6f\n", thetaSA, fL2.Value(fn.Bind(thetaSA))) // Пример кусочно-линейной аппроксимации 1D - knots := Vector{-1, 0, 1, 2} + knots := IVector{-1, 0, 1, 2} pwl := PiecewiseLinear1D{knots: knots} s1 := Samples{ - X: []Vector{{-1}, {0}, {0.5}, {1.7}}, - Y: Vector{-1, 0, 1, 2}, + X: []IVector{{-1}, {0}, {0.5}, {1.7}}, + Y: IVector{-1, 0, 1, 2}, } l1 := L1Functional{Data: s1} - theta0 := Vector{0, 0, 0, 0} + theta0 := IVector{0, 0, 0, 0} thetaPWL := (GradDescent{Iters: 1000, LR: 0.1}).Minimize(l1, pwl, theta0, nil, nil) fmt.Printf("PWL L1 fit: y(knots)=%.3v, L1=%.6f\n", thetaPWL, l1.Value(pwl.Bind(thetaPWL))) }