python - 是否可以在子类模型中使用 Tensorflow Keras 函数式 API?

标签 python tensorflow keras

我正在尝试创建一个 keras 模型,它需要对输入进行特定的预处理,然后才能被模型本身调用。我正在子类化,因为模型只是复杂网络的一部分,所以我可以连接输出并直接从代码的其他部分访问模型行为......等等。

我设计它的方式是在构造函数中使用 keras 函数式 API 链接层,如果我定义call 方法(它的行为似乎与我在调用实例时正常使用 fAPI 完全一样)。

我的问题是当我DO 想要定义call 方法时,我不确定要调用哪个函数来访问已编译模型的默认行为构造函数:

import tensorflow as tf
import numpy as np

class MyModel(tf.keras.Model):

  def __init__(self, inputshape):
    inputs = tf.keras.Input(shape=inputshape)
    x = tf.keras.layers.Dense(4, activation=tf.nn.relu)(inputs)
    outputs = tf.keras.layers.Dense(5, activation=tf.nn.softmax)(x)

    super(MyModel, self).__init__(inputs=inputs, outputs=outputs)


  def call(self, inputs, training=False):
    reduced_input = tf.expand_dims(inputs['b'], axis=0)

    # Want to call my compiled self MODEL with 'reduced_input' as the input argument but not sure how...
    return something(reduced_input)


myModelInstance = MyModel(inputshape=(3,))
myInput = {'a': [1, 2], 'b': np.array([3, 4, 5]), 'c': 6}

# Example preprocessing that I want to implement from within the model when called. Won't be this simple
reduced_input  = tf.expand_dims(myInput['b'], axis=0)

print(myModelInstance(reduced_input ))

在此代码段中,我简化了构造函数和输入预处理(此处它仅从输入中提取“b”元素并添加批处理维度),但我的实际实现更为复杂。

我希望 a) 避免在调用实例之前 预处理数据,b) 将 Model 子类化,而不是将模型存储为类属性。 p>

有没有办法像我正在尝试的那样将模型子类化与函数式 API 结合起来?

最佳答案

你应该这样做:

class MyModel(tf.keras.Model):

  def __init__(self, inputshape):
    super(MyModel, self).__init__()
    inputs = tf.keras.Input(shape=inputshape)
    x = tf.keras.layers.Dense(4, activation=tf.nn.relu)(inputs)
    outputs = tf.keras.layers.Dense(5, activation=tf.nn.softmax)(x)
    self.model = tf.keras.Model(inputs, outputs)

  def call(self, inputs, training=False):
    reduced_input = tf.expand_dims(inputs['b'], axis=0)

    # Want to call my compiled self MODEL with 'reduced_input' as the input argument but not sure how...
    return self.model(reduced_input)


myModelInstance = MyModel(inputshape=(3,))
myInput = {'a': [1, 2], 'b': np.array([3, 4, 5]), 'c': 6}

# Example preprocessing that I want to implement from within the model when called. Won't be this simple
#reduced_input  = tf.expand_dims(myInput['b'], axis=0)

print(myModelInstance(myInput))

关于python - 是否可以在子类模型中使用 Tensorflow Keras 函数式 API?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65318036/

相关文章:

python - Visual Studio 2019 中的 Jupyter Notebook 支持

python - Python Generator 抽象基类没有实现必要的 __del__,这是故意的吗?

python - 生成复合饼图或饼图饼图

python - tensorflow :如何交错两个张量的列(例如使用 tf.scatter_nd)?

python - 如何在tensorflow中查找给定.ckpt.meta文件的输出节点名称

python - KivyMD 动态选项卡管理,具有不同的 'iterations' 选项卡

python - 为什么即使批量大小为 1 也会出现内存分配错误?

keras - 关于Keras RNN输入形状要求的困惑

python - 如何在 Keras 中实现三元组损失?

python - sklearn 和 n_jobs 中的超参数优化 > 1 : Pickling