使用Golang编写优化算法 (1)
动手写点东西是学习新知识很重要的一个阶段。之前用 Python 和 JavaScript 实现优化算法,现在用 Golang 来实现。语法上略有不爽,某些C语言的思维又回来了。
- Golang 用 package 来组织代码,同一 package 下不同文件之间的标识符是共享的,不能包含两个相同名称的函数。而且只有 package main 能够包含 main 函数。所以将公用的函数提取出来,放在package common。同时,每种例子程序移动到 examples 目录下。
- 在 CleverAlgorithms 中都是随机优化算法,最常用的是随机数或向量的生成函数。因为默认采用Fixed Seed,所以需要自行设置成运行时刻的纳秒值作为种子。
- 在缺乏灵活的dict类型之后,需要定义struct组合类型来满足数组单元中存储不同类型值的需求。
package common import ( "math/rand" "time" ) // InitSeed set random seed with current time value func 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 float64 Vector []float64 }
然后,随机搜索的代码变成:
// // Random Search // package stochastic import ( "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.Entity common.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 }
添加简单的单元测试:
package stochastic import ( "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 = 2 var 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