python - 以自定义张量作为变量的 TensorFlow 2.0 Keras 层

标签 python tensorflow keras tensorflow2.0

在 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 可能取决于(对于在 modulating sub-netsparameter generationmeta-learning 等中实现功能特别有用)。

变量作用域用于使用自定义 getter 轻松嵌套所有图形构建内部作用域,并在提供的张量之上构建模型作为它们的参数。由于在 TF 2.0 中不再建议使用 session 和变量范围(并且所有这些低级内容都移至 tf.compat.v1),最佳实践 使用 Keras 和 TF 2.0 实现上述内容?

(相关 issue on GitHub .)

最佳答案

根据下面的评论回答

假设你有:

kernel = createTheKernelVarBasedOnWhatYouWant() #shape (784, 64)
bias = createTheBiasVarBasedOnWhatYouWant() #shape (64,)

复制Dense中的代码制作一个简单的函数:

def custom_dense(x):
    inputs, kernel, bias = x

    outputs = K.dot(inputs, kernel)
    outputs = K.bias_add(outputs, bias, data_format='channels_last')
    return outputs

Lambda 层中使用函数:

layer = Lambda(custom_dense)
hiddens = layer([x, kernel, bias])

Warning: kernel and bias must be produced from a Keras layer, or come from an kernel = Input(tensor=the_kernel_var) and bias = Input(tensor=bias_var)


如果上面的警告对您不利,您始终可以“从外部”使用 kernelbias,例如:

def custom_dense(inputs):
    outputs = K.dot(inputs, kernel) #where kernel is not part of the arguments anymore
    outputs = K.bias_add(outputs, bias, data_format='channels_last')
    return outputs

layer = Lambda(custom_dense)
hiddens = layer(x)

最后一个选项使保存/加载模型变得有点复杂。

旧答案

您可能应该使用 Keras Dense 层并以标准方式设置其权重:

layer = tf.keras.layers.Dense(64, name='the_layer')
layer.set_weights([np.random.rand(784, 64), np.random.rand(64)])

如果你需要这些权重是不可训练的,在编译你设置的keras模型之前:

model.get_layer('the_layer').trainable=False

如果您想直接访问变量作为张量,它们是:

kernel = layer.kernel    
bias = layer.bias

还有很多其他选项,但这取决于您的确切意图,这在您的问题中并不清楚。

关于python - 以自定义张量作为变量的 TensorFlow 2.0 Keras 层,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58275253/

相关文章:

python - 加速django嵌套for循环时间序列

python - 如何使用 opencv - python 标记中心并计算图像的直径?

python - 再训练最后一层 Inception-ResNet-v2

python - tensorflow 1.14+ : dockerized task based flask api doesn't run and or stalls?

python - 在没有互联网连接的情况下安装tensorflow

python - 在python中,为什么我不能以简单的方式继承pandas.Series?

python - 如何使用非分隔符 Pandas 将索引拆分为多索引

python - 'RefVariable' 对象没有属性 '_id'

python - Tensorflow 2.0 无法识别张量形状

python - 如何将 Lambda 层作为输入层添加到 Keras 中的现有模型中?