handwriting.go 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160
  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. neuralnetwork "git.semlanik.org/semlanik/NeuralNetwork/neuralnetwork"
  32. gradients "git.semlanik.org/semlanik/NeuralNetwork/neuralnetwork/gradients"
  33. training "git.semlanik.org/semlanik/NeuralNetwork/training"
  34. "gonum.org/v1/gonum/mat"
  35. grpc "google.golang.org/grpc"
  36. )
  37. type HandwritingService struct {
  38. nn *neuralnetwork.NeuralNetwork
  39. }
  40. func NewHandwritingService() (hws *HandwritingService) {
  41. hws = &HandwritingService{}
  42. hws.nn, _ = neuralnetwork.NewNeuralNetwork([]int{784, 300, 10}, gradients.NewRPropInitializer(gradients.RPropConfig{
  43. NuPlus: 1.2,
  44. NuMinus: 0.5,
  45. DeltaMax: 50.0,
  46. DeltaMin: 0.000001,
  47. }))
  48. hws.nn.SetStateWatcher(hws)
  49. return
  50. }
  51. func (hws *HandwritingService) Recognize(ctx context.Context, matrix *Matrix) (*Result, error) {
  52. fmt.Printf("Recognize %v size: %v\n", len(matrix.Data), hws.nn.Sizes[0])
  53. dense := mat.NewDense(hws.nn.Sizes[0], 1, matrix.Data)
  54. index, _ := hws.nn.Predict(dense)
  55. fmt.Printf("Recognition result %v\n", index)
  56. return &Result{ResultCharacter: uint32(index)}, nil
  57. }
  58. func (hws *HandwritingService) SetNeuralNetworkData(ctx context.Context, nnRaw *NeuralNetworkRaw) (*None, error) {
  59. fmt.Println("SetNeuralNetworkData")
  60. r := bytes.NewReader(nnRaw.Data)
  61. hws.nn.LoadState(r)
  62. return &None{}, nil
  63. }
  64. func (hws *HandwritingService) GetNeuralNetworkData(context.Context, *None) (*NeuralNetworkRaw, error) {
  65. nnRaw := &NeuralNetworkRaw{}
  66. fmt.Println("SetNeuralNetworkData")
  67. r := bytes.NewReader(nnRaw.Data)
  68. hws.nn.LoadState(r)
  69. return nnRaw, nil
  70. }
  71. func (hws *HandwritingService) ReTrain(context.Context, *None) (*None, error) {
  72. fmt.Println("ReTrain")
  73. trainer := training.NewMNISTReader("./train-images-idx3-ubyte", "./train-labels-idx1-ubyte", "./t10k-images-idx3-ubyte", "./t10k-labels-idx1-ubyte")
  74. failCount, total := hws.nn.Validate(trainer)
  75. fmt.Printf("Fail count before: %v/%v\n\n", failCount, total)
  76. hws.nn.Train(trainer, 100)
  77. hws.nn.SaveStateToFile("./mnistnet.nnd")
  78. failCount, total = hws.nn.Validate(trainer)
  79. fmt.Printf("Fail count after: %v/%v\n\n", failCount, total)
  80. fmt.Println("ReTrain finished")
  81. return &None{}, nil
  82. }
  83. func (hws *HandwritingService) Run() {
  84. grpcServer := grpc.NewServer()
  85. RegisterHandwritingServer(grpcServer, hws)
  86. lis, err := net.Listen("tcp", "localhost:65001")
  87. if err != nil {
  88. fmt.Printf("Failed to listen: %v\n", err)
  89. }
  90. fmt.Printf("Listen localhost:65001\n")
  91. if err := grpcServer.Serve(lis); err != nil {
  92. fmt.Printf("Failed to serve: %v\n", err)
  93. }
  94. }
  95. func (hws *HandwritingService) Init(nn *neuralnetwork.NeuralNetwork) {
  96. }
  97. func (hws *HandwritingService) UpdateState(int) {
  98. }
  99. func (hws *HandwritingService) UpdateActivations(int, *mat.Dense) {
  100. }
  101. func (hws *HandwritingService) UpdateBiases(int, *mat.Dense) {
  102. }
  103. func (hws *HandwritingService) UpdateWeights(int, *mat.Dense) {
  104. }
  105. func (hws *HandwritingService) UpdateTraining(t int, epocs int, samplesProcced int, totalSamplesCount int) {
  106. fmt.Printf("Training progress: Epoc: %v/%v\n", t, epocs)
  107. }
  108. func (hws *HandwritingService) UpdateValidation(validatorCount int, failCount int) {
  109. }
  110. func (hws *HandwritingService) GetSubscriptionFeatures() (features neuralnetwork.SubscriptionFeatures) {
  111. features = 0
  112. features.Set(neuralnetwork.TrainingSubscription)
  113. features.Set(neuralnetwork.ValidationSubscription)
  114. return
  115. }
  116. func drawImage(dense *mat.Dense) {
  117. for i := 0; i < 28; i++ {
  118. for j := 0; j < 28; j++ {
  119. val := 0
  120. if dense.At(i*28+j, 0) > 0 {
  121. val = 1
  122. }
  123. fmt.Printf("%v ", val)
  124. }
  125. fmt.Println()
  126. }
  127. }