简体   繁体   English

是否可以在子类 ZA559B87068921EEC05086CE584 中使用 Tensorflow Keras 功能 API

[英]Is it possible to use the Tensorflow Keras functional API within a subclassed Model?

I'm trying to create a keras Model that needs particular preprocessing on the inputs before it can be called by the model itself.我正在尝试创建一个 keras Model 需要对输入进行特殊预处理,然后才能被 model 本身调用。 I'm subclassing as the model is only part of a complex network so I can concatenate outputs and directly access model behaviour from other parts of my code...etc.我将子类化为 model 只是复杂网络的一部分,因此我可以连接输出并直接从我的代码的其他部分访问 model 行为......等等。

The way I've designed it is using the keras functional API in the constructor to chain the layers which works fine if I DON'T define the call method (it seems to behave exactly as if I used the fAPI normally when I call the instance).我设计它的方式是在构造函数中使用 keras 功能 API 来链接层,如果我没有定义call方法,这可以正常工作(它的行为似乎与我调用实例时正常使用 fAPI 完全一样)。

My problem is when I DO want to define the call method, where I'm not sure what function to call to access the default behaviour of the compiled model from the constructor:我的问题是当我确实想定义call方法时,我不确定要调用什么function以从构造函数访问已编译 model 的默认行为:

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 ))

In this snippet I've simplified the constructor as well as the input preprocessing (here it extracts only the 'b' element from the input and adds a batch dimension) but my actual implementation is more complex.在这个片段中,我简化了构造函数以及输入预处理(这里它只从输入中提取“b”元素并添加一个批处理维度),但我的实际实现更复杂。

I'd prefer a) to avoid preprocessing the data before calling the instance and b) to subclass Model instead of storing the model as a class attribute.我更喜欢 a) 在调用实例之前避免预处理数据,b) 将Model子类化,而不是将 model 存储为 class 属性。

Is there a way to combine Model subclassing with the functional API as I'm trying to do?有没有办法将 Model 子类化与功能 API 结合起来,就像我正在尝试做的那样?

You should do this way:你应该这样做:

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))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 TensorFlow model 到 Keras 功能 API? - TensorFlow model to Keras functional API? 使用Keras Functional API为Tensorflow LITE建立模型 - Build a model with Keras Functional API for Tensorflow LITE Tensorflow Keras功能API模型可以训练Tensorflow变量吗? 可以在功能性API模型中使用Tensorflow操作吗? - Can a Tensorflow variable be trained using the Tensorflow Keras functional API model? Can a Tensorflow operation be used in the functional API Model? Keras 功能 API 和 TensorFlow 集线器 - Keras functional API and TensorFlow Hub 如何在keras子类化模型中使用回调? - How to use callbacks in keras subclassed model? 是否可以在没有输入层的 Keras 功能 API 中创建 model ? - Is it possible to create a model in Keras Functional API without an input layer? 将 Keras-Fuctional-API 转换为 Keras 子类 Model - Convert Keras-Fuctional-API into a Keras Subclassed Model 训练使用 tensorflow.keras.Model 和 keras 函数式 API 设计的网络会导致 Python 崩溃 - Training a Network designed using tensorflow.keras.Model and the keras functional API causes Python crash 为什么在构建Keras模型时同时使用顺序API和功能API? - Why use both Sequential and Functional API when building a Keras model? 获取中间层(Functional API)的output并在SubClassed中使用API - Obtain the output of intermediate layer (Functional API) and use it in SubClassed API
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM