TypeError: __call__() takes 2 positional arguments but 4 were given

    E:/2021project/tensorflow-study-long/src/chapter04/TF05-sentiment_analysis_cell.py:77 call
        out0, state0 = self.rnn_cell0(word, state0, training)

    TypeError: __call__() takes 2 positional arguments but 4 were given

 最近学习tensorflow时,在使用 from keras import layers创建RNN,调用创建的layers时出现报

错。

最终发现的根本原因时没有从tensorflow.keras 中导入layers,才出现的问题。最好是通过tf.keras来使用keras,直接import keras 可能会出现一些问题。

代码:

class MyRNN(keras.Model):
    def __init__(self, units):
        super(MyRNN, self).__init__()
        # [b,64]:初始化为0
        self.state0 = [tf.zeros([batchsz, units])]
        self.state1 = [tf.zeros([batchsz, units])]
        # [b,80]->[b,80,100]
        self.embedding = layers.Embedding(total_words, embedding_len, input_length=max_review_len)

        # [b,80,100],h_dim=64
        self.rnn_cell0 = layers.SimpleRNNCell(units, dropout=0.2)
        self.rnn_cell1 = layers.SimpleRNNCell(units, dropout=0.2)
        # fc ,[b,80,100]=>[b,64]=>[b,1]
        self.outlayer = layers.Dense(1)

    def call(self, inputs, training=None):
        # train:net(x,training=True),net(x):train mode
        # test:net(x,training=Fasle):test mode
        # input:[b,80]
        x = inputs
        # embedding:[b,80]=>[b,80,100]
        x = self.embedding(x)
        # run cell compute
        # [b,80,100]=>[b,64]
        state0 = self.state0
        state1 = self.state1
        for word in tf.unstack(x, axis=1):  # word:[b,100]
            # h1= x* wxh + h*whh
            out0, state0 = self.rnn_cell0(word,state0,training)
            out1, state1 = self.rnn_cell1(out0, state1, training)

        # out:[b,64]=>[b,1]
        x = self.outlayer(out1)
        prob = tf.sigmoid(x)

        return prob

你可能感兴趣的:(keras,python,tensorflow)