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 =
"2.4"

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
# File 'lib/nn.rb', line 46

def self.load(file_name)
  Marshal.load(File.binread(file_name))
end

.load_json(file_name) ⇒ Object



50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# File 'lib/nn.rb', line 50

def self.load_json(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



93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
# File 'lib/nn.rb', line 93

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



126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
# File 'lib/nn.rb', line 126

def learn(x_train, y_train, &block)
  if x_train.is_a?(SFloat)
    indexes = (0...x_train.shape[0]).to_a.sample(@batch_size)
    x = x_train[indexes, true]
    y = y_train[indexes, true]
  else
    indexes = (0...x_train.length).to_a.sample(@batch_size)
    x = SFloat.zeros(@batch_size, @num_nodes.first)
    y = SFloat.zeros(@batch_size, @num_nodes.last)
    @batch_size.times do |i|
      x[i, true] = SFloat.cast(x_train[indexes[i]])
      y[i, true] = SFloat.cast(y_train[indexes[i]])
    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



148
149
150
151
152
153
154
# File 'lib/nn.rb', line 148

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

#save(file_name) ⇒ Object



156
157
158
# File 'lib/nn.rb', line 156

def save(file_name)
  File.binwrite(file_name, Marshal.dump(self))
end

#save_json(file_name) ⇒ Object



160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
# File 'lib/nn.rb', line 160

def save_json(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



87
88
89
90
91
# File 'lib/nn.rb', line 87

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, func = nil, &block) ⇒ Object



71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
# File 'lib/nn.rb', line 71

def train(x_train, y_train, epochs, func = nil, &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, &func)
      if loss.nan?
        puts "loss is nan"
        return
      end
    end
    puts "epoch #{epoch}/#{epochs} loss: #{loss}"
    block.call(epoch) if block
  end
end