【问题标题】:Python issue with subclassing and keras子类化和 keras 的 Python 问题
【发布时间】:2020-04-01 02:12:12
【问题描述】:

我正在使用实验室笔记本来编写一些开放式课程笔记。 其中一个练习是创建一个新类 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))

我应该共同调用 IndentityModel 的调用方法。 这就是问题所在。

IdentityModel.call(x_input, False)

改为调用 tf.keras.Model.call

IdentityModel.call(x_input, isidentity=False) 

有错误 TypeError: call() missing 1 required positional argument: 'inputs'

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

有错误 TypeError: call() missing 1 required positional argument: 'self'

这里发生了什么?我以前使用过类似的代码,没有这些问题。

【问题讨论】:

    标签: python class inheritance keras


    【解决方案1】:

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

    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) 
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-10-20
      • 1970-01-01
      • 1970-01-01
      • 2016-09-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-14
      相关资源
      最近更新 更多