Esempio n. 1
0
def test_composed_param():
    param1 = Parameter('param1', 1.)
    param2 = Parameter('param2', 2.)
    param3 = Parameter('param3', 3., floating=False)
    param4 = Parameter(
        'param4', 4.
    )  # noqa Needed to make sure it does not only take all params as deps

    def value_fn(p1, p2, p3):
        return z.math.log(3. * p1) * tf.square(p2) - p3

    param_a = ComposedParameter('param_as',
                                value_fn=value_fn,
                                params=(param1, param2, param3))
    param_a2 = ComposedParameter(
        'param_as2',
        value_fn=value_fn,
        params={f'p{i}': p
                for i, p in enumerate((param1, param2, param3))})
    assert param_a2.params['p1'] == param2
    assert isinstance(param_a.get_cache_deps(only_floating=True), OrderedSet)
    assert param_a.get_cache_deps(only_floating=True) == {param1, param2}
    assert param_a.get_cache_deps(only_floating=False) == {
        param1, param2, param3
    }
    a_unchanged = value_fn(param1, param2, param3).numpy()
    assert a_unchanged == param_a.numpy()
    assert param2.assign(3.5).numpy()
    a_changed = value_fn(param1, param2, param3).numpy()
    assert a_changed == param_a.numpy()
    assert a_changed != a_unchanged
Esempio n. 2
0
def test_composed_param():
    param1 = Parameter("param1", 1.0)
    param2 = Parameter("param2", 2.0)
    param3 = Parameter("param3", 3.0, floating=False)
    param4 = Parameter(
        "param4", 4.0
    )  # noqa Needed to make sure it does not only take all params as deps

    def value_fn(p1, p2, p3):
        return z.math.log(3.0 * p1) * tf.square(p2) - p3

    param_a = ComposedParameter("param_as",
                                value_fn=value_fn,
                                params=(param1, param2, param3))
    param_a2 = ComposedParameter(
        "param_as2",
        value_fn=value_fn,
        params={f"p{i}": p
                for i, p in enumerate((param1, param2, param3))},
    )
    assert param_a2.params["p1"] == param2
    assert isinstance(param_a.get_cache_deps(only_floating=True), OrderedSet)
    assert param_a.get_cache_deps(only_floating=True) == {param1, param2}
    assert param_a.get_cache_deps(only_floating=False) == {
        param1, param2, param3
    }
    a_unchanged = value_fn(param1, param2, param3).numpy()
    assert a_unchanged == param_a.numpy()
    param2.assign(3.5)
    assert param2.numpy()
    a_changed = value_fn(param1, param2, param3).numpy()
    assert a_changed == param_a.numpy()
    assert a_changed != a_unchanged

    print(param_a)

    @z.function
    def print_param(p):
        print(p)

    print_param(param_a)