Class: DNN::Layers::Dropout

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

Instance Attribute Summary collapse

Attributes inherited from Layer

#input_shape, #name

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Layer

#build, #built?, #call, call, #output_shape

Constructor Details

#initialize(dropout_ratio = 0.5, seed: rand(1 << 31), use_scale: true) ⇒ Dropout

Returns a new instance of Dropout.

Parameters:

  • (defaults to: 0.5)

    Nodes dropout ratio.

  • (defaults to: rand(1 << 31))

    Seed of random number used for masking.

  • (defaults to: true)

    Set to true to scale the output according to the dropout ratio.



310
311
312
313
314
315
316
317
# File 'lib/dnn/core/layers.rb', line 310

def initialize(dropout_ratio = 0.5, seed: rand(1 << 31), use_scale: true)
  super()
  @dropout_ratio = dropout_ratio
  @seed = seed
  @use_scale = use_scale
  @mask = nil
  @rnd = Random.new(@seed)
end

Instance Attribute Details

#dropout_ratio ⇒ Object

Returns the value of attribute dropout_ratio.



300
301
302
# File 'lib/dnn/core/layers.rb', line 300

def dropout_ratio
  @dropout_ratio
end

#use_scale ⇒ Object (readonly)

Returns the value of attribute use_scale.



301
302
303
# File 'lib/dnn/core/layers.rb', line 301

def use_scale
  @use_scale
end

Class Method Details

.from_hash(hash) ⇒ Object



303
304
305
# File 'lib/dnn/core/layers.rb', line 303

def self.from_hash(hash)
  self.new(hash[:dropout_ratio], seed: hash[:seed], use_scale: hash[:use_scale])
end

Instance Method Details

#backward(dy) ⇒ Object



330
331
332
333
# File 'lib/dnn/core/layers.rb', line 330

def backward(dy)
  dy[@mask] = 0
  dy
end

#forward(x) ⇒ Object



319
320
321
322
323
324
325
326
327
328
# File 'lib/dnn/core/layers.rb', line 319

def forward(x)
  if DNN.learning_phase
    Xumo::SFloat.srand(@rnd.rand(1 << 31))
    @mask = Xumo::SFloat.ones(*x.shape).rand < @dropout_ratio
    x[@mask] = 0
  elsif @use_scale
    x *= (1 - @dropout_ratio)
  end
  x
end

#to_hash ⇒ Object



335
336
337
# File 'lib/dnn/core/layers.rb', line 335

def to_hash
  super(dropout_ratio: @dropout_ratio, seed: @seed, use_scale: @use_scale)
end