|
| 1 | +""" |
| 2 | +Note: Cost functions are not implemented for RectifierConvNonlinearity, |
| 3 | +TanhConvNonlinearity, RectifiedLinear, and Tanh. Here we verify that the |
| 4 | +implemented cost functions for convolutional layers give the correct output |
| 5 | +by comparing to standard MLP's. |
| 6 | +""" |
| 7 | + |
| 8 | +import numpy as np |
| 9 | +from numpy.testing import assert_raises |
| 10 | + |
| 11 | +import theano |
| 12 | +from theano import config |
| 13 | +from theano.tests.unittest_tools import assert_allclose |
| 14 | + |
| 15 | +from pylearn2.models.mlp import MLP |
| 16 | +from pylearn2.models.mlp import Sigmoid, Tanh, Linear, RectifiedLinear |
| 17 | +from pylearn2.models.mlp import ConvElemwise |
| 18 | +from pylearn2.space import Conv2DSpace |
| 19 | +from pylearn2.models.mlp import SigmoidConvNonlinearity |
| 20 | +from pylearn2.models.mlp import TanhConvNonlinearity |
| 21 | +from pylearn2.models.mlp import IdentityConvNonlinearity |
| 22 | +from pylearn2.models.mlp import RectifierConvNonlinearity |
| 23 | + |
| 24 | + |
| 25 | +def check_case(conv_nonlinearity, mlp_nonlinearity, cost_implemented=True): |
| 26 | + """Check that ConvNonLinearity and MLPNonlinearity are consistent. |
| 27 | +
|
| 28 | + This is done by building an MLP with a ConvElemwise layer with the |
| 29 | + supplied non-linearity, an MLP with a dense layer, and checking that |
| 30 | + the outputs (and costs if applicable) are consistent. |
| 31 | +
|
| 32 | + Parameters |
| 33 | + ---------- |
| 34 | + conv_nonlinearity: instance of `ConvNonlinearity` |
| 35 | + The non-linearity to provide to a `ConvElemwise` layer. |
| 36 | +
|
| 37 | + mlp_nonlinearity: subclass of `mlp.Linear` |
| 38 | + The fully-connected MLP layer (including non-linearity). |
| 39 | +
|
| 40 | + check_implemented: bool |
| 41 | + If `True`, check that both costs give consistent results. |
| 42 | + If `False`, check that both costs raise `NotImplementedError`. |
| 43 | + """ |
| 44 | + |
| 45 | + # Create fake data |
| 46 | + np.random.seed(12345) |
| 47 | + |
| 48 | + r = 31 |
| 49 | + s = 21 |
| 50 | + shape = [r, s] |
| 51 | + nvis = r*s |
| 52 | + output_channels = 13 |
| 53 | + batch_size = 103 |
| 54 | + |
| 55 | + x = np.random.rand(batch_size, r, s, 1) |
| 56 | + y = np.random.randint(2, size=[batch_size, output_channels, 1, 1]) |
| 57 | + |
| 58 | + x = x.astype(config.floatX) |
| 59 | + y = y.astype(config.floatX) |
| 60 | + |
| 61 | + x_mlp = x.flatten().reshape(batch_size, nvis) |
| 62 | + y_mlp = y.flatten().reshape(batch_size, output_channels) |
| 63 | + |
| 64 | + # Initialize convnet with random weights. |
| 65 | + |
| 66 | + conv_model = MLP( |
| 67 | + input_space=Conv2DSpace(shape=shape, |
| 68 | + axes=['b', 0, 1, 'c'], |
| 69 | + num_channels=1), |
| 70 | + layers=[ConvElemwise(layer_name='conv', |
| 71 | + nonlinearity=conv_nonlinearity, |
| 72 | + output_channels=output_channels, |
| 73 | + kernel_shape=shape, |
| 74 | + pool_shape=[1, 1], |
| 75 | + pool_stride=shape, |
| 76 | + irange=1.0)], |
| 77 | + batch_size=batch_size |
| 78 | + ) |
| 79 | + |
| 80 | + X = conv_model.get_input_space().make_theano_batch() |
| 81 | + Y = conv_model.get_target_space().make_theano_batch() |
| 82 | + Y_hat = conv_model.fprop(X) |
| 83 | + g = theano.function([X], Y_hat) |
| 84 | + |
| 85 | + # Construct an equivalent MLP which gives the same output |
| 86 | + # after flattening both. |
| 87 | + mlp_model = MLP( |
| 88 | + layers=[mlp_nonlinearity(dim=output_channels, |
| 89 | + layer_name='mlp', |
| 90 | + irange=1.0)], |
| 91 | + batch_size=batch_size, |
| 92 | + nvis=nvis |
| 93 | + ) |
| 94 | + |
| 95 | + W, b = conv_model.get_param_values() |
| 96 | + |
| 97 | + W_mlp = np.zeros(shape=(output_channels, nvis), dtype=config.floatX) |
| 98 | + for k in range(output_channels): |
| 99 | + W_mlp[k] = W[k, 0].flatten()[::-1] |
| 100 | + W_mlp = W_mlp.T |
| 101 | + b_mlp = b.flatten() |
| 102 | + |
| 103 | + mlp_model.set_param_values([W_mlp, b_mlp]) |
| 104 | + |
| 105 | + X1 = mlp_model.get_input_space().make_theano_batch() |
| 106 | + Y1 = mlp_model.get_target_space().make_theano_batch() |
| 107 | + Y1_hat = mlp_model.fprop(X1) |
| 108 | + f = theano.function([X1], Y1_hat) |
| 109 | + |
| 110 | + # Check that the two models give the same output |
| 111 | + assert_allclose(f(x_mlp).flatten(), g(x).flatten(), rtol=1e-5, atol=5e-5) |
| 112 | + |
| 113 | + if cost_implemented: |
| 114 | + # Check that the two models have the same costs |
| 115 | + mlp_cost = theano.function([X1, Y1], mlp_model.cost(Y1, Y1_hat)) |
| 116 | + conv_cost = theano.function([X, Y], conv_model.cost(Y, Y_hat)) |
| 117 | + assert_allclose(conv_cost(x, y), mlp_cost(x_mlp, y_mlp)) |
| 118 | + else: |
| 119 | + # Check that both costs are not implemented |
| 120 | + assert_raises(NotImplementedError, conv_model.cost, Y, Y_hat) |
| 121 | + assert_raises(NotImplementedError, mlp_model.cost, Y1, Y1_hat) |
| 122 | + |
| 123 | + |
| 124 | +def test_all_costs(): |
| 125 | + """Check all instances of ConvNonLinearity. |
| 126 | +
|
| 127 | + Either they should be consistent with the corresponding subclass |
| 128 | + of `Linear`, or their `cost` method should not be implemented. |
| 129 | + """ |
| 130 | + |
| 131 | + cases = [[SigmoidConvNonlinearity(), Sigmoid, True], |
| 132 | + [IdentityConvNonlinearity(), Linear, True], |
| 133 | + [TanhConvNonlinearity(), Tanh, False], |
| 134 | + [RectifierConvNonlinearity(), RectifiedLinear, False]] |
| 135 | + |
| 136 | + for conv_nonlinearity, mlp_nonlinearity, cost_implemented in cases: |
| 137 | + check_case(conv_nonlinearity, mlp_nonlinearity, cost_implemented) |
| 138 | + |
| 139 | + |
| 140 | +if __name__ == "__main__": |
| 141 | + test_all_costs() |
0 commit comments