Class: DNN::Layers::Pool2D

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

Overview

Super class of all pooling2D class.

Direct Known Subclasses

AvgPool2D, MaxPool2D

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) ⇒ Pool2D

Returns a new instance of Pool2D.



173
174
175
176
177
178
179
180
181
182
# File 'lib/dnn/core/cnn_layers.rb', line 173

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.



166
167
168
# File 'lib/dnn/core/cnn_layers.rb', line 166

def pool_size
  @pool_size
end

#stridesObject (readonly)

Returns the value of attribute strides.



167
168
169
# File 'lib/dnn/core/cnn_layers.rb', line 167

def strides
  @strides
end

Class Method Details

.load_hash(pool2d_class, hash) ⇒ Object



169
170
171
# File 'lib/dnn/core/cnn_layers.rb', line 169

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

Instance Method Details

#backward(dcol) ⇒ Object



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

def backward(dcol)
  dx = col2im(dcol, @x_shape, *@out_size, *@pool_size, @strides)
  @padding ? back_padding(dx, @pad) : dx
end

#build(model) ⇒ Object



184
185
186
187
188
189
190
191
192
193
194
# File 'lib/dnn/core/cnn_layers.rb', line 184

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

#forward(x) ⇒ Object



196
197
198
199
200
201
# File 'lib/dnn/core/cnn_layers.rb', line 196

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

#shapeObject



208
209
210
# File 'lib/dnn/core/cnn_layers.rb', line 208

def shape
  [*@out_size, @num_channel]
end

#to_hashObject



212
213
214
215
216
217
# File 'lib/dnn/core/cnn_layers.rb', line 212

def to_hash
  super({pool_width: @pool_width,
         pool_height: @pool_height,
         strides: @strides,
         padding: @padding})
end