📜 ⬆️ ⬇️

Introduction to Neural Networks on Golang

Hello to Habrahabr readers! In this article I will show you an example of a simple neural network in the Golang language using a ready-made library.

Little preface


Having started learning the Golang programming language, I wondered what this language could do in machine learning. Then I began to look for some NA code examples in this language. Unfortunately, nothing sensible was found. And then I decided to rewrite the NA from this article under GO.

Neural network


The task of the neural network is to decide what the character should do, based on 3 parameters:


Depending on the outcome, one of the following decisions may be taken:
')

Examples:
HealthWeaponsThe enemiesDecision
50oneoneAttack
90one2Attack
800oneAttack
thirtyoneoneSteal
60one2Steal
400oneSteal
90one7Run away
60onefourRun away
ten0oneRun away
60one0Nothing to do
10000Nothing to do

Training


We will use the GoNN library.

Installation:

go get github.com/fxsjy/gonn/gonn 

Let's get started!


First, let's set the import:

 import ( "fmt" "github.com/fxsjy/gonn/gonn" ) 

Now let's start creating a neural network:

 func CreateNN() { //    3   (   ), // 16    // 4   (   ) nn := gonn.DefaultNetwork(3, 16, 4, false) //    : // 1  -   (0.1 - 1.0) // 2  -   (0 - , 1 - ) // 3  -   input := [][]float64 { []float64{0.5, 1, 1}, []float64{0.9, 1, 2}, []float64{0.8, 0, 1}, []float64{0.3, 1, 1}, []float64{0.6, 1, 2}, []float64{0.4, 0, 1}, []float64{0.9, 1, 7}, []float64{0.6, 1, 4}, []float64{0.1, 0, 1}, []float64{0.6, 1, 0}, []float64{1, 0, 0} } //   "" -  ,    target := [][]float64 { []float64{1, 0, 0, 0}, []float64{1, 0, 0, 0}, []float64{1, 0, 0, 0}, []float64{0, 1, 0, 0}, []float64{0, 1, 0, 0}, []float64{0, 1, 0, 0}, []float64{0, 0, 1, 0}, []float64{0, 0, 1, 0}, []float64{0, 0, 1, 0}, []float64{0, 0, 0, 1}, []float64{0, 0, 0, 1} } //    . //   - 100000 nn.Train(input, target, 100000) //     . gonn.DumpNN("gonn", nn) } 

Now we need to write a function that selects the answer of the neuron with the greatest weight.

 func GetResult(output []float64) string { max := -99999 pos := -1 //       . for i, value := range output { if (value > max) { max = value pos = i } } // ,    ,  . switch pos { case 0: return "" case 1: return "" case 2: return "" case 3: return "  " } return "" } 

And now we write the main function.

 func main() { CreateNN() //    . nn := gonn.LoadNN("gonn") //    : // hp -  (0.1 - 1.0) // weapon -   (0 - , 1 - ) // enemyCount -   var hp float64 = 0.7 var weapon float64 = 1.0 var enemyCount float64 = 1.0 //     ( ) out := nn.Forward([]float64{ hp, weapon, enemyCount }) //    . fmt.Println(GetResult(out)) } 

In this case, the answer is “Attack”

Conclusion


As you can see, the process of working with neural networks on Golang is the same as with other programming languages. Experiment with this network and create your own!

Source: https://habr.com/ru/post/343466/


All Articles