Python的子类化和keras问题

2024-05-29 02:45:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在用实验笔记本做一些开放式课程笔记。 其中一个练习是创建一个新类IdentityModel,该类继承自tensorflow.keras.Model,并具有自己的方法“call(inputs,isidentity=False)”。 这应该是一个简单的练习。下面是代码的解释,导入是从他们的单元格复制的

# Import relevant packages
import tensorflow as tf
from tensorflow.keras import Sequential
from tensorflow.keras.layers import Dense

from tensorflow.keras import Model
from tensorflow.keras.layers import Dense
import numpy as np
import matplotlib.pyplot as plt

class IdentityModel(tf.keras.Model):

  # As before, in __init__ we define the Model's layers
  # Since our desired behavior involves the forward pass, this part is unchanged
  def __init__(self, n_output_nodes):
    super(IdentityModel, self).__init__()
    self.dense_layer = tf.keras.layers.Dense(n_output_nodes, activation='sigmoid')


  def call(self, inputs, isidentity=False):
    x = self.dense_layer(inputs)
    if isidentity:
      return inputs
    else:
      return x

n_output_nodes = 3
model = IdentityModel(n_output_nodes)
x_input = tf.constant([[1,2.]], shape=(1,2))

我应该共同调用IdentityModel的调用方法。 这里是出问题的地方

IdentityModel.call(x_input, False)

改为调用tf.keras.Model.call

IdentityModel.call(x_input, isidentity=False) 

错误类型为error:call()缺少1个必需的位置参数:“inputs”

IdentityModel.call(input=x_input, isidentity=False) 

错误类型错误:call()缺少1个必需的位置参数:“self”

这是怎么回事?我以前使用过类似的代码,但没有这些问题


Tags: fromimportselffalseinputoutputmodellayers
1条回答
网友
1楼 · 发布于 2024-05-29 02:45:32

这些是实例方法,因此需要从生成的实例而不是类调用它

n_output_nodes = 3
x_input = tf.constant([[1,2.]], shape=(1,2))

instance = IdentityModel(n_output_nodes)

# Call any of the following
instance.call(x_input)
instance.call(x_input, False)
instance.call(x_input, isidentity=False) 
instance.call(input=x_input, isidentity=False) 

相关问题 更多 >

    热门问题