Class: NN

Inherits:
Object
  • Object
show all
Includes:
Numo
Defined in:
lib/nn.rb

Defined Under Namespace

Classes: Affine, BatchNorm, Dropout, Identity, ReLU, Sigmoid, Softmax

Constant Summary collapse

VERSION =
"1.8"

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(num_nodes, learning_rate: 0.01, batch_size: 1, activation: %i(relu identity),, momentum: 0, weight_decay: 0, use_dropout: false, dropout_ratio: 0.5, use_batch_norm: false) ⇒ NN

Returns a new instance of NN.


21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/nn.rb', line 21

def initialize(num_nodes,
               learning_rate: 0.01,
               batch_size: 1,
               activation: %i(relu identity),
               momentum: 0,
               weight_decay: 0,
               use_dropout: false,
               dropout_ratio: 0.5,
               use_batch_norm: false)
  SFloat.srand(rand(2 ** 64))
  @num_nodes = num_nodes
  @learning_rate = learning_rate
  @batch_size = batch_size
  @activation = activation
  @momentum = momentum
  @weight_decay = weight_decay
  @use_dropout = use_dropout
  @dropout_ratio = dropout_ratio
  @use_batch_norm = use_batch_norm
  init_weight_and_bias
  init_gamma_and_beta if @use_batch_norm
  @training = true
  init_layers
end

Instance Attribute Details

#activationObject

Returns the value of attribute activation.


15
16
17
# File 'lib/nn.rb', line 15

def activation
  @activation
end

#batch_sizeObject

Returns the value of attribute batch_size.


14
15
16
# File 'lib/nn.rb', line 14

def batch_size
  @batch_size
end

#betasObject

Returns the value of attribute betas.


12
13
14
# File 'lib/nn.rb', line 12

def betas
  @betas
end

#biasesObject

Returns the value of attribute biases.


10
11
12
# File 'lib/nn.rb', line 10

def biases
  @biases
end

#dropout_ratioObject

Returns the value of attribute dropout_ratio.


18
19
20
# File 'lib/nn.rb', line 18

def dropout_ratio
  @dropout_ratio
end

#gammasObject

Returns the value of attribute gammas.


11
12
13
# File 'lib/nn.rb', line 11

def gammas
  @gammas
end

#learning_rateObject

Returns the value of attribute learning_rate.


13
14
15
# File 'lib/nn.rb', line 13

def learning_rate
  @learning_rate
end

#momentumObject

Returns the value of attribute momentum.


16
17
18
# File 'lib/nn.rb', line 16

def momentum
  @momentum
end

#trainingObject (readonly)

Returns the value of attribute training.


19
20
21
# File 'lib/nn.rb', line 19

def training
  @training
end

#weight_decayObject

Returns the value of attribute weight_decay.


17
18
19
# File 'lib/nn.rb', line 17

def weight_decay
  @weight_decay
end

#weightsObject

Returns the value of attribute weights.


9
10
11
# File 'lib/nn.rb', line 9

def weights
  @weights
end

Class Method Details

.load(file_name) ⇒ Object


46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/nn.rb', line 46

def self.load(file_name)
  json = JSON.parse(File.read(file_name))
  nn = self.new(json["num_nodes"],
    learning_rate: json["learning_rate"],
    batch_size: json["batch_size"],
    activation: json["activation"].map(&:to_sym),
    momentum: json["momentum"],
    weight_decay: json["weight_decay"],
    use_dropout: json["use_dropout"],
    dropout_ratio: json["dropout_ratio"],
    use_batch_norm: json["use_batch_norm"],
  )
  nn.weights = json["weights"].map{|weight| SFloat.cast(weight)}
  nn.biases = json["biases"].map{|bias| SFloat.cast(bias)}
  if json["use_batch_norm"]
    nn.gammas = json["gammas"].map{|gamma| SFloat.cast(gamma)}
    nn.betas = json["betas"].map{|beta| SFloat.cast(beta)}
  end
  nn
end

Instance Method Details

#accurate(x_test, y_test, tolerance = 0.5, &block) ⇒ Object


107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
# File 'lib/nn.rb', line 107

def accurate(x_test, y_test, tolerance = 0.5, &block)
  correct = 0
  num_test_data = x_test.is_a?(SFloat) ? x_test.shape[0] : x_test.length
  (num_test_data.to_f / @batch_size).ceil.times do |i|
    x = SFloat.zeros(@batch_size, @num_nodes.first)
    y = SFloat.zeros(@batch_size, @num_nodes.last)
    @batch_size.times do |j|
      k = i * @batch_size + j
      break if k >= num_test_data
      if x_test.is_a?(SFloat)
        x[j, true] = x_test[k, true]
        y[j, true] = y_test[k, true]
      else
        x[j, true] = SFloat.cast(x_test[k])
        y[j, true] = SFloat.cast(y_test[k])
      end
    end
    x, y = block.call(x, y) if block
    out = forward(x, false)
    @batch_size.times do |j|
      vout = out[j, true]
      vy = y[j, true]
      case @activation[1]
      when :identity
        correct += 1 unless (NMath.sqrt((vout - vy) ** 2) < tolerance).to_a.include?(0)
      when :softmax
        correct += 1 if vout.max_index == vy.max_index
      end
    end
  end
  correct.to_f / num_test_data
end

#learn(x_train, y_train, &block) ⇒ Object


140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
# File 'lib/nn.rb', line 140

def learn(x_train, y_train, &block)
  x = SFloat.zeros(@batch_size, @num_nodes.first)
  y = SFloat.zeros(@batch_size, @num_nodes.last)
  @batch_size.times do |i|
    if x_train.is_a?(SFloat)
      r = rand(x_train.shape[0])
      x[i, true] = x_train[r, true]
      y[i, true] = y_train[r, true]
    else
      r = rand(x_train.length)
      x[i, true] = SFloat.cast(x_train[r])
      y[i, true] = SFloat.cast(y_train[r])
    end
  end
  x, y = block.call(x, y) if block
  forward(x)
  backward(y)
  update_weight_and_bias
  update_gamma_and_beta if @use_batch_norm
  @layers[-1].loss(y)
end

#run(x) ⇒ Object


162
163
164
165
166
# File 'lib/nn.rb', line 162

def run(x)
  x = SFloat.cast(x) if x.is_a?(Array)
  out = forward(x, false)
  out.to_a
end

#save(file_name) ⇒ Object


168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
# File 'lib/nn.rb', line 168

def save(file_name)
  json = {
    "version" => VERSION,
    "num_nodes" => @num_nodes,
    "learning_rate" => @learning_rate,
    "batch_size" => @batch_size,
    "activation" => @activation,
    "momentum" => @momentum,
    "weight_decay" => @weight_decay,
    "use_dropout" => @use_dropout,
    "dropout_ratio" => @dropout_ratio,
    "use_batch_norm" => @use_batch_norm,
    "weights" => @weights.map(&:to_a),
    "biases" => @biases.map(&:to_a),
  }
  if @use_batch_norm
    json_batch_norm = {
      "gammas" => @gammas,
      "betas" => @betas
    }
    json.merge!(json_batch_norm)
  end
  File.write(file_name, JSON.dump(json))
end

#test(x_test, y_test, tolerance = 0.5, &block) ⇒ Object


101
102
103
104
105
# File 'lib/nn.rb', line 101

def test(x_test, y_test, tolerance = 0.5, &block)
  acc = accurate(x_test, y_test, tolerance, &block)
  puts "accurate: #{acc}"
  acc
end

#train(x_train, y_train, epochs, learning_rate_decay: 0, save_dir: nil, save_interval: 1, test: nil, border: nil, tolerance: 0.5, &block) ⇒ Object


67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
# File 'lib/nn.rb', line 67

def train(x_train, y_train, epochs,
          learning_rate_decay: 0,
          save_dir: nil,
          save_interval: 1,
          test: nil,
          border: nil,
          tolerance: 0.5,
          &block)
  num_train_data = x_train.is_a?(SFloat) ? x_train.shape[0] : x_train.length
  (1..epochs).each do |epoch|
    loss = nil
    (num_train_data.to_f / @batch_size).ceil.times do
      loss = learn(x_train, y_train, &block)
      if loss.nan?
        puts "loss is nan"
        return
      end
    end
    if save_dir && epoch % save_interval == 0
      save("#{save_dir}/epoch#{epoch}.json")
    end
    msg = "epoch #{epoch}/#{epochs} loss: #{loss}"
    if test
      acc = accurate(*test, tolerance, &block)
      puts "#{msg} accurate: #{acc}"
      break if border && acc >= border
    else
      puts msg
    end
    @learning_rate -= learning_rate_decay
    @learning_rate = 1e-7 if @learning_rate < 1e-7
  end
end