Cost layer

class layers.cost_layer.Cost_layer(cost_type, input_shape=None, scale=1.0, ratio=0.0, noobject_scale=1.0, threshold=0.0, smoothing=0.0, **kwargs)[source]

Bases: NumPyNet.layers.base.BaseLayer

Cost layer

Compute the cost of the output based on the selected cost function.

Parameters
  • input_shape – tuple (default=None) Shape of the input in the format (batch, w, h, c), None is used when the layer is part of a Network model.

  • cost_type – cost_type or str Cost function to be applied to the layer, from the enum cost_type.

  • scale – float (default=1.)

  • ratio – float (default=0.)

  • noobject_scale – float (default=1)

  • threshold – float (default=0.)

  • smooothing – float (default=0.)

Example

>>> import os
>>>
>>> import numpy as np
>>> import pylab as plt
>>> from PIL import Image
>>>
>>> img_2_float = lambda im : ((im - im.min()) * (1. / (im.max() - im.min()) * 1.)).astype(float)
>>> float_2_img = lambda im : ((im - im.min()) * (1. / (im.max() - im.min()) * 255.)).astype(np.uint8)
>>>
>>> filename = os.path.join(os.path.dirname(__file__), '..', '..', 'data', 'dog.jpg')
>>> inpt = np.asarray(Image.open(filename), dtype=float)
>>> inpt.setflags(write=1)
>>> inpt = img_2_float(inpt)
>>>
>>> # batch == 1
>>> inpt = np.expand_dims(inpt, axis=0)
>>>
>>> cost_type = cost_type.mse
>>> scale = 1.
>>> ratio = 0.
>>> noobject_scale = 1.
>>> threshold = 0.
>>> smoothing = 0.
>>>
>>> truth = np.random.uniform(low=0., high=1., size=inpt.shape)
>>>
>>> layer = Cost_layer(input_shape=inpt.shape,
>>>                    cost_type=cost_type, scale=scale,
>>>                    ratio=ratio,
>>>                    noobject_scale=noobject_scale,
>>>                    threshold=threshold,
>>>                    smoothing=smoothing,
>>>                    trainable=True)
>>> print(layer)
>>>
>>> layer.forward(inpt, truth)
>>> forward_out = layer.output
>>>
>>> print('Cost: {:.3f}'.format(layer.cost))

References

  • TODO

SECRET_NUM = 12345
backward(delta)[source]

Backward function of the cost_layer, it updates the delta variable to be backpropagated. self.delta is updated inside the cost function.

Parameters

delta (array-like) – delta array of shape (batch, w, h, c). Global delta to be backpropagated.

Return type

self

forward(inpt, truth=None)[source]

Forward function for the cost layer. Using the chosen cost function, computes output, delta and cost.

Parameters
  • inpt (array-like) – Input batch of images in format (batch, in_w, in_h, in _c).

  • truth (array-like) – truth values, it must have the same dimension as inpt.

Return type

self

property out_shape

Get the output shape

Returns

out_shape – Tuple as (batch, out_w, out_h, out_c)

Return type

tuple