handwriting.go 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164
  1. /*
  2. * MIT License
  3. *
  4. * Copyright (c) 2019 Alexey Edelev <semlanik@gmail.com>
  5. *
  6. * This file is part of NeuralNetwork project https://git.semlanik.org/semlanik/NeuralNetwork
  7. *
  8. * Permission is hereby granted, free of charge, to any person obtaining a copy of this
  9. * software and associated documentation files (the "Software"), to deal in the Software
  10. * without restriction, including without limitation the rights to use, copy, modify,
  11. * merge, publish, distribute, sublicense, and/or sell copies of the Software, and
  12. * to permit persons to whom the Software is furnished to do so, subject to the following
  13. * conditions:
  14. *
  15. * The above copyright notice and this permission notice shall be included in all copies
  16. * or substantial portions of the Software.
  17. *
  18. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
  19. * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
  20. * PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
  21. * FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  22. * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  23. * DEALINGS IN THE SOFTWARE.
  24. */
  25. package handwriting
  26. import (
  27. "bytes"
  28. context "context"
  29. fmt "fmt"
  30. "net"
  31. earlystop "git.semlanik.org/semlanik/NeuralNetwork/earlystop"
  32. neuralnetwork "git.semlanik.org/semlanik/NeuralNetwork/neuralnetwork"
  33. gradients "git.semlanik.org/semlanik/NeuralNetwork/neuralnetwork/gradients"
  34. training "git.semlanik.org/semlanik/NeuralNetwork/training"
  35. mat "gonum.org/v1/gonum/mat"
  36. grpc "google.golang.org/grpc"
  37. )
  38. type HandwritingService struct {
  39. nn *neuralnetwork.NeuralNetwork
  40. }
  41. func NewHandwritingService() (hws *HandwritingService) {
  42. hws = &HandwritingService{}
  43. hws.nn, _ = neuralnetwork.NewNeuralNetwork([]int{784, 300, 10}, gradients.NewRPropInitializer(gradients.RPropConfig{
  44. NuPlus: 1.2,
  45. NuMinus: 0.5,
  46. DeltaMax: 50.0,
  47. DeltaMin: 0.000001,
  48. }))
  49. hws.nn.SetStateWatcher(hws)
  50. return
  51. }
  52. func (hws *HandwritingService) Recognize(ctx context.Context, matrix *Matrix) (*Result, error) {
  53. fmt.Printf("Recognize %v size: %v\n", len(matrix.Data), hws.nn.Sizes[0])
  54. dense := mat.NewDense(hws.nn.Sizes[0], 1, matrix.Data)
  55. index, _ := hws.nn.Predict(dense)
  56. fmt.Printf("Recognition result %v\n", index)
  57. return &Result{ResultCharacter: uint32(index)}, nil
  58. }
  59. func (hws *HandwritingService) SetNeuralNetworkData(ctx context.Context, nnRaw *NeuralNetworkRaw) (*None, error) {
  60. fmt.Println("SetNeuralNetworkData")
  61. r := bytes.NewReader(nnRaw.Data)
  62. hws.nn.LoadState(r)
  63. return &None{}, nil
  64. }
  65. func (hws *HandwritingService) GetNeuralNetworkData(context.Context, *None) (*NeuralNetworkRaw, error) {
  66. nnRaw := &NeuralNetworkRaw{}
  67. fmt.Println("SetNeuralNetworkData")
  68. r := bytes.NewReader(nnRaw.Data)
  69. hws.nn.LoadState(r)
  70. return nnRaw, nil
  71. }
  72. func (hws *HandwritingService) ReTrain(context.Context, *None) (*None, error) {
  73. fmt.Println("ReTrain")
  74. trainer := training.NewMNISTReader("./train-images-idx3-ubyte", "./train-labels-idx1-ubyte", "./t10k-images-idx3-ubyte", "./t10k-labels-idx1-ubyte")
  75. hws.nn.SetEarlyStop(earlystop.NewSimpleDescentEarlyStop(hws.nn, trainer))
  76. squareError, failCount, total := hws.nn.Validate(trainer)
  77. fmt.Printf("Fail count before: %v/%v, error: %v\n\n", failCount, total, squareError)
  78. hws.nn.Train(trainer, 100)
  79. hws.nn.SaveStateToFile("./mnistnet.nnd")
  80. squareError, failCount, total = hws.nn.Validate(trainer)
  81. fmt.Printf("Fail count after: %v/%v, error: %v\n\n", failCount, total, squareError)
  82. fmt.Println("ReTrain finished")
  83. return &None{}, nil
  84. }
  85. func (hws *HandwritingService) Run() {
  86. grpcServer := grpc.NewServer()
  87. RegisterHandwritingServer(grpcServer, hws)
  88. lis, err := net.Listen("tcp", "localhost:65001")
  89. if err != nil {
  90. fmt.Printf("Failed to listen: %v\n", err)
  91. }
  92. fmt.Printf("Listen localhost:65001\n")
  93. if err := grpcServer.Serve(lis); err != nil {
  94. fmt.Printf("Failed to serve: %v\n", err)
  95. }
  96. }
  97. func (hws *HandwritingService) Init(nn *neuralnetwork.NeuralNetwork) {
  98. }
  99. func (hws *HandwritingService) UpdateState(int) {
  100. }
  101. func (hws *HandwritingService) UpdateActivations(int, *mat.Dense) {
  102. }
  103. func (hws *HandwritingService) UpdateBiases(int, *mat.Dense) {
  104. }
  105. func (hws *HandwritingService) UpdateWeights(int, *mat.Dense) {
  106. }
  107. func (hws *HandwritingService) UpdateTraining(t int, epocs int, samplesProcced int, totalSamplesCount int) {
  108. fmt.Printf("Training progress: Epoc: %v/%v\n", t, epocs)
  109. }
  110. func (hws *HandwritingService) UpdateValidation(validatorCount int, failCount int) {
  111. }
  112. func (hws *HandwritingService) GetSubscriptionFeatures() (features neuralnetwork.SubscriptionFeatures) {
  113. features = 0
  114. features.Set(neuralnetwork.TrainingSubscription)
  115. features.Set(neuralnetwork.ValidationSubscription)
  116. return
  117. }
  118. func drawImage(dense *mat.Dense) {
  119. for i := 0; i < 28; i++ {
  120. for j := 0; j < 28; j++ {
  121. val := 0
  122. if dense.At(i*28+j, 0) > 0 {
  123. val = 1
  124. }
  125. fmt.Printf("%v ", val)
  126. }
  127. fmt.Println()
  128. }
  129. }