1
0
mirror of https://github.com/sjwhitworth/golearn.git synced 2025-04-28 13:48:56 +08:00
golearn/utilities/utilities.go

98 lines
1.7 KiB
Go
Raw Normal View History

// Package utilities implements a host of helpful miscellaneous functions to the library.
package utilities
import (
2014-04-30 08:57:13 +01:00
"fmt"
rand "math/rand"
"sort"
"strconv"
2014-05-03 23:08:43 +01:00
mat64 "github.com/gonum/matrix/mat64"
2014-04-30 08:57:13 +01:00
)
type sortedIntMap struct {
m map[int]float64
s []int
}
2014-04-30 08:57:13 +01:00
func (sm *sortedIntMap) Len() int {
return len(sm.m)
}
2014-04-30 08:57:13 +01:00
func (sm *sortedIntMap) Less(i, j int) bool {
return sm.m[sm.s[i]] < sm.m[sm.s[j]]
}
2014-04-30 08:57:13 +01:00
func (sm *sortedIntMap) Swap(i, j int) {
sm.s[i], sm.s[j] = sm.s[j], sm.s[i]
}
2014-04-30 08:57:13 +01:00
func SortIntMap(m map[int]float64) []int {
sm := new(sortedIntMap)
sm.m = m
sm.s = make([]int, len(m))
i := 0
for key, _ := range m {
sm.s[i] = key
i++
}
sort.Sort(sm)
return sm.s
}
type sortedStringMap struct {
m map[string]int
s []string
}
2014-04-30 08:57:13 +01:00
func (sm *sortedStringMap) Len() int {
return len(sm.m)
}
2014-04-30 08:57:13 +01:00
func (sm *sortedStringMap) Less(i, j int) bool {
return sm.m[sm.s[i]] < sm.m[sm.s[j]]
}
2014-04-30 08:57:13 +01:00
func (sm *sortedStringMap) Swap(i, j int) {
sm.s[i], sm.s[j] = sm.s[j], sm.s[i]
}
2014-04-30 08:57:13 +01:00
func SortStringMap(m map[string]int) []string {
sm := new(sortedStringMap)
sm.m = m
sm.s = make([]string, len(m))
i := 0
for key, _ := range m {
sm.s[i] = key
i++
}
sort.Sort(sm)
return sm.s
}
2014-01-05 00:23:31 +00:00
func RandomArray(n int, k int) []float64 {
ReturnedArray := make([]float64, n)
for i := 0; i < n; i++ {
2014-01-05 00:23:31 +00:00
ReturnedArray[i] = rand.Float64() * float64(rand.Intn(k))
}
return ReturnedArray
2014-01-05 00:23:31 +00:00
}
func ConvertLabelsToFloat(labels []string) []float64 {
floats := make([]float64, 0)
for _, elem := range labels {
converted, err := strconv.ParseFloat(elem, 64)
if err != nil {
fmt.Println(err)
}
floats = append(floats, converted)
}
return floats
2014-04-30 08:57:13 +01:00
}
2014-05-03 23:08:43 +01:00
func FloatsToMatrix(floats []float64) *mat64.Dense {
return mat64.NewDense(1, len(floats), floats)
}