Class: DNN::Layers::MaxPool2D

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

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Layer

#built?, #prev_layer

Constructor Details

#initialize(pool_size, strides: nil, padding: false) ⇒ MaxPool2D

Returns a new instance of MaxPool2D.



329
330
331
332
333
334
335
336
337
338
# File 'lib/dnn/core/layers.rb', line 329

def initialize(pool_size, strides: nil, padding: false)
  super()
  @pool_size = pool_size.is_a?(Integer) ? [pool_size, pool_size] : pool_size
  @strides = if strides
    strides.is_a?(Integer) ? [strides, strides] : strides
  else
    @pool_size.clone
  end
  @padding = padding
end

Instance Attribute Details

#pool_sizeObject (readonly)

Returns the value of attribute pool_size.



322
323
324
# File 'lib/dnn/core/layers.rb', line 322

def pool_size
  @pool_size
end

#stridesObject (readonly)

Returns the value of attribute strides.



323
324
325
# File 'lib/dnn/core/layers.rb', line 323

def strides
  @strides
end

Class Method Details

.load_hash(hash) ⇒ Object



325
326
327
# File 'lib/dnn/core/layers.rb', line 325

def self.load_hash(hash)
  MaxPool2D.new(hash[:pool_size], strides: hash[:strides], padding: hash[:padding])
end

Instance Method Details

#backward(dout) ⇒ Object



361
362
363
364
365
366
367
# File 'lib/dnn/core/layers.rb', line 361

def backward(dout)
  dmax = SFloat.zeros(dout.size * @pool_size.reduce(:*))
  dmax[@max_index] = dout.flatten
  dcol = dmax.reshape(dout.shape[0..2].reduce(:*), dout.shape[3] * @pool_size.reduce(:*))
  dx = col2im(dcol, @x_shape, *@out_size, *@pool_size, @strides)
  @padding ? back_padding(dx, @pad) : dx
end

#build(model) ⇒ Object



340
341
342
343
344
345
346
347
348
349
350
# File 'lib/dnn/core/layers.rb', line 340

def build(model)
  super
  prev_w, prev_h = prev_layer.shape[0..1]
  @num_channel = prev_layer.shape[2]
  @out_size = out_size(prev_w, prev_h, *@pool_size, @strides)
  out_w, out_h = @out_size
  if @padding
    @pad = [prev_w - out_w, prev_h - out_h]
    @out_size = [prev_w, prev_h]
  end
end

#forward(x) ⇒ Object



352
353
354
355
356
357
358
359
# File 'lib/dnn/core/layers.rb', line 352

def forward(x)
  x = padding(x, @pad) if @padding
  @x_shape = x.shape
  col = im2col(x, *@out_size, *@pool_size, @strides)
  col = col.reshape(x.shape[0] * @out_size.reduce(:*) * x.shape[3], @pool_size.reduce(:*))
  @max_index = col.max_index(1)
  col.max(1).reshape(x.shape[0], *@out_size, x.shape[3])
end

#shapeObject



369
370
371
# File 'lib/dnn/core/layers.rb', line 369

def shape
  [*@out_size, @num_channel]
end

#to_hashObject



373
374
375
376
377
378
379
380
381
# File 'lib/dnn/core/layers.rb', line 373

def to_hash
  {
    name: self.class.name,
    pool_width: @pool_width,
    pool_height: @pool_height,
    strides: @strides,
    padding: @padding,
  }
end