code
stringlengths
17
6.64M
def aggregate(loss, weights=None, mode='mean'): "Aggregates an element- or item-wise loss to a scalar loss.\n\n Parameters\n ----------\n loss : Theano tensor\n The loss expression to aggregate.\n weights : Theano tensor, optional\n The weights for each element or item, must be broadcast...
def binary_hinge_loss(predictions, targets, binary=True, delta=1): 'Computes the binary hinge loss between predictions and targets.\n\n .. math:: L_i = \\max(0, \\delta - t_i p_i)\n\n Parameters\n ----------\n predictions : Theano tensor\n Predictions in (0, 1), such as sigmoidal output of a ne...
def multiclass_hinge_loss(predictions, targets, delta=1): 'Computes the multi-class hinge loss between predictions and targets.\n\n .. math:: L_i = \\max_{j \\not = p_i} (0, t_j - t_{p_i} + \\delta)\n\n Parameters\n ----------\n predictions : Theano 2D tensor\n Predictions in (0, 1), such as so...
def binary_accuracy(predictions, targets, threshold=0.5): 'Computes the binary accuracy between predictions and targets.\n\n .. math:: L_i = \\mathbb{I}(t_i = \\mathbb{I}(p_i \\ge \\alpha))\n\n Parameters\n ----------\n predictions : Theano tensor\n Predictions in [0, 1], such as a sigmoidal ou...
def categorical_accuracy(predictions, targets, top_k=1): 'Computes the categorical accuracy between predictions and targets.\n\n .. math:: L_i = \\mathbb{I}(t_i = \\operatorname{argmax}_c p_{i,c})\n\n Can be relaxed to allow matches among the top :math:`k` predictions:\n\n .. math::\n L_i = \\math...
def get_rng(): 'Get the package-level random number generator.\n\n Returns\n -------\n :class:`numpy.random.RandomState` instance\n The :class:`numpy.random.RandomState` instance passed to the most\n recent call of :func:`set_rng`, or ``numpy.random`` if :func:`set_rng`\n has never b...
def set_rng(new_rng): 'Set the package-level random number generator.\n\n Parameters\n ----------\n new_rng : ``numpy.random`` or a :class:`numpy.random.RandomState` instance\n The random number generator to use.\n ' global _rng _rng = new_rng
def l1(x): 'Computes the L1 norm of a tensor\n\n Parameters\n ----------\n x : Theano tensor\n\n Returns\n -------\n Theano scalar\n l1 norm (sum of absolute values of elements)\n ' return T.sum(abs(x))
def l2(x): 'Computes the squared L2 norm of a tensor\n\n Parameters\n ----------\n x : Theano tensor\n\n Returns\n -------\n Theano scalar\n squared l2 norm (sum of squared values of elements)\n ' return T.sum((x ** 2))
def apply_penalty(tensor_or_tensors, penalty, **kwargs): '\n Computes the total cost for applying a specified penalty\n to a tensor or group of tensors.\n\n Parameters\n ----------\n tensor_or_tensors : Theano tensor or list of tensors\n penalty : callable\n **kwargs\n keyword argument...
def regularize_layer_params(layer, penalty, tags={'regularizable': True}, **kwargs): '\n Computes a regularization cost by applying a penalty to the parameters\n of a layer or group of layers.\n\n Parameters\n ----------\n layer : a :class:`Layer` instances or list of layers.\n penalty : callabl...
def regularize_layer_params_weighted(layers, penalty, tags={'regularizable': True}, **kwargs): '\n Computes a regularization cost by applying a penalty to the parameters\n of a layer or group of layers, weighted by a coefficient for each layer.\n\n Parameters\n ----------\n layers : dict\n A...
def regularize_network_params(layer, penalty, tags={'regularizable': True}, **kwargs): '\n Computes a regularization cost by applying a penalty to the parameters\n of all layers in a network.\n\n Parameters\n ----------\n layer : a :class:`Layer` instance.\n Parameters of this layer and all ...
def pytest_addoption(parser): parser.addoption('--runslow', action='store_true', help='run slow tests')
def pytest_runtest_setup(item): if (('slow' in item.keywords) and (not item.config.getoption('--runslow'))): pytest.skip('need --runslow option to run')
@pytest.fixture def dummy_input_layer(): from lasagne.layers.input import InputLayer input_layer = InputLayer((2, 3, 4)) mock = Mock(input_layer) mock.shape = input_layer.shape mock.input_var = input_layer.input_var mock.output_shape = input_layer.output_shape return mock
class TestLayer(): @pytest.fixture def layer(self): from lasagne.layers.base import Layer return Layer(Mock(output_shape=(None,))) @pytest.fixture def named_layer(self): from lasagne.layers.base import Layer return Layer(Mock(output_shape=(None,)), name='layer_name') ...
class TestMergeLayer(): @pytest.fixture def layer(self): from lasagne.layers.base import MergeLayer return MergeLayer([Mock(), Mock()]) def test_input_shapes(self, layer): assert (layer.input_shapes == [l.output_shape for l in layer.input_layers]) @pytest.fixture def lay...
def test_embedding_2D_input(): import numpy as np import theano import theano.tensor as T from lasagne.layers import EmbeddingLayer, InputLayer, helper x = T.imatrix() batch_size = 2 seq_len = 3 emb_size = 5 vocab_size = 3 l_in = InputLayer((None, seq_len)) W = np.arange((v...
def test_embedding_1D_input(): import numpy as np import theano import theano.tensor as T from lasagne.layers import EmbeddingLayer, InputLayer, helper x = T.ivector() batch_size = 2 emb_size = 10 vocab_size = 3 l_in = InputLayer((None,)) W = np.arange((vocab_size * emb_size))....
class TestGetAllLayers(): def test_stack(self): from lasagne.layers import InputLayer, DenseLayer, get_all_layers from itertools import permutations l1 = InputLayer((10, 20)) l2 = DenseLayer(l1, 30) l3 = DenseLayer(l2, 40) for count in (0, 1, 2, 3): for...
class TestGetOutput_InputLayer(): @pytest.fixture def get_output(self): from lasagne.layers.helper import get_output return get_output @pytest.fixture def layer(self): from lasagne.layers.input import InputLayer return InputLayer((3, 2)) def test_get_output_witho...
class TestGetOutput_Layer(): @pytest.fixture def get_output(self): from lasagne.layers.helper import get_output return get_output @pytest.fixture def layers(self): from lasagne.layers.base import Layer from lasagne.layers.input import InputLayer l1 = Mock(Inpu...
class TestGetOutput_MergeLayer(): @pytest.fixture def get_output(self): from lasagne.layers.helper import get_output return get_output @pytest.fixture def layers(self): from lasagne.layers.base import Layer, MergeLayer from lasagne.layers.input import InputLayer ...
class TestGetOutputShape_InputLayer(): @pytest.fixture def get_output_shape(self): from lasagne.layers.helper import get_output_shape return get_output_shape @pytest.fixture def layer(self): from lasagne.layers.input import InputLayer return InputLayer((3, 2)) de...
class TestGetOutputShape_Layer(): @pytest.fixture def get_output_shape(self): from lasagne.layers.helper import get_output_shape return get_output_shape @pytest.fixture def layers(self): from lasagne.layers.base import Layer from lasagne.layers.input import InputLayer...
class TestGetOutputShape_MergeLayer(): @pytest.fixture def get_output_shape(self): from lasagne.layers.helper import get_output_shape return get_output_shape @pytest.fixture def layers(self): from lasagne.layers.base import Layer, MergeLayer from lasagne.layers.input ...
class TestGetAllParams(): def test_get_all_params(self): from lasagne.layers import InputLayer, DenseLayer, get_all_params l1 = InputLayer((10, 20)) l2 = DenseLayer(l1, 30) l3 = DenseLayer(l2, 40) assert (get_all_params(l3) == (l2.get_params() + l3.get_params())) a...
class TestCountParams(): def test_get_all_params(self): from lasagne.layers import InputLayer, DenseLayer, count_params l1 = InputLayer((10, 20)) l2 = DenseLayer(l1, 30) l3 = DenseLayer(l2, 40) num_weights = ((20 * 30) + (30 * 40)) num_biases = (30 + 40) as...
class TestGetAllParamValues(): def test_get_all_param_values(self): from lasagne.layers import InputLayer, DenseLayer, get_all_param_values l1 = InputLayer((10, 20)) l2 = DenseLayer(l1, 30) l3 = DenseLayer(l2, 40) pvs = get_all_param_values(l3) assert (len(pvs) == ...
class TestSetAllParamValues(): def test_set_all_param_values(self): from lasagne.layers import InputLayer, DenseLayer, set_all_param_values from lasagne.utils import floatX l1 = InputLayer((10, 20)) l2 = DenseLayer(l1, 30) l3 = DenseLayer(l2, 40) a2 = floatX(numpy....
class TestInputLayer(): @pytest.fixture def layer(self): from lasagne.layers.input import InputLayer return InputLayer((3, 2)) def test_input_var(self, layer): assert (layer.input_var.ndim == 2) def test_shape(self, layer): assert (layer.shape == (3, 2)) def tes...
class TestDropoutLayer(): @pytest.fixture(params=[(100, 100), (None, 100)]) def input_layer(self, request): from lasagne.layers.input import InputLayer return InputLayer(request.param) @pytest.fixture def layer(self, input_layer): from lasagne.layers.noise import DropoutLayer...
class TestGaussianNoiseLayer(): @pytest.fixture def layer(self): from lasagne.layers.noise import GaussianNoiseLayer return GaussianNoiseLayer(Mock(output_shape=(None,))) @pytest.fixture(params=[(100, 100), (None, 100)]) def input_layer(self, request): from lasagne.layers.inp...
def _example_modules(): paths = glob(join(EXAMPLES_DIR, '*py')) return [splitext(basename(path))[0] for path in paths]
@pytest.fixture def example(request): sys.path.insert(0, EXAMPLES_DIR) request.addfinalizer((lambda : sys.path.remove(EXAMPLES_DIR)))
@pytest.mark.slow @pytest.mark.parametrize('module_name', _example_modules()) def test_example(example, module_name): try: main = getattr(import_module(module_name), 'main') except ImportError as e: skip_exceptions = ['requires a GPU', 'pylearn2', 'dnn not available'] if any([(text in ...
def test_initializer_sample(): from lasagne.init import Initializer with pytest.raises(NotImplementedError): Initializer().sample((100, 100))
def test_shape(): from lasagne.init import Initializer for klass in Initializer.__subclasses__(): if len(klass.__subclasses__()): for sub_klass in klass.__subclasses__(): assert (sub_klass().sample((12, 23)).shape == (12, 23)) else: assert (klass().sampl...
def test_specified_rng(): from lasagne.random import get_rng, set_rng from lasagne.init import Normal, Uniform, GlorotNormal, GlorotUniform, Sparse, Orthogonal from numpy.random import RandomState from numpy import allclose seed = 123456789 rng = get_rng() for init_class in [Normal, Unifor...
def test_normal(): from lasagne.init import Normal sample = Normal().sample((100, 200)) assert ((- 0.001) < sample.mean() < 0.001) assert (0.009 < sample.std() < 0.011)
def test_uniform_range_as_number(): from lasagne.init import Uniform sample = Uniform(1.0).sample((300, 400)) assert (sample.shape == (300, 400)) assert ((- 1.0) <= sample.min() < (- 0.9)) assert (0.9 < sample.max() <= 1.0)
def test_uniform_range_as_range(): from lasagne.init import Uniform sample = Uniform((0.0, 1.0)).sample((300, 400)) assert (sample.shape == (300, 400)) assert (0.0 <= sample.min() < 0.1) assert (0.9 < sample.max() <= 1.0)
def test_uniform_mean_std(): from lasagne.init import Uniform sample = Uniform(std=1.0, mean=5.0).sample((300, 400)) assert (4.9 < sample.mean() < 5.1) assert (0.9 < sample.std() < 1.1)
def test_glorot_normal(): from lasagne.init import GlorotNormal sample = GlorotNormal().sample((100, 100)) assert ((- 0.01) < sample.mean() < 0.01) assert (0.09 < sample.std() < 0.11)
def test_glorot_1d_not_supported(): from lasagne.init import GlorotNormal with pytest.raises(RuntimeError): GlorotNormal().sample((100,))
def test_glorot_normal_receptive_field(): from lasagne.init import GlorotNormal sample = GlorotNormal().sample((50, 50, 2)) assert ((- 0.01) < sample.mean() < 0.01) assert (0.09 < sample.std() < 0.11)
def test_glorot_normal_gain(): from lasagne.init import GlorotNormal sample = GlorotNormal(gain=10.0).sample((100, 100)) assert ((- 0.1) < sample.mean() < 0.1) assert (0.9 < sample.std() < 1.1) sample = GlorotNormal(gain='relu').sample((100, 100)) assert ((- 0.01) < sample.mean() < 0.01) a...
def test_glorot_normal_c01b(): from lasagne.init import GlorotNormal sample = GlorotNormal(c01b=True).sample((25, 2, 2, 25)) assert ((- 0.01) < sample.mean() < 0.01) assert (0.09 < sample.std() < 0.11)
def test_glorot_normal_c01b_4d_only(): from lasagne.init import GlorotNormal with pytest.raises(RuntimeError): GlorotNormal(c01b=True).sample((100,)) with pytest.raises(RuntimeError): GlorotNormal(c01b=True).sample((100, 100)) with pytest.raises(RuntimeError): GlorotNormal(c01b...
def test_glorot_uniform(): from lasagne.init import GlorotUniform sample = GlorotUniform().sample((150, 450)) assert ((- 0.1) <= sample.min() < (- 0.09)) assert (0.09 < sample.max() <= 0.1)
def test_glorot_uniform_receptive_field(): from lasagne.init import GlorotUniform sample = GlorotUniform().sample((150, 150, 2)) assert ((- 0.1) <= sample.min() < (- 0.09)) assert (0.09 < sample.max() <= 0.1)
def test_glorot_uniform_gain(): from lasagne.init import GlorotUniform sample = GlorotUniform(gain=10.0).sample((150, 450)) assert ((- 1.0) <= sample.min() < (- 0.9)) assert (0.9 < sample.max() <= 1.0) sample = GlorotUniform(gain='relu').sample((100, 100)) assert ((- 0.01) < sample.mean() < 0....
def test_glorot_uniform_c01b(): from lasagne.init import GlorotUniform sample = GlorotUniform(c01b=True).sample((75, 2, 2, 75)) assert ((- 0.1) <= sample.min() < (- 0.09)) assert (0.09 < sample.max() <= 0.1)
def test_glorot_uniform_c01b_4d_only(): from lasagne.init import GlorotUniform with pytest.raises(RuntimeError): GlorotUniform(c01b=True).sample((100,)) with pytest.raises(RuntimeError): GlorotUniform(c01b=True).sample((100, 100)) with pytest.raises(RuntimeError): GlorotUniform...
def test_he_normal(): from lasagne.init import HeNormal sample = HeNormal().sample((100, 100)) assert ((- 0.01) < sample.mean() < 0.01) assert (0.09 < sample.std() < 0.11)
def test_he_1d_not_supported(): from lasagne.init import HeNormal with pytest.raises(RuntimeError): HeNormal().sample((100,))
def test_he_normal_receptive_field(): from lasagne.init import HeNormal sample = HeNormal().sample((50, 50, 2)) assert ((- 0.01) < sample.mean() < 0.01) assert (0.09 < sample.std() < 0.11)
def test_he_normal_gain(): from lasagne.init import HeNormal sample = HeNormal(gain=10.0).sample((100, 100)) assert ((- 0.1) < sample.mean() < 0.1) assert (0.9 < sample.std() < 1.1) sample = HeNormal(gain='relu').sample((200, 50)) assert ((- 0.1) < sample.mean() < 0.1) assert (0.07 < sampl...
def test_he_normal_c01b(): from lasagne.init import HeNormal sample = HeNormal(c01b=True).sample((25, 2, 2, 25)) assert ((- 0.01) < sample.mean() < 0.01) assert (0.09 < sample.std() < 0.11)
def test_he_normal_c01b_4d_only(): from lasagne.init import HeNormal with pytest.raises(RuntimeError): HeNormal(c01b=True).sample((100,)) with pytest.raises(RuntimeError): HeNormal(c01b=True).sample((100, 100)) with pytest.raises(RuntimeError): HeNormal(c01b=True).sample((100, ...
def test_he_uniform(): from lasagne.init import HeUniform sample = HeUniform().sample((300, 200)) assert ((- 0.1) <= sample.min() < (- 0.09)) assert (0.09 < sample.max() <= 0.1)
def test_he_uniform_receptive_field(): from lasagne.init import HeUniform sample = HeUniform().sample((150, 150, 2)) assert ((- 0.1) <= sample.min() < (- 0.09)) assert (0.09 < sample.max() <= 0.1)
def test_he_uniform_gain(): from lasagne.init import HeUniform sample = HeUniform(gain=10.0).sample((300, 200)) assert ((- 1.0) <= sample.min() < (- 0.9)) assert (0.9 < sample.max() <= 1.0) sample = HeUniform(gain='relu').sample((100, 100)) assert ((- 0.1) < sample.mean() < 0.1) assert (0....
def test_he_uniform_c01b(): from lasagne.init import HeUniform sample = HeUniform(c01b=True).sample((75, 2, 2, 75)) assert ((- 0.1) <= sample.min() < (- 0.09)) assert (0.09 < sample.max() <= 0.1)
def test_he_uniform_c01b_4d_only(): from lasagne.init import HeUniform with pytest.raises(RuntimeError): HeUniform(c01b=True).sample((100,)) with pytest.raises(RuntimeError): HeUniform(c01b=True).sample((100, 100)) with pytest.raises(RuntimeError): HeUniform(c01b=True).sample((...
def test_constant(): from lasagne.init import Constant sample = Constant(1.0).sample((10, 20)) assert (sample == 1.0).all()
def test_sparse(): from lasagne.init import Sparse sample = Sparse(sparsity=0.1).sample((10, 20)) assert ((sample != 0.0).sum() == ((10 * 20) * 0.1))
def test_sparse_1d_not_supported(): from lasagne.init import Sparse with pytest.raises(RuntimeError): Sparse().sample((100,))
def test_orthogonal(): import numpy as np from lasagne.init import Orthogonal sample = Orthogonal().sample((100, 200)) assert np.allclose(np.dot(sample, sample.T), np.eye(100), atol=1e-06) sample = Orthogonal().sample((200, 100)) assert np.allclose(np.dot(sample.T, sample), np.eye(100), atol=1...
def test_orthogonal_gain(): import numpy as np from lasagne.init import Orthogonal gain = 2 sample = Orthogonal(gain).sample((100, 200)) assert np.allclose(np.dot(sample, sample.T), ((gain * gain) * np.eye(100)), atol=1e-06) gain = np.sqrt(2) sample = Orthogonal('relu').sample((100, 200)) ...
def test_orthogonal_multi(): import numpy as np from lasagne.init import Orthogonal sample = Orthogonal().sample((100, 50, 80)) sample = sample.reshape(100, (50 * 80)) assert np.allclose(np.dot(sample, sample.T), np.eye(100), atol=1e-06)
def test_orthogonal_1d_not_supported(): from lasagne.init import Orthogonal with pytest.raises(RuntimeError): Orthogonal().sample((100,))
class TestNonlinearities(object): def linear(self, x): return x def rectify(self, x): return (x * (x > 0)) def leaky_rectify(self, x): return ((x * (x > 0)) + ((0.01 * x) * (x < 0))) def leaky_rectify_0(self, x): return self.rectify(x) def elu(self, x, alpha=1)...
class TestRegularizationPenalties(object): def l1(self, x): return np.abs(x).sum() def l2(self, x): return (x ** 2).sum() @pytest.mark.parametrize('penalty', ['l1', 'l2']) def test_penalty(self, penalty): np_penalty = getattr(self, penalty) theano_penalty = getattr(l...
class TestRegularizationHelpers(object): @pytest.fixture def layers(self): l_1 = lasagne.layers.InputLayer((10,)) l_2 = lasagne.layers.DenseLayer(l_1, num_units=20) l_3 = lasagne.layers.DenseLayer(l_2, num_units=30) return (l_1, l_2, l_3) def test_apply_penalty(self): ...
class TestUpdateFunctions(object): torch_values = {'sgd': [0.81707280688755, 0.6648326359915, 0.5386151140949], 'momentum': [0.6848486952183, 0.44803321781003, 0.27431190123502], 'nesterov_momentum': [0.67466543592725, 0.44108468114241, 0.2769002108997], 'adagrad': [0.55373120047759, 0.55373120041518, 0.553731200...
def test_get_or_compute_grads(): from lasagne.updates import get_or_compute_grads A = theano.shared(1) B = theano.shared(1) loss = (A + B) grads = get_or_compute_grads(loss, [A, B]) assert (get_or_compute_grads(grads, [A, B]) is grads) with pytest.raises(ValueError): get_or_compute...
@pytest.mark.parametrize('ndim', [2, 3]) def test_norm_constraint(ndim): import numpy as np import theano from lasagne.updates import norm_constraint from lasagne.utils import compute_norms max_norm = 0.01 param = theano.shared(np.random.randn(*((25,) * ndim)).astype(theano.config.floatX)) ...
def test_norm_constraint_norm_axes(): import numpy as np import theano from lasagne.updates import norm_constraint from lasagne.utils import compute_norms max_norm = 0.01 norm_axes = (0, 2) param = theano.shared(np.random.randn(10, 20, 30, 40).astype(theano.config.floatX)) update = nor...
def test_norm_constraint_dim6_raises(): import numpy as np import theano from lasagne.updates import norm_constraint max_norm = 0.01 param = theano.shared(np.random.randn(1, 2, 3, 4, 5, 6).astype(theano.config.floatX)) with pytest.raises(ValueError) as excinfo: norm_constraint(param, m...
def test_total_norm_constraint(): import numpy as np import theano import theano.tensor as T from lasagne.updates import total_norm_constraint x1 = T.scalar() x2 = T.matrix() threshold = 5.0 tensors1 = total_norm_constraint([x1, x2], threshold, return_norm=False) (tensors2, norm) =...
def test_shared_empty(): from lasagne.utils import shared_empty X = shared_empty(3) assert (np.zeros((1, 1, 1)) == X.eval()).all()
def test_as_theano_expression_fails(): from lasagne.utils import as_theano_expression with pytest.raises(TypeError): as_theano_expression({})
def test_collect_shared_vars(): from lasagne.utils import collect_shared_vars as collect (x, y, z) = (theano.shared(0, name=n) for n in 'xyz') assert (collect([x, y, z]) == [x, y, z]) assert (collect([x, y, x, y, y, z]) == [x, y, z]) assert (collect(((x + y) + z)) == [x, y, z]) assert (collect...
def test_one_hot(): from lasagne.utils import one_hot a = np.random.randint(0, 10, 20) b = np.zeros((a.size, (a.max() + 1))) b[(np.arange(a.size), a)] = 1 result = one_hot(a).eval() assert (result == b).all()
def test_as_tuple_fails(): from lasagne.utils import as_tuple with pytest.raises(ValueError): as_tuple([1, 2, 3], 4) with pytest.raises(TypeError): as_tuple('asdf', 4, int)
def test_compute_norms(): from lasagne.utils import compute_norms array = np.random.randn(10, 20, 30, 40).astype(theano.config.floatX) norms = compute_norms(array) assert (array.dtype == norms.dtype) assert (norms.shape[0] == array.shape[0])
def test_compute_norms_axes(): from lasagne.utils import compute_norms array = np.random.randn(10, 20, 30, 40).astype(theano.config.floatX) norms = compute_norms(array, norm_axes=(0, 2)) assert (array.dtype == norms.dtype) assert (norms.shape == (array.shape[1], array.shape[3]))
def test_compute_norms_ndim6_raises(): from lasagne.utils import compute_norms array = np.random.randn(1, 2, 3, 4, 5, 6).astype(theano.config.floatX) with pytest.raises(ValueError) as excinfo: compute_norms(array) assert ('Unsupported tensor dimensionality' in str(excinfo.value))
def test_create_param_bad_callable_raises(): from lasagne.utils import create_param with pytest.raises(RuntimeError): create_param((lambda x: {}), (1, 2, 3)) with pytest.raises(RuntimeError): create_param((lambda x: np.array(1)), (1, 2, 3))
def test_create_param_bad_spec_raises(): from lasagne.utils import create_param with pytest.raises(RuntimeError): create_param({}, (1, 2, 3))
def test_create_param_accepts_iterable_shape(): from lasagne.utils import create_param factory = np.empty create_param(factory, [2, 3]) create_param(factory, (x for x in [2, 3]))
def test_create_param_numpy_bad_shape_raises_error(): from lasagne.utils import create_param param = np.array([[1, 2, 3], [4, 5, 6]]) with pytest.raises(RuntimeError): create_param(param, (3, 2))
def test_create_param_numpy_returns_shared(): from lasagne.utils import create_param param = np.array([[1, 2, 3], [4, 5, 6]]) result = create_param(param, (2, 3)) assert (result.get_value() == param).all() assert isinstance(result, type(theano.shared(param))) assert (result.get_value() == para...
def test_create_param_shared_returns_same(): from lasagne.utils import create_param param = theano.shared(np.array([[1, 2, 3], [4, 5, 6]])) result = create_param(param, (2, 3)) assert (result is param)
def test_create_param_shared_bad_ndim_raises_error(): from lasagne.utils import create_param param = theano.shared(np.array([[1, 2, 3], [4, 5, 6]])) with pytest.raises(RuntimeError): create_param(param, (2, 3, 4))
def test_create_param_callable_returns_return_value(): from lasagne.utils import create_param array = np.array([[1, 2, 3], [4, 5, 6]]) factory = Mock() factory.return_value = array result = create_param(factory, (2, 3)) assert (result.get_value() == array).all() factory.assert_called_with(...
def test_nonpositive_dims_raises_value_error(): from lasagne.utils import create_param neg_shape = ((- 1), (- 1)) zero_shape = (0, 0) pos_shape = (1, 1) spec = np.empty with pytest.raises(ValueError): create_param(spec, neg_shape) with pytest.raises(ValueError): create_para...
def test_unroll_scan(): from lasagne.utils import unroll_scan k = 2 a = T.scalar('a') result = unroll_scan(fn=(lambda step, prior_result, a: (prior_result * a)), sequences=T.arange(k), outputs_info=[1.0], non_sequences=[a], n_steps=k) final_result = result[(- 1)] power = theano.function(inputs...