textdatareader.go 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204
  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 training
  26. import (
  27. "bufio"
  28. "fmt"
  29. "log"
  30. "math/rand"
  31. "os"
  32. "strconv"
  33. "strings"
  34. "sync"
  35. "time"
  36. mat "gonum.org/v1/gonum/mat"
  37. )
  38. type TextDataReader struct {
  39. dataSet []*mat.Dense
  40. result []*mat.Dense
  41. index int
  42. validationIndex int
  43. validationCount int
  44. mutex *sync.Mutex
  45. }
  46. func NewTextDataReader(filename string, validationPart int) *TextDataReader {
  47. r := &TextDataReader{
  48. index: 0,
  49. validationIndex: 0,
  50. mutex: &sync.Mutex{},
  51. }
  52. r.readData(filename)
  53. r.validationCount = len(r.dataSet) / validationPart
  54. r.validationIndex = len(r.dataSet) - r.validationCount
  55. return r
  56. }
  57. func (r *TextDataReader) readData(filename string) {
  58. inputFile, err := os.Open(filename)
  59. if err != nil {
  60. log.Fatal(err)
  61. }
  62. defer inputFile.Close()
  63. scanner := bufio.NewScanner(inputFile)
  64. scanner.Split(bufio.ScanLines)
  65. var results []string
  66. var uniqueResults []string
  67. var max []float64
  68. for scanner.Scan() {
  69. dataLine := scanner.Text()
  70. data := strings.Split(dataLine, ",")
  71. dataSetSize := len(data) - 1
  72. if len(max) <= 0 {
  73. max = make([]float64, dataSetSize)
  74. }
  75. if dataSetSize != len(max) {
  76. fmt.Printf("Garbage record: %s\n", dataLine)
  77. continue
  78. }
  79. var dataRaw []float64
  80. for i := 0; i < dataSetSize; i++ {
  81. val, err := strconv.ParseFloat(data[i], 64)
  82. if err != nil {
  83. break
  84. }
  85. dataRaw = append(dataRaw, val)
  86. if max[i] < val {
  87. max[i] = val
  88. }
  89. }
  90. if len(dataRaw) < dataSetSize {
  91. fmt.Printf("Garbage record: %s\n", dataLine)
  92. continue
  93. }
  94. r.dataSet = append(r.dataSet, mat.NewDense(dataSetSize, 1, dataRaw))
  95. found := false
  96. for _, uniqueResult := range uniqueResults {
  97. if uniqueResult == data[dataSetSize] {
  98. found = true
  99. break
  100. }
  101. }
  102. if !found {
  103. uniqueResults = append(uniqueResults, data[dataSetSize])
  104. }
  105. results = append(results, data[dataSetSize])
  106. }
  107. for i, result := range results {
  108. k := 0
  109. for k, _ = range uniqueResults {
  110. if uniqueResults[k] == result {
  111. break
  112. }
  113. }
  114. r.result = append(r.result, mat.NewDense(len(uniqueResults), 1, nil))
  115. r.result[i].Set(k, 0, 1.0)
  116. }
  117. //normalize
  118. for i := 0; i < len(r.dataSet); i++ {
  119. r.dataSet[i].Apply(func(r, _ int, val float64) float64 {
  120. return val / max[r]
  121. }, r.dataSet[i])
  122. }
  123. rand.Seed(time.Now().UnixNano())
  124. for k := 0; k < 25; k++ {
  125. rand.Shuffle(len(r.dataSet), func(i, j int) {
  126. r.result[i], r.result[j] = r.result[j], r.result[i]
  127. r.dataSet[i], r.dataSet[j] = r.dataSet[j], r.dataSet[i]
  128. })
  129. }
  130. }
  131. func (r *TextDataReader) GetData() (*mat.Dense, *mat.Dense) {
  132. // r.mutex.Lock()
  133. // defer r.mutex.Unlock()
  134. return r.dataSet[r.index], r.result[r.index]
  135. }
  136. func (r *TextDataReader) NextData() bool {
  137. // r.mutex.Lock()
  138. // defer r.mutex.Unlock()
  139. if (r.index + 1) >= len(r.result)-r.validationCount {
  140. r.index = 0
  141. return false
  142. }
  143. r.index++
  144. return true
  145. }
  146. func (r *TextDataReader) GetValidator() (*mat.Dense, *mat.Dense) {
  147. return r.dataSet[r.validationIndex], r.result[r.validationIndex]
  148. }
  149. func (r *TextDataReader) NextValidator() bool {
  150. if (r.validationIndex + 1) >= len(r.dataSet) {
  151. r.validationIndex = len(r.dataSet) - r.validationCount
  152. return false
  153. }
  154. r.validationIndex++
  155. return true
  156. }
  157. func (r *TextDataReader) Reset() {
  158. r.index = 0
  159. r.validationIndex = len(r.dataSet) - r.validationCount
  160. }
  161. func (r *TextDataReader) Index() int {
  162. return r.index
  163. }
  164. func (r *TextDataReader) ValidationIndex() int {
  165. return r.validationIndex
  166. }
  167. func (r *TextDataReader) GetDataByIndex(i int) (*mat.Dense, *mat.Dense) {
  168. if i >= len(r.result)-r.validationCount {
  169. return nil, nil
  170. }
  171. return r.dataSet[i], r.result[i]
  172. }
  173. func (r *TextDataReader) GetDataCount() int {
  174. return len(r.dataSet) - r.validationCount
  175. }