numpy.random.randn.astype

Here are the examples of the python api numpy.random.randn.astype taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

119 Examples 7

Example 1

Project: treeano Source File: partition_axis_test.py
def test_partition_axis_node():
    # just testing that it runs
    network = tn.SequentialNode(
        "s",
        [tn.InputNode("i", shape=(4, 8, 12, 16, 20)),
         partition_axis.PartitionAxisNode("pa",
                                          split_idx=2,
                                          num_splits=4,
                                          channel_axis=3)]
    ).network()
    fn = network.function(["i"], ["s"])
    x = np.random.randn(4, 8, 12, 16, 20).astype(fX)
    ans = x[:, :, :, 8:12, :]
    res = fn(x)[0]
    nt.assert_equal(ans.shape, network["pa"].get_vw("default").shape)
    np.testing.assert_equal(res, ans)

Example 2

Project: seya Source File: test_variational.py
Function: test_basic
    def test_basic(self):
        """Just check that the Variational layer can compile and run"""
        nb_samples, input_dim, output_dim = 3, 10, 5
        layer = VariationalDense(input_dim=input_dim, output_dim=output_dim,
                                 batch_size=nb_samples)
        X = layer.get_input()
        Y1 = layer.get_output(train=True)
        Y2 = layer.get_output(train=False)
        F = theano.function([X], [Y1, Y2])

        y1, y2 = F(np.random.randn(nb_samples, input_dim).astype(floatX))
        assert y1.shape == (nb_samples, output_dim)
        assert y2.shape == (nb_samples, output_dim)

Example 3

Project: treeano Source File: simple_test.py
def test_apply_node():
    network = tn.SequentialNode("s", [
        tn.InputNode("in", shape=(3, 4, 5)),
        tn.ApplyNode("a", fn=T.sum, shape_fn=lambda x: ()),
    ]).network()
    fn = network.function(["in"], ["s"])
    x = np.random.randn(3, 4, 5).astype(fX)
    np.testing.assert_allclose(fn(x)[0],
                               x.sum(),
                               rtol=1e-5)

Example 4

Project: treeano Source File: lrn_test.py
def _test_localresponse_normalization_fn(fn, shape=(3, 4, 5, 6), **kwargs):
    vw = treeano.VariableWrapper("foo", variable=T.tensor4(), shape=shape)
    new_kwargs = dict(
        # use a big value of alpha so mistakes involving alpha show up strong
        alpha=1.5,
        k=2,
        beta=0.75,
        n=5,
    )
    new_kwargs.update(kwargs)
    fn = theano.function([vw.variable], [fn(vw, **new_kwargs)])
    x = np.random.randn(*shape).astype(fX)
    res, = fn(x)
    ans = ground_truth_normalizer(x, **new_kwargs)
    np.testing.assert_allclose(ans, res, rtol=1e-5)

Example 5

Project: treeano Source File: theanode_test.py
def test_repeat_node():
    network = tn.SequentialNode(
        "s",
        [tn.InputNode("in", shape=(3,)),
         tn.RepeatNode("r", repeats=2, axis=0)]
    ).network()
    fn = network.function(["in"], ["s"])
    x = np.random.randn(3).astype(fX)
    np.testing.assert_allclose(np.repeat(x, 2, 0),
                               fn(x)[0])

Example 6

Project: treeano Source File: simple_test.py
def test_reference_node():
    network = tn.SequentialNode("s", [
        tn.InputNode("input1", shape=(3, 4, 5)),
        tn.InputNode("input2", shape=(5, 4, 3)),
        tn.ReferenceNode("ref", reference="input1"),
    ]).network()

    fn = network.function(["input1"], ["ref"])
    x = np.random.randn(3, 4, 5).astype(fX)
    np.testing.assert_allclose(fn(x)[0], x)

Example 7

Project: treeano Source File: gradient_test.py
def test_gradient_reversal():
    v = np.random.randn(3, 4).astype(fX)
    m = T.matrix()
    s1 = m.sum()
    g1 = T.grad(s1, m)
    s2 = ttg.gradient_reversal(s1)
    g2 = T.grad(s2, m)
    g1_res, g2_res, s1_res, s2_res = theano.function([m], [g1, g2, s1, s2])(v)
    np.testing.assert_allclose(v.sum(), s1_res, rtol=1e-5)
    np.testing.assert_equal(s1_res, s2_res)
    np.testing.assert_equal(np.ones((3, 4), dtype=fX), g1_res)
    np.testing.assert_equal(g1_res, -g2_res)

Example 8

Project: lda2vec Source File: test_fake_data.py
def test_orthogonal_matrix_covariance():
    msg = "Orthogonal matrix should have less covariance than a random matrix"
    orth = Variable(fake_data.orthogonal_matrix([20, 20]).astype('float32'))
    rand = Variable(np.random.randn(20, 20).astype('float32'))
    orth_cc = cross_covariance(orth, orth).data
    rand_cc = cross_covariance(rand, rand).data
    assert orth_cc < rand_cc, msg

Example 9

Project: pylearn2 Source File: test_autoencoder.py
def test_autoencoder_logistic_linear_tied():
    data = np.random.randn(10, 5).astype(config.floatX)
    ae = Autoencoder(5, 7, act_enc='sigmoid', act_dec='linear',
                     tied_weights=True)
    w = ae.weights.get_value()
    ae.hidbias.set_value(np.random.randn(7).astype(config.floatX))
    hb = ae.hidbias.get_value()
    ae.visbias.set_value(np.random.randn(5).astype(config.floatX))
    vb = ae.visbias.get_value()
    d = tensor.matrix()
    result = np.dot(1. / (1 + np.exp(-hb - np.dot(data,  w))), w.T) + vb
    ff = theano.function([d], ae.reconstruct(d))
    assert _allclose(ff(data), result)

Example 10

Project: treeano Source File: variable_test.py
Function: test_variable2
def test_variable2():
    s = treeano.core.variable.VariableWrapper("foo",
                                              shape=(3, 4, 5),
                                              is_shared=True,
                                              inits=[])
    assert s.value.sum() == 0
    x = np.random.randn(3, 4, 5).astype(theano.config.floatX)
    s.value = x
    assert np.allclose(s.value, x)
    try:
        s.value = np.random.randn(5, 4, 3)
    except:
        pass
    else:
        assert False

Example 11

Project: treeano Source File: irregular_length_test.py
def test_irregular_length_attention_node():
    network = tn.SequentialNode(
        "s",
        [tn.InputNode("l", shape=(None,)),
         tn.InputNode("i", shape=(None, 3)),
         irregular_length.irregular_length_attention_node(
             "foo",
             lengths_reference="l",
             num_units=3,
             output_units=None)]
    ).network()
    nt.assert_equal((None, 3), network["foo"].get_vw("default").shape)

    fn = network.function(["i", "l"], ["s"])
    x = np.random.randn(15, 3).astype(fX)
    l = np.array([2, 3, 7, 3], dtype=fX)
    res = fn(x, l)[0].shape
    ans = (4, 3)
    nt.assert_equal(ans, res)

Example 12

Project: treeano Source File: upsample_test.py
def test_repeat_n_d_node2():
    network = tn.SequentialNode(
        "s",
        [tn.InputNode("i", shape=(3, 4, 5)),
         tn.RepeatNDNode("r", upsample_factor=(1, 1, 1))]).network()

    fn = network.function(["i"], ["s"])
    x = np.random.randn(3, 4, 5).astype(fX)
    np.testing.assert_equal(x,
                            fn(x)[0])

Example 13

Project: treeano Source File: downsample_test.py
def test_global_mean_pool_2d_node():
    network = tn.SequentialNode(
        "s",
        [tn.InputNode("i", shape=(6, 5, 4, 3)),
         tn.GlobalMeanPool2DNode("gp")]
    ).network()
    fn = network.function(["i"], ["s"])
    x = np.random.randn(6, 5, 4, 3).astype(fX)
    ans = x.mean(axis=(2, 3))
    np.testing.assert_allclose(ans,
                               fn(x)[0],
                               rtol=1e-5,
                               atol=1e-7)

Example 14

Project: treeano Source File: lrn_test.py
def test_local_response_normalization_node_shape():
    for ndim in [2, 3, 4, 5, 6]:
        shape = (3,) * ndim
        network = tn.SequentialNode(
            "s",
            [tn.InputNode("i", shape=shape),
             lrn.LocalResponseNormalizationNode("lrn")]
        ).network()
        fn = network.function(["i"], ["s"])
        x = np.random.randn(*shape).astype(fX)
        res = fn(x)[0].shape
        np.testing.assert_equal(shape, res)

Example 15

Project: lda2vec Source File: test_dirichlet_likelihood.py
def test_concentration():
    """ Test that alpha > 1.0 on a dense vector has a higher likelihood
    than alpha < 1.0 on a dense vector, and test that a sparse vector
    has the opposite character. """

    dense = np.random.randn(5, 10).astype('float32')
    sparse = np.random.randn(5, 10).astype('float32')
    sparse[:, 1:] /= 1e5
    weights = Variable(dense)
    dhl_dense_10 = dirichlet_likelihood(weights, alpha=10.0).data
    dhl_dense_01 = dirichlet_likelihood(weights, alpha=0.1).data
    weights = Variable(sparse)
    dhl_sparse_10 = dirichlet_likelihood(weights, alpha=10.0).data
    dhl_sparse_01 = dirichlet_likelihood(weights, alpha=0.1).data

    msg = "Sparse vector has higher likelihood than dense with alpha=0.1"
    assert dhl_sparse_01 > dhl_dense_01, msg
    msg = "Dense vector has higher likelihood than sparse with alpha=10.0"
    assert dhl_dense_10 > dhl_sparse_10, msg

Example 16

Project: treeano Source File: utils_test.py
def test_stable_softmax_grad():
    x = theano.shared(np.random.randn(50, 50).astype(fX))
    s1 = T.nnet.softmax(x)
    s2 = treeano.utils.stable_softmax(
        x.reshape([50, 1, 5, 10]),
        axis=(2, 3)
    ).reshape([50, 50])
    np.testing.assert_allclose(s1.eval(), s2.eval(), rtol=1e-5)
    g1 = T.grad(s1[:10, :10].sum(), x)
    g2 = T.grad(s2[:10, :10].sum(), x)
    np.testing.assert_allclose(g1.eval(), g2.eval(), rtol=1e-5)

Example 17

Project: treeano Source File: simple_test.py
def test_add_bias_node():
    network = tn.SequentialNode("s", [
        tn.InputNode("in", shape=(3, 4, 5)),
        tn.AddBiasNode("b", broadcastable_axes=())
    ]).network()
    bias_var = network["b"].get_vw("bias")
    fn = network.function(["in"], ["s"])
    x = np.random.randn(3, 4, 5).astype(fX)
    y = np.random.randn(3, 4, 5).astype(fX)
    # test that bias is 0 initially
    np.testing.assert_allclose(fn(x)[0], x)
    # set bias_var value to new value
    bias_var.value = y
    # test that adding works
    np.testing.assert_allclose(fn(x)[0], x + y)

Example 18

Project: hessianfree Source File: test_gpu.py
def test_rnn_calc_G(dtype):
    inputs = np.random.randn(1000, 10, 1).astype(dtype)
    rnn = hf.RNNet([1, 10, 1], debug=(dtype == np.float64), use_GPU=True)
    rnn.cache_minibatch(inputs, inputs)
    rnn.optimizer = hf.opt.HessianFree()

    v = np.random.randn(rnn.W.size).astype(dtype)
    gpu_Gv = rnn.GPU_calc_G(v)
    cpu_Gv = rnn.calc_G(v)

    assert np.allclose(gpu_Gv, cpu_Gv, rtol=1e-4)

Example 19

Project: tvb-library Source File: _numba_tests.py
    def _run_n_node(self, n_node):
        weights = numpy.random.randn(n_node, n_node).astype('f')
        state = numpy.random.randn(n_node, 2, self.n_thread).astype('f')
        out = numpy.zeros((n_node, self.n_thread)).astype('f')
        offset = 0.5
        cf = cu_simple_cfun(offset, 1)
        @self.jit_and_run(out, weights, state)
        def kernel(out, weights, state):
            t = cuda.blockDim.x * cuda.blockIdx.x + cuda.threadIdx.x
            for i in range(weights.shape[0]):
                out[i, t] = cf(weights, state, i, t)
        expected = weights.dot(state[:, 1] + offset)
        ok = numpy.allclose(expected, out, 1e-4, 1e-5)
        se = numpy.sqrt((expected - out)**2)
        numpy.testing.assert_allclose(out, expected, 1e-4, 1e-5)

Example 20

Project: parakeet Source File: test_simple_regression.py
def test_simple_regression():
  N = 10
  x = np.random.randn(N).astype('float64')
  slope = 903.29
  offset = 102.1
  y = slope * x + offset
  expect(fit_simple_regression, [x,y], (slope,offset))

Example 21

Project: treeano Source File: stochastic_test.py
def test_gaussian_dropout_node():
    def make_network(p):
        return tn.SequentialNode("s", [
            tn.InputNode("i", shape=(3, 4, 5)),
            tn.GaussianDropoutNode("do", p=p)
        ]).network()

    x = np.random.randn(3, 4, 5).astype(fX)
    fn1 = make_network(0).function(["i"], ["s"])
    np.testing.assert_allclose(fn1(x)[0], x)

    @nt.raises(AssertionError)
    def test_not_identity():
        fn2 = make_network(0.5).function(["i"], ["s"])
        np.testing.assert_allclose(fn2(x)[0], x)

    test_not_identity()

Example 22

Project: treeano Source File: theanode_test.py
def test_reshape_node():
    network = tn.SequentialNode(
        "s",
        [tn.InputNode("in", shape=(3, 4, 5)),
         tn.ReshapeNode("r", shape=(5, 12))]
    ).network()
    fn = network.function(["in"], ["s"])
    x = np.random.randn(3, 4, 5).astype(fX)
    res = fn(x)[0]
    np.testing.assert_allclose(res,
                               x.reshape(5, 12))

Example 23

Project: kaggle-galaxies Source File: realtime_augmentation.py
def post_augment_brightness_gen(data_gen, std=0.5):
    for target_arrays, chunk_size in data_gen:
        labels = target_arrays.pop()
        
        stds = np.random.randn(chunk_size).astype('float32') * std
        noise = stds[:, None] * colour_channel_weights[None, :]

        target_arrays = [np.clip(t + noise[:, None, None, :], 0, 1) for t in target_arrays]
        target_arrays.append(labels)

        yield target_arrays, chunk_size

Example 24

Project: treeano Source File: theanode_test.py
def test_dimshuffle_node():
    network = tn.SequentialNode(
        "s",
        [tn.InputNode("in", shape=(3, 4, 5)),
         tn.DimshuffleNode("r", pattern=(1, "x", 0, 2))]
    ).network()
    fn = network.function(["in"], ["s"])
    x = np.random.randn(3, 4, 5).astype(fX)
    ans = T.constant(x).dimshuffle(1, "x", 0, 2).eval()
    res = fn(x)[0]
    np.testing.assert_equal(res.shape, ans.shape)
    np.testing.assert_equal(res, ans)

Example 25

Project: treeano Source File: composite_test.py
Function: test_dense_node
def test_dense_node():
    network = tn.SequentialNode(
        "seq",
        [tn.InputNode("in", shape=(3, 4, 5)),
         tn.DenseNode("fc1", num_units=6),
         tn.DenseNode("fc2", num_units=7),
         tn.DenseNode("fc3", num_units=8)]
    ).network()
    x = np.random.randn(3, 4, 5).astype(fX)
    fn = network.function(["in"], ["fc3"])
    res = fn(x)[0]
    nt.assert_equal(res.shape, (3, 8))

Example 26

Project: treeano Source File: gradnet_test.py
def test_grad_net_interpolation_node():
    network = tn.SequentialNode(
        "s",
        [tn.InputNode("i", shape=(1, 10)),
         gradnet.GradNetInterpolationNode(
             "gradnet",
             {"early": tn.ReLUNode("r"),
              "late": tn.TanhNode("t")},
             late_gate=0.5)]
    ).network()

    fn = network.function(["i"], ["s"])
    x = np.random.randn(1, 10).astype(fX)
    ans = 0.5 * np.clip(x, 0, np.inf) + 0.5 * np.tanh(x)
    np.testing.assert_allclose(ans, fn(x)[0], rtol=1e-5)

Example 27

Project: treeano Source File: activation_transformation_test.py
def test_concatenate_negation_node():
    # just testing that it runs
    network = tn.SequentialNode(
        "s",
        [tn.InputNode("i", shape=(10, 10)),
         activation_transformation.ConcatenateNegationNode("a")]).network()
    fn = network.function(["i"], ["s"])
    x = np.random.randn(10, 10).astype(fX)
    ans = np.concatenate([x, -x], axis=1)
    np.testing.assert_allclose(ans, fn(x)[0])

Example 28

Project: treeano Source File: downsample_test.py
def test_custom_global_pool_node():
    network = tn.SequentialNode(
        "s",
        [tn.InputNode("i", shape=(6, 5, 4, 3)),
         tn.CustomGlobalPoolNode("gp", pool_function=T.mean)]
    ).network()
    fn = network.function(["i"], ["s"])
    x = np.random.randn(6, 5, 4, 3).astype(fX)
    ans = x.mean(axis=(2, 3))
    np.testing.assert_allclose(ans,
                               fn(x)[0],
                               rtol=1e-5,
                               atol=1e-7)

Example 29

Project: treeano Source File: kumaraswamy_unit_test.py
def test_kumaraswamy_unit_node():
    # just testing that it runs
    network = tn.SequentialNode(
        "s",
        [tn.InputNode("i", shape=(100,)),
         ku.KumaraswamyUnitNode("k")]).network()
    fn = network.function(["i"], ["s"])
    x = np.random.randn(100).astype(fX)
    fn(x)

Example 30

Project: deep_recommend_system Source File: sparse_tensor_dense_matmul_grad_test.py
Function: randomtensor
  def _randomTensor(self, size, np_dtype, adjoint=False, sparse=False):
    n, m = size
    x = np.random.randn(n, m).astype(np_dtype)

    if adjoint:
      x = x.transpose()

    if sparse:
      return self._sparsify(x)
    else:
      return tf.constant(x, dtype=np_dtype)

Example 31

Project: treeano Source File: lrn_test.py
def test_local_response_normalization_2d_node_shape():
    shape = (3, 4, 5, 6)
    network = tn.SequentialNode(
        "s",
        [tn.InputNode("i", shape=shape),
         lrn.LocalResponseNormalization2DNode("lrn")]
    ).network()
    fn = network.function(["i"], ["s"])
    x = np.random.randn(*shape).astype(fX)
    res = fn(x)[0].shape
    np.testing.assert_equal(shape, res)

Example 32

Project: treeano Source File: monitor_test.py
def test_monitor_variance_node():
    network = tn.SequentialNode(
        "s",
        [tn.InputNode("x", shape=(3, 4, 5)),
         tn.MonitorVarianceNode("mv")]).network()
    vw = network["mv"].get_vw("var")
    x = np.random.randn(3, 4, 5).astype(fX)
    ans = x.var()
    fn = network.function(["x"], [vw.variable])
    np.testing.assert_allclose(fn(x), [ans], rtol=1e-5)

Example 33

Project: treeano Source File: paired_conv_test.py
def test_paired_conv_2d_with_bias_node():
    network = tn.SequentialNode(
        "s",
        [tn.InputNode("i", shape=(3, 4, 5, 6)),
         paired_conv.PairedConvNode(
             "c",
             {"conv": tn.Conv2DWithBiasNode("c_conv"),
              "separator": tn.IdentityNode("sep")},
             filter_size=(2, 2),
             num_filters=7,
             pad="same")]
    ).network()
    fn = network.function(["i"], ["s"])
    res = fn(np.random.randn(3, 4, 5, 6).astype(fX))[0]
    np.testing.assert_equal((3, 7, 5, 6), res.shape)

Example 34

Project: word2gauss Source File: embeddings_py.py
Function: init_params
    def init_params(self, mu0, sigma_mean0, sigma_std0, sigma_min, sigma_max):
        '''
        Initialize parameters 

        mu = random normal with std mu0, mean 0
        Sigma = random normal with mean sigma_mean0, std sigma_std0,
            and min / max of sigma_min, sigma_max
        '''
        self.mu = mu0 * np.random.randn(self.N, self.K).astype(DTYPE)
        self.Sigma = np.random.randn(*self.Sigma.shape).astype(DTYPE)
        self.Sigma *= sigma_std0
        self.Sigma += sigma_mean0
        self.Sigma = np.maximum(sigma_min, np.minimum(self.Sigma, sigma_max))

Example 35

Project: treeano Source File: recurrent_convolution_test.py
Function: test_default_recurrent_conv_2d_node
    def test_default_recurrent_conv_2d_node():
        network = tn.SequentialNode(
            "s",
            [tn.InputNode("i", shape=(3, 4, 5, 6)),
             rcl.DefaultRecurrentConv2DNode("a",
                                            num_filters=7,
                                            filter_size=(3, 3),
                                            pad="same")]
        ).network()
        fn = network.function(["i"], ["s"])
        res = fn(np.random.randn(3, 4, 5, 6).astype(fX))[0]
        np.testing.assert_equal((3, 7, 5, 6), res.shape)

Example 36

Project: treeano Source File: simple_test.py
def test_send_to_node():
    network = tn.ContainerNode("c", [
        tn.SequentialNode(
            "s1",
            [tn.InputNode("in", shape=(3, 4, 5)),
             tn.SendToNode("stn1", reference="s2")]),
        tn.SequentialNode(
            "s2",
            [tn.SendToNode("stn2", reference="stn3")]),
        tn.SequentialNode(
            "s3",
            [tn.SendToNode("stn3", reference="i")]),
        tn.IdentityNode("i"),
    ]).network()

    fn = network.function(["in"], ["i"])
    x = np.random.randn(3, 4, 5).astype(fX)
    np.testing.assert_allclose(fn(x)[0], x)

Example 37

Project: treeano Source File: utils_test.py
def _clone_test_case(clone_fn):
    x = T.matrix("x")
    y = T.matrix("y")
    x_shape = x.shape
    sample_y = np.random.randn(4, 5).astype(theano.config.floatX)
    srng = theano.tensor.shared_randomstreams.RandomStreams()
    mask = srng.binomial(n=1, p=0.5, size=x_shape)
    mask2 = clone_fn([mask], replace={x: y})[0]
    mask2.eval({y: sample_y})  # ERROR

Example 38

Project: lda2vec Source File: test_dirichlet_likelihood.py
Function: test_embed
def test_embed():
    """ Test that embedding is treated like a Variable"""

    embed_dense = L.EmbedID(5, 10)
    embed_sparse = L.EmbedID(5, 10)
    embed_dense.W.data[:] = np.random.randn(5, 10).astype('float32')
    embed_sparse.W.data[:] = np.random.randn(5, 10).astype('float32')
    embed_sparse.W.data[:, 1:] /= 1e5
    dhl_dense_01 = dirichlet_likelihood(embed_dense, alpha=0.1).data
    dhl_sparse_01 = dirichlet_likelihood(embed_sparse, alpha=0.1).data

    msg = "Sparse vector has higher likelihood than dense with alpha=0.1"
    assert dhl_sparse_01 > dhl_dense_01, msg

Example 39

Project: hessianfree Source File: test_gpu.py
def test_ff_calc_G(dtype):
    inputs = np.random.randn(1000, 1).astype(dtype)
    ff = hf.FFNet([1, 10, 1], debug=(dtype == np.float64), use_GPU=True)
    ff.cache_minibatch(inputs, inputs)

    v = np.random.randn(ff.W.size).astype(dtype)
    gpu_Gv = ff.GPU_calc_G(v)
    cpu_Gv = ff.calc_G(v)

    assert np.allclose(gpu_Gv, cpu_Gv, rtol=1e-4)

Example 40

Project: treeano Source File: simple_test.py
def test_linear_mapping_node():
    network = tn.SequentialNode("s", [
        tn.InputNode("in", shape=(3, 4, 5)),
        tn.LinearMappingNode("linear", output_dim=6),
    ]).network()
    weight_var = network["linear"].get_vw("weight")
    fn = network.function(["in"], ["s"])
    x = np.random.randn(3, 4, 5).astype(fX)
    W = np.random.randn(5, 6).astype(fX)
    # test that weight is 0 initially
    np.testing.assert_allclose(fn(x)[0], np.zeros((3, 4, 6)))
    # set weight_var value to new value
    weight_var.value = W
    # test that adding works
    np.testing.assert_allclose(np.dot(x, W), fn(x)[0], rtol=1e-4, atol=1e-7)

Example 41

Project: seya Source File: test_apply.py
    def test_apply_model(self):
        """Test keras.models.Sequential.__call__"""
        nb_samples, input_dim, output_dim = 3, 10, 5
        model = Sequential()
        model.add(Dense(output_dim=output_dim, input_dim=input_dim))
        model.compile('sgd', 'mse')

        X = K.placeholder(ndim=2)
        Y = apply_model(model, X)
        F = theano.function([X], Y)

        x = np.random.randn(nb_samples, input_dim).astype(floatX)
        y1 = F(x)
        y2 = model.predict(x)
        # results of __call__ should match model.predict
        assert_allclose(y1, y2)

Example 42

Project: attention-lvcsr Source File: test_types.py
def test_cdata():
    if not theano.config.cxx:
        raise SkipTest("G++ not available, so we need to skip this test.")
    i = TensorType('float32', (False,))()
    c = ProdOp()(i)
    i2 = GetOp()(c)
    mode = None
    if theano.config.mode == "FAST_COMPILE":
        mode = "FAST_RUN"

    # This should be a passthrough function for vectors
    f = theano.function([i], i2, mode=mode)

    v = numpy.random.randn(9).astype('float32')

    v2 = f(v)
    assert (v2 == v).all()

Example 43

Project: GPflow Source File: test_transforms.py
    def setUp(self):
        tf.reset_default_graph()
        self.x = tf.placeholder(float_type)
        self.x_np = np.random.randn(10).astype(np_float_type)
        self.session = tf.Session()
        self.transforms = [C() for C in GPflow.transforms.Transform.__subclasses__()]
        self.transforms.append(GPflow.transforms.Logistic(7.3, 19.4))

Example 44

Project: treeano Source File: stochastic_test.py
def test_dropout_node():
    def make_network(p):
        return tn.SequentialNode("s", [
            tn.InputNode("i", shape=(3, 4, 5)),
            tn.DropoutNode("do", p=p)
        ]).network()

    x = np.random.randn(3, 4, 5).astype(fX)
    fn1 = make_network(0).function(["i"], ["s"])
    np.testing.assert_allclose(fn1(x)[0], x)

    @nt.raises(AssertionError)
    def test_not_identity():
        fn2 = make_network(0.5).function(["i"], ["s"])
        np.testing.assert_allclose(fn2(x)[0], x)

    test_not_identity()

Example 45

Project: treeano Source File: fns_test.py
def test_transform_node_data_postwalk():
    network1 = tn.InputNode("i", shape=(3, 4, 5)).network()

    def change_it_up(obj):
        if obj == (3, 4, 5):
            return (6, 7, 8)
        elif obj == "i":
            return "foo"
        else:
            return obj

    network2 = canopy.transforms.transform_node_data_postwalk(network1,
                                                              change_it_up)
    x = np.random.randn(6, 7, 8).astype(fX)
    fn = network2.function(["foo"], ["foo"])
    np.testing.assert_equal(x, fn(x)[0])

Example 46

Project: chainer Source File: test_det.py
    def det_scaling(self, gpu=False):
        scaling = numpy.random.randn(1).astype('float32')
        if gpu:
            cx = cuda.to_gpu(self.x)
            sx = cuda.to_gpu(scaling * self.x)
        else:
            cx = self.x
            sx = scaling * self.x
        c = float(scaling ** self.x.shape[1])
        cxv = chainer.Variable(cx)
        sxv = chainer.Variable(sx)
        cxd = self.det(cxv)
        sxd = self.det(sxv)
        testing.assert_allclose(cxd.data * c, sxd.data)

Example 47

Project: attention-lvcsr Source File: test_sort.py
Function: test_sort
    def test_sort(self):
        x = tensor.matrix()
        self._compile_and_check(
                [x],
                [sort(x)],
                [np.random.randn(10, 40).astype(theano.config.floatX)],
                SortOp)
        self._compile_and_check(
                [x],
                [sort(x, axis=None)],
                [np.random.randn(10, 40).astype(theano.config.floatX)],
                SortOp)

Example 48

Project: kaggle-galaxies Source File: realtime_augmentation.py
def post_augment_gaussian_noise_gen(data_gen, std=0.1):
    """
    Adds gaussian noise. Note that this is not entirely correct, the correct way would be to do it
    before downsampling, so the regular image and the rot45 image have the same noise pattern.
    But this is easier.
    """
    for target_arrays, chunk_size in data_gen:
        labels = target_arrays.pop()
        
        noise = np.random.randn(*target_arrays[0].shape).astype('float32') * std

        target_arrays = [np.clip(t + noise, 0, 1) for t in target_arrays]
        target_arrays.append(labels)

        yield target_arrays, chunk_size

Example 49

Project: treeano Source File: composite_test.py
def test_dense_combine_node():
    network = tn.SequentialNode(
        "seq",
        [tn.InputNode("in", shape=(3, 4, 5)),
         tn.DenseCombineNode("fc1", [tn.IdentityNode("i1")], num_units=6),
         tn.DenseCombineNode("fc2", [tn.IdentityNode("i2")], num_units=7),
         tn.DenseCombineNode("fc3", [tn.IdentityNode("i3")], num_units=8)]
    ).network()
    x = np.random.randn(3, 4, 5).astype(fX)
    fn = network.function(["in"], ["fc3"])
    res = fn(x)[0]
    nt.assert_equal(res.shape, (3, 8))

Example 50

Project: treeano Source File: deconv_upsample_test.py
Function: test_default_recurrent_conv_2d_node
    def test_default_recurrent_conv_2d_node():
        network = tn.SequentialNode(
            "s",
            [tn.InputNode("i", shape=(3, 4, 5, 6)),
             deconv_upsample.DeconvUpsample2DNode(
                "a",
                num_filters=7,
                upsample_factor=(2, 2),
                filter_size=(3, 3),
            )]
        ).network()
        fn = network.function(["i"], ["s"])
        res = fn(np.random.randn(3, 4, 5, 6).astype(fX))[0]
        np.testing.assert_equal((3, 7, 10, 12), res.shape)
        np.testing.assert_equal((3, 7, 10, 12),
                                network['a'].get_vw('default').shape)
See More Examples - Go to Next Page
Page 1 Selected Page 2 Page 3