Class: DNN::Model

Inherits:
Object
  • Object
show all
Defined in:
lib/dnn/core/model.rb

Overview

This class deals with the model of the network.

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeModel

Returns a new instance of Model.



22
23
24
25
26
27
28
# File 'lib/dnn/core/model.rb', line 22

def initialize
  @layers = []
  @trainable = true
  @optimizer = nil
  @training = false
  @compiled = false
end

Instance Attribute Details

#layersObject

All layers possessed by the model



7
8
9
# File 'lib/dnn/core/model.rb', line 7

def layers
  @layers
end

#trainableObject

Setting false prevents learning of parameters.



8
9
10
# File 'lib/dnn/core/model.rb', line 8

def trainable
  @trainable
end

Class Method Details

.load(file_name) ⇒ Object



10
11
12
# File 'lib/dnn/core/model.rb', line 10

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

.load_json(json_str) ⇒ Object



14
15
16
17
18
19
20
# File 'lib/dnn/core/model.rb', line 14

def self.load_json(json_str)
  hash = JSON.parse(json_str, symbolize_names: true)
  model = self.new
  model.layers = hash[:layers].map { |hash_layer| Util.load_hash(hash_layer) }
  model.compile(Util.load_hash(hash[:optimizer]))
  model
end

Instance Method Details

#<<(layer) ⇒ Object



78
79
80
81
82
83
84
# File 'lib/dnn/core/model.rb', line 78

def <<(layer)
  if !layer.is_a?(Layers::Layer) && !layer.is_a?(Model)
    raise TypeError.new("layer is not an instance of the DNN::Layers::Layer class or DNN::Model class.")
  end
  @layers << layer
  self
end

#accurate(x, y, batch_size = 100, &batch_proc) ⇒ Object



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

def accurate(x, y, batch_size = 100, &batch_proc)
  input_data_shape_check(x, y)
  batch_size = batch_size >= x.shape[0] ? x.shape[0] : batch_size
  correct = 0
  (x.shape[0].to_f / batch_size).ceil.times do |i|
    x_batch = Xumo::SFloat.zeros(batch_size, *x.shape[1..-1])
    y_batch = Xumo::SFloat.zeros(batch_size, *y.shape[1..-1])
    batch_size.times do |j|
      k = i * batch_size + j
      break if k >= x.shape[0]
      x_batch[j, false] = x[k, false]
      y_batch[j, false] = y[k, false]
    end
    x_batch, y_batch = batch_proc.call(x_batch, y_batch) if batch_proc
    out = forward(x_batch, false)
    batch_size.times do |j|
      if @layers[-1].shape == [1]
        correct += 1 if out[j, 0].round == y_batch[j, 0].round
      else
        correct += 1 if out[j, true].max_index == y_batch[j, true].max_index
      end
    end
  end
  correct.to_f / x.shape[0]
end

#backward(y) ⇒ Object



234
235
236
237
238
239
240
# File 'lib/dnn/core/model.rb', line 234

def backward(y)
  dout = y
  @layers.reverse.each do |layer|
    dout = layer.backward(dout)
  end
  dout
end

#build(super_model = nil) ⇒ Object



97
98
99
100
101
102
# File 'lib/dnn/core/model.rb', line 97

def build(super_model = nil)
  @super_model = super_model
  @layers.each do |layer|
    layer.build(self)
  end
end

#compile(optimizer) ⇒ Object



86
87
88
89
90
91
92
93
94
95
# File 'lib/dnn/core/model.rb', line 86

def compile(optimizer)
  unless optimizer.is_a?(Optimizers::Optimizer)
    raise TypeError.new("optimizer is not an instance of the DNN::Optimizers::Optimizer class.")
  end
  @compiled = true
  layers_check
  @optimizer = optimizer
  build
  layers_shape_check
end

#compiled?Boolean

Returns:

  • (Boolean)


108
109
110
# File 'lib/dnn/core/model.rb', line 108

def compiled?
  @compiled
end

#copyObject



204
205
206
# File 'lib/dnn/core/model.rb', line 204

def copy
  Marshal.load(Marshal.dump(self))
end

#forward(x, training) ⇒ Object



218
219
220
221
222
223
224
225
226
227
228
# File 'lib/dnn/core/model.rb', line 218

def forward(x, training)
  @training = training
  @layers.each do |layer|
    x = if layer.is_a?(Layers::Layer)
      layer.forward(x)
    elsif layer.is_a?(Model)
      layer.forward(x, training)
    end
  end
  x
end

#get_layer(*args) ⇒ Object



208
209
210
211
212
213
214
215
216
# File 'lib/dnn/core/model.rb', line 208

def get_layer(*args)
  if args.length == 1
    index = args[0]
    @layers[index]
  else
    layer_class, index = args
    @layers.select { |layer| layer.is_a?(layer_class) }[index]
  end
end

#get_prev_layer(layer) ⇒ Object



248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
# File 'lib/dnn/core/model.rb', line 248

def get_prev_layer(layer)
  layer_index = @layers.index(layer)
  prev_layer = if layer_index == 0
    if @super_model
      @super_model.layers[@super_model.layers.index(self) - 1]
    else
      self
    end
  else
    @layers[layer_index - 1]
  end
  if prev_layer.is_a?(Layers::Layer)
    prev_layer
  elsif prev_layer.is_a?(Model)
    prev_layer.layers[-1]
  end
end

#load_json_params(json_str) ⇒ Object



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/dnn/core/model.rb', line 30

def load_json_params(json_str)
  has_param_layers_params = JSON.parse(json_str, symbolize_names: true)
  has_param_layers_index = 0
  @layers.each do |layer|
    next unless layer.is_a?(HasParamLayer)
    hash_params = has_param_layers_params[has_param_layers_index]
    hash_params.each do |key, (shape, base64_param)|
      bin = Base64.decode64(base64_param)
      data = Xumo::SFloat.from_binary(bin).reshape(*shape)
      if layer.params[key].is_a?(LearningParam)
        layer.params[key].data = data
      else
        layer.params[key] = data
      end
    end
    has_param_layers_index += 1
  end
end

#loss(y) ⇒ Object



230
231
232
# File 'lib/dnn/core/model.rb', line 230

def loss(y)
  @layers[-1].loss(y)
end

#optimizerObject



104
105
106
# File 'lib/dnn/core/model.rb', line 104

def optimizer
  @optimizer ? @optimizer : @super_model.optimizer
end

#params_to_jsonObject



66
67
68
69
70
71
72
73
74
75
76
# File 'lib/dnn/core/model.rb', line 66

def params_to_json
  has_param_layers = @layers.select { |layer| layer.is_a?(Layers::HasParamLayer) }
  has_param_layers_params = has_param_layers.map do |layer|
    layer.params.map { |key, param|
      param = param.data if param.is_a?(LearningParam)
      base64_param = Base64.encode64(param.to_binary)
      [key, [param.shape, base64_param]]
    }.to_h
  end
  JSON.dump(has_param_layers_params)
end

#predict(x) ⇒ Object



195
196
197
198
# File 'lib/dnn/core/model.rb', line 195

def predict(x)
  input_data_shape_check(x)
  forward(x, false)
end

#predict1(x) ⇒ Object



200
201
202
# File 'lib/dnn/core/model.rb', line 200

def predict1(x)
  predict(Xumo::SFloat.cast([x]))[0, false]
end

#save(file_name) ⇒ Object



49
50
51
52
53
54
55
56
57
58
# File 'lib/dnn/core/model.rb', line 49

def save(file_name)
  marshal = Marshal.dump(self)
  begin
    File.binwrite(file_name, marshal)
  rescue Errno::ENOENT => ex
    dir_name = file_name.match(%r`(.*)/.+$`)[1]
    Dir.mkdir(dir_name)
    File.binwrite(file_name, marshal)
  end
end

#to_jsonObject



60
61
62
63
64
# File 'lib/dnn/core/model.rb', line 60

def to_json
  hash_layers = @layers.map { |layer| layer.to_hash }
  hash = {version: VERSION, layers: hash_layers, optimizer: @optimizer.to_hash}
  JSON.pretty_generate(hash)
end

#train(x, y, epochs, batch_size: 1, test: nil, verbose: true, batch_proc: nil, &epoch_proc) ⇒ Object



116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
# File 'lib/dnn/core/model.rb', line 116

def train(x, y, epochs,
          batch_size: 1,
          test: nil,
          verbose: true,
          batch_proc: nil,
          &epoch_proc)
  unless compiled?
    raise DNN_Error.new("The model is not compiled.")
  end
  num_train_data = x.shape[0]
  (1..epochs).each do |epoch|
    puts "【 epoch #{epoch}/#{epochs}" if verbose
    (num_train_data.to_f / batch_size).ceil.times do |index|
      x_batch, y_batch = Util.get_minibatch(x, y, batch_size)
      loss = train_on_batch(x_batch, y_batch, &batch_proc)
      if loss.nan?
        puts "\nloss is nan" if verbose
        return
      end
      num_trained_data = (index + 1) * batch_size
      num_trained_data = num_trained_data > num_train_data ? num_train_data : num_trained_data
      log = "\r"
      40.times do |i|
        if i < num_trained_data * 40 / num_train_data
          log << "="
        elsif i == num_trained_data * 40 / num_train_data
          log << ">"
        else
          log << "_"
        end
      end
      log << "  #{num_trained_data}/#{num_train_data} loss: #{sprintf('%.8f', loss)}"
      print log if verbose
    end
    if verbose && test
      acc = accurate(test[0], test[1], batch_size, &batch_proc)
      print "  accurate: #{acc}"
    end
    puts "" if verbose
    epoch_proc.call(epoch) if epoch_proc
  end
end

#train_on_batch(x, y, &batch_proc) ⇒ Object



159
160
161
162
163
164
165
166
167
# File 'lib/dnn/core/model.rb', line 159

def train_on_batch(x, y, &batch_proc)
  input_data_shape_check(x, y)
  x, y = batch_proc.call(x, y) if batch_proc
  forward(x, true)
  loss_value = loss(y)
  backward(y)
  update
  loss_value
end

#training?Boolean

Returns:

  • (Boolean)


112
113
114
# File 'lib/dnn/core/model.rb', line 112

def training?
  @training
end

#updateObject



242
243
244
245
246
# File 'lib/dnn/core/model.rb', line 242

def update
  @layers.each do |layer|
    layer.update if @trainable && (layer.is_a?(Layers::HasParamLayer) || layer.is_a?(Model))
  end
end