使用自定义张量作为变量的TensorFlow 2.0 Keras层

丸安

在TF 1.x中,可以使用自定义变量构建图层。这是一个例子:

import numpy as np
import tensorflow as tf

def make_custom_getter(custom_variables):
    def custom_getter(getter, name, **kwargs):
        if name in custom_variables:
            variable = custom_variables[name]
        else:
            variable = getter(name, **kwargs)
        return variable
    return custom_getter

# Make a custom getter for the dense layer variables.
# Note: custom variables can result from arbitrary computation;
#       for the sake of this example, we make them just constant tensors.
custom_variables = {
    "model/dense/kernel": tf.constant(
        np.random.rand(784, 64), name="custom_kernel", dtype=tf.float32),
    "model/dense/bias": tf.constant(
        np.random.rand(64), name="custom_bias", dtype=tf.float32),
}
custom_getter = make_custom_getter(custom_variables)

# Compute hiddens using a dense layer with custom variables.
x = tf.random.normal(shape=(1, 784), name="inputs")
with tf.variable_scope("model", custom_getter=custom_getter):
    Layer = tf.layers.Dense(64)
    hiddens = Layer(x)

print(Layer.variables)

构造的密集层的打印变量将是我们在custom_variables字典中指定的自定义张量

[<tf.Tensor 'custom_kernel:0' shape=(784, 64) dtype=float32>, <tf.Tensor 'custom_bias:0' shape=(64,) dtype=float32>]

这样一来,我们就可以创建custom_variables直接使用提供的张量作为权重的图层/模型,以便我们可以进一步根据custom_variables可能依赖的任何张量来区分图层/模型的输出(特别是对于实现在调制子模块中的功能很有用网络参数生成元学习等)。

变量作用域用于简化使用自定义getter将所有图构建嵌套在作用域内的情况,并在提供的张量之上作为其参数构建模型。由于在TF 2.0中不再建议使用会话和可变作用域(并且所有这些低级内容已移至tf.compat.v1),使用Keras和TF 2.0实施上述方法的最佳实践是什么?

(有关GitHub的问题。)

丸安

以下是适用于TF2中任意Keras模型的通用解决方案。

首先,我们需要使用以下签名定义一个辅助功能canonical_variable_name和一个上下文管理器custom_make_variable(请参阅meta-blocks库中的实现)。

def canonical_variable_name(variable_name: str, outer_scope: str):
    """Returns the canonical variable name: `outer_scope/.../name`."""
    # ...

@contextlib.contextmanager
def custom_make_variable(
    canonical_custom_variables: Dict[str, tf.Tensor], outer_scope: str
):
    """A context manager that overrides `make_variable` with a custom function.

    When building layers, Keras uses `make_variable` function to create weights
    (kernels and biases for each layer). This function wraps `make_variable` with
    a closure that infers the canonical name of the variable being created (of the
    form `outer_scope/.../var_name`) and looks it up in the `custom_variables` dict
    that maps canonical names to tensors. The function adheres the following logic:

    * If there is a match, it does a few checks (shape, dtype, etc.) and returns
      the found tensor instead of creating a new variable.
    * If there is a match but checks fail, it throws an exception.
    * If there are no matching `custom_variables`, it calls the original
      `make_variable` utility function and returns a newly created variable.
    """
    # ...

使用这些函数,我们可以使用自定义张量作为变量来创建任意Keras模型:

import numpy as np
import tensorflow as tf

canonical_custom_variables = {
    "model/dense/kernel": tf.constant(
        np.random.rand(784, 64), name="custom_kernel", dtype=tf.float32),
    "model/dense/bias": tf.constant(
        np.random.rand(64), name="custom_bias", dtype=tf.float32),
}

# Compute hiddens using a dense layer with custom variables.
x = tf.random.normal(shape=(1, 784), name="inputs")
with custom_make_variable(canonical_custom_variables, outer_scope="model"):
    Layer = tf.layers.Dense(64)
    hiddens = Layer(x)

print(Layer.variables)

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

0 keras自定义层中的训练参数

如何在Tensorflow 2.x Keras自定义层中使用多个输入?

Keras自定义softmax层:是否有可能基于零作为输入层中的数据在softmax层的输出中将输出神经元设置为0?

Keras 权重文件加载异常:将 2 层加载到具有 0 层的模型中

使用tf.keras.layers.concatenate()作为Tensorflow中的自定义层

Keras自定义层:根据条件更改张量的值

我可以使用现有的操作(例如conv2d和张量操作)在python中的tensorflow中编写自定义层吗?

Keras 2上具有自定义(无)损耗的三重嵌入层

创建可计算2D DCT的Keras / Tensorflow层

Keras 2:在“合并”层中使用lambda函数

如何定义 2 个 keras 形状层的 Kronecker 产品层(无,4096)被执行?

Keras/TensorFlow 中具有 2D 输入、2D 权重和 2D 偏差的自定义密集层?

Keras:使用“输入”层时出现“发现:Tensor(“ input_1:0”,shape =(None,256,256,2),dtype = float32)“错误

ValueError:输入0与lstm_1层不兼容:预期ndim = 3,找到的ndim = 2 [keras]

语法 Keras 层定义

自定义池层-minmax池-Keras-Tensorflow

在预测期间使用来自 tensorflow hub 的 Elmo 作为自定义 tf.keras 层的问题

keras 自定义层加载数据

层之间的自定义连接Keras

Keras 中的自定义层

Tensorflow 2渴望在自定义层内禁用执行

keras自定义层中的持久变量

在Keras中使用Tensorflow层

TF2 / Keras切片张量使用[:,:,0]

使用keras自定义层时生成错误

带有keras的CNN:输入0与flatten_2层不兼容:预期的min_ndim = 3,找到的ndim = 2

keras:ValueError:输入0与层卷积不兼容2d_11:预期的ndim = 4,找到的ndim = 2

如何使用批量大小在自定义TensorFlow层中创建张量

Tensorflow 2:如何在 keras 功能 API 中使用密集层堆栈?