Машинное обучение Golang
CalculatingВычисление simpleпростых statisticalстатических propertiesсвойств
StatisticalСтатистическое learningобучение isэто aветвь branchприменения ofстатистики appliedкоторая statisticsсвязана thatс isмашинным related to machine learning.обучением.
MachineМашинное learning,обучение, whichкоторое isтесно closelyсвязано relatedс toвычислительной computationalстатистикой, statistics,это isчасть anинформатики areaкоторая ofпробует computerизучить scienceданные thatи triesна toих learnоснове fromделать dataпредсказания andо makeих predictionsповедении aboutбез itспециального without being specifically programmed to do so.программирования.
InВ thisэтой article,статье, youмы areсобираемся goingизучить toкак learnсосчитать howбазовые toстатистические calculateсвойства, basicтакие statisticalкак propertiesсреднее suchзначение, asминимальное theи meanмаксимальное value,значение theпримера, minimumмедианное andзначение, theа maximumтакже valuesдисперсию ofпримера. yourЭти sample,значения theдадут medianвам value,отличное andпонимание theвашего varianceпримера ofбез theсреёзного sample.погружения Theseв valuesдетали. giveОднако, youобщие aзначения goodкоторые overviewописывает ofпример, yourмогут sampleлегко withoutобмануть goingвас, intoзаставив tooвас muchповерить, detail.что However,вы genericхорошо valuesзнаете thatпример, tryи toбез describe your sample can easily trick you by making you believe that you know your sample well without this being true.них.
AllВсе theseэти statisticalстатистические propertiesсвойства, willбудут beпосчитаны computedв in stats.go
, whichкоторый willбудет beпредставлен presentedв inпяти fiveчастях.
parts.Каждая Eachстрока lineвходного ofфайла theсодержит inputодно fileчисло, containsкоторое aзначит, singleчто number,входной whichфайл meansчитается thatпострочно. theНеправильный inputввод fileбудет isпроигнорирован readбез lineкаких byлибо line.предупредительных Invalid input will be ignored without any warning messages.сообщений.
Notice
Ввод thatбудет inputсохранен willв beсрезе, storedчтобы inможно aбыло sliceиспользовать inотдельную orderфункцию toдля useподсчета aкаждого separateсвойства. functionТак forже, calculatingувидим, eachзначения property.среза Also,будут asотсортированны youперед willобработкой.
see shortly, the values of the slice will be sorted before processing them.
package main
import (
"bufio"
"flag"
"fmt"
"io"
"math"
"os"
"sort"
"strconv"
"strings"
)
func min(x []float64) float64 {
return x[0]
}
func max(x []float64) float64 {
return x[len(x)-1]
}
func meanValue(x []float64) float64 {
sum := float64(0)
for _, v := range x {
sum = sum + v
}
return sum / float64(len(x))
}
func medianValue(x []float64) float64 {
length := len(x)
if length%2 == 1 {
// Odd
return x[(length-1)/2]
} else {
// Even
return (x[length/2] + x[(length/2)-1]) / 2
}
return 0
}
func variance(x []float64) float64 {
mean := meanValue(x)
sum := float64(0)
for _, v := range x {
sum = sum + (v-mean)*(v-mean)
}
return sum / float64(len(x))
}
func main() {
flag.Parse()
if len(flag.Args()) == 0 {
fmt.Printf("usage: stats filename\n")
return
}
data := make([]float64, 0)
file := flag.Args()[0]
f, err := os.Open(file)
if err != nil {
fmt.Println(err)
return
}
defer f.Close()
RegressionРегрессия
RegressionРегрессия isэто aстатистический statisticalметод methodдля forрасчета calculatingсвязи relationshipsмежду amongпеременными. variables.Эта Thisчасть sectionреализует willлинейную implementрегрессию, linearкоторая regression,наиболее whichпопуляная isи theнаиболее mostпростая popularтехника, andа simplestтак regressionже techniqueнаилучший andспособ aпонять veryнаши goodданные. wayЗаметим, toчто understandрегрессия yourне data. Note that regression techniques are notимеет 100% accurate,точность, evenдаже ifесли youвы useиспользвали higher-orderмногочлен высшего порядка(nonlinear)нелинейный). polynomials.Цель Theрегрессия, keyкак withи regression,в asбольшинстве withML mostтехник machine- learningнайти techniques,достаточно isхорошую toтехнику findа aне goodлучшую enoughиз technique and not the perfect technique and model.лучших.
LinearЛинейная regressionрегрессия.
TheЗа ideaэтой behindрегрессией linearпрячется regressionследующее: isвы simple:берете youмодель areваших tryingданных toиспользуя modelуравнение yourпервой dataстепени. usingего aможно first-degreeпредставить equation.как A first-degree equation can be represented as y = a x + b
.
ThereЕсть areмножество manyметодов, methodsкоторые thatпозволяют allowнайти youуравнение toпервого findпорядка, outкоторое thatпредставит first-degreeмодель equationваших thatданных willи modelвычислит youra
dataи – all techniques calculate a and b
.
ImplementingРеализация linearлинейной regression
Theрегрессии.
Go codeкод, ofэтой thisчасти sectionбудет willсохранен beв saved in regression.go
, whichкоторый isбудет goingпредставлен toв beтрех presentedчастях. inВывод threeпрограммы parts.будет Theдва outputчисла ofс theплавающей programзапятой, willкоторые beопределяют twoa
floating-pointи numbersb
thatдля defineураввнения aпервого and b in the first-degree equation.порядка.
TheПервая firstчасть part of regression.go
containsсодержит theследующий following code:код:
package main
import (
"encoding/csv"
"flag"
"fmt"
"gonum.org/v1/gonum/stat"
"os"
"strconv"
)
type xy struct {
x []float64
y []float64
}
func main() {
flag.Parse()
if len(flag.Args()) == 0 {
fmt.Printf("usage: regression filename\n")
return
}
filename := flag.Args()[0]
file, err := os.Open(filename)
if err != nil {
fmt.Println(err)
return
}
defer file.Close()
r := csv.NewReader(file)
records, err := r.ReadAll()
if err != nil {
fmt.Println(err)
return
}
size := len(records)
data := xy{
x: make([]float64, size),
y: make([]float64, size),
}
for i, v := range records {
if len(v) != 2 {
fmt.Println("Expected two elements")
continue
}
if s, err := strconv.ParseFloat(v[0], 64); err == nil {
data.y[i] = s
}
if s, err := strconv.ParseFloat(v[1], 64); err == nil {
data.x[i] = s
}
}
b, a := stat.LinearRegression(data.x, data.y, nil, false)
fmt.Printf("%.4v x + %.4v\n", a, b)
fmt.Printf("a = %.4v b = %.4v\n", a, b)
}
ClassificationКлассификация
InВ statisticsстатистике andи machineML, learning,классификация classificationэто isпроцесс theпомещения processэлементов ofв puttingсуществующие elementsнаборы intoкоторые existingназываются setsкатегориями. thatВ areML calledклассификация categories.подразумевает Inобучение machineс learning,учителем, classificationв isкотором consideredнабор aпредполагает supervisedсодержание learningверно technique,определенные whichданные isиспользуемые whereдля aобучение setперед thatработой isс consideredреальными to contain correctly identified observations is used for training before working with the actual data.данными.
AОчень veryпростой popularи andлегко easy-to-implementреализуемая classificationметод methodклассификации isназывается called"k-близжайших k-nearest neighbors соседей"(k-NN). TheИдея ideaметода behindтакова, что мы можем отсортировать данные основываясь на их схожести с другими предметами. "k" в "k-NNNN" isобозначает thatчисло weсоседей canкоторые classifyдолжны dataбыть itemsвключены basedв onрешение, theirкоторое similarityзначит with other items. Theчто k inэто k-NNположительное denotesцелое. theкоторое numberдовольно of neighbors that are going to be included in the decision, which means that k is a positive integer that is usually pretty small.маленькое.
The input of the algorithm consists of the k-closest training examples in the feature space. An object is classified by a plurality vote of its neighbors, with the object being assigned to the class that is the most common among its k-NN. If the value of k is 1 , then the element is simply assigned to the class that is the nearest neighbor according to the distance metric used. The distance metric depends on the data you are dealing with. As an example, you will need a different distance metric when working with complex numbers and another when working with points in three-dimensional space.
package main
import (
"flag"
"fmt"
"strconv"
"github.com/sjwhitworth/golearn/base"
"github.com/sjwhitworth/golearn/evaluation"
"github.com/sjwhitworth/golearn/knn"
)
func main() {
flag.Parse()
if len(flag.Args()) < 2 {
fmt.Printf("usage: classify filename k\n")
return
}
dataset := flag.Args()[0]
rawData, err := base.ParseCSVToInstances(dataset, false)
if err != nil {
fmt.Println(err)
return
}
k, err := strconv.Atoi(flag.Args()[1])
if err != nil {
fmt.Println(err)
return
}
cls := knn.NewKnnClassifier("euclidean", "linear", k)
The knn.NewKnnClassifier() method returns a new classifier. The last parameter of the function is the number of neighbors that the classifier will have.
The final part of classify.go is as follows:
train, test := base.InstancesTrainTestSplit(rawData, 0.50)
cls.Fit(train)
p, err := cls.Predict(test)
if err != nil {
fmt.Println(err)
return
}
confusionMat, err := evaluation.GetConfusionMatrix(test, p)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(evaluation.GetSummary(confusionMat))
Working with tensorflow
TensorFlow is a rather famous open-source platform for machine learning. In order to use TensorFlow with Go, you will first need to download a Go package:
$ go get github.com/tensorflow/tensorflow/tensorflow/go
However, for the aforementioned command to work, the C interface for TensorFlow should be already installed. On a macOS Mojave machine, this can be installed as follows:
$ brew install tensorflow
If the C interface is not installed, and you try to install the Go package for TensorFlow, you will get the following error message:
$ go get github.com/tensorflow/tensorflow/tensorflow/go
# github.com/tensorflow/tensorflow/tensorflow/go
ld: library not found for -ltensorflow clang: error: linker command failed with exit code 1 (use -v to see invocation) As TensorFlow is pretty complex, it would be good to execute the following command in order to validate your installation:
$ go test github.com/tensorflow/tensorflow/tensorflow/go
ok github.com/tensorflow/tensorflow/tensorflow/go 0.109s
Now let's begin with some code:
package main
import (
tf "github.com/tensorflow/tensorflow/tensorflow/go"
"github.com/tensorflow/tensorflow/tensorflow/go/op"
"fmt"
)
func main() {
s := op.NewScope()
c := op.Const(s, "Using TensorFlow version: " + tf.Version())
graph, err := s.Finalize()
if err != nil {
fmt.Println(err)
return
}
sess, err := tf.NewSession(graph, nil)
if err != nil {
fmt.Println(err)
return
}
output, err := sess.Run(nil, []tf.Output{c}, nil)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(output[0].Value())
}