It is an important stage to learn new knowledge. Previously, the optimization algorithm was implemented using Python and JavaScript, And now implemented using golang. The syntax is slightly uncomfortable, and some C language thinking is back.
-Golang uses a package to organize code. The identifiers of different files in the same package are shared and cannot contain two functions with the same name. Only package main can contain the main function. Therefore, the common functions are extracted and placed in package common. At the same time, each example program is moved to the examples directory.
-Cleveralgorithms is a random optimization algorithm. The most common function is the random number or vector generation function. Because fixed seed is used by default, you need to set it as the seed of the running time.
-In the absence of flexible dict types, you need to define a struct combination type to meet the needs of storing different types of values in array units.
package commonimport ("math/rand""time")// InitSeed set random seed with current time valuefunc InitSeed() {rand.Seed(time.Now().UnixNano())}// RandomVector generates a random vector from min_max bound.// It returns the generated random vector.func RandomVector(min_max [][2]float64) []float64 {var v = make([]float64, len(min_max))for i, mm := range min_max {v[i] = mm[0] + (mm[1]-mm[0])*rand.Float64()}return v}// RandomBound generates a random value from the bound.// It returns the random value.func RandomBound(bound [2]float64) float64 {return bound[0] + (bound[1]-bound[0])*rand.Float64()}// FRange simulates range in python for float64.// It yields values in the range.func FRange(start float64, stop float64, step float64) (c chan float64) {c = make(chan float64)go func() {for x := start; x<stop;x += step {c <- x}close(c)}()return}// Entity stores cost and vector.type Entity struct {Cost float64Vector []float64}
Then, the random search code becomes:
//// Random Search//package stochasticimport ("clever_algorithms/common""fmt")func objective_function(v []float64) float64 {return common.SphereFunction(v)}func RandomSearch(search_space [][2]float64, max_iteration int) common.Entity {var best common.Entitycommon.InitSeed()for i := 0; i < max_iteration; i++ {candidate := common.Entity{0.0,common.RandomVector(search_space),}candidate.Cost = objective_function(candidate.Vector)if best.Vector == nil || best.Cost > candidate.Cost {best = candidate}fmt.Println("Iteration ", i+1, ", best=", best.Cost)}return best}
Add a simple unit test:
package stochasticimport ("fmt""testing")func TestObjectiveFunction(t *testing.T) {if 5 != objective_function([]float64{1, 2}) {t.Error("Objetive function failed")}}func TestSearch(t *testing.T) {//var problem_size = 2var search_space = make([][2]float64, problem_size)for i, _ := range search_space {search_space[i] = [2]float64{-5, 5}}//const max_iteration = 100//var best = RandomSearch(search_space, max_iteration)if best.Vector == nil {t.Error("Search result should not be nil.")}fmt.Println("Done. Best Solution: c=", best.Cost, ", v= [")for i, v := range best.Vector {fmt.Print(" ", v)if v < search_space[i][0] || v > search_space[i][1] {t.Error("vector values should be in the search space.")}}fmt.Println("]")}
[1] https://coding.net/u/huys03/p/clever_algorithms_go/git
Use golang to write optimization algorithms (1)