[英]Is it possible to use the Tensorflow Keras functional API within a subclassed Model?
我正在尝试创建一个 keras Model 需要对输入进行特殊预处理,然后才能被 model 本身调用。 我将子类化为 model 只是复杂网络的一部分,因此我可以连接输出并直接从我的代码的其他部分访问 model 行为......等等。
我设计它的方式是在构造函数中使用 keras 功能 API 来链接层,如果我没有定义call
方法,这可以正常工作(它的行为似乎与我调用实例时正常使用 fAPI 完全一样)。
我的问题是当我确实想定义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 ))
在这个片段中,我简化了构造函数以及输入预处理(这里它只从输入中提取“b”元素并添加一个批处理维度),但我的实际实现更复杂。
我更喜欢 a) 在调用实例之前避免预处理数据,b) 将Model
子类化,而不是将 model 存储为 class 属性。
有没有办法将 Model 子类化与功能 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))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.