0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

keras.layers.RNN (GRU) の return_state, return_sequences

Last updated at Posted at 2023-02-17

keras.layers.RNN (GRU)の return_state, return_sequence に True を指定したときの戻り値の形を整理しておきます。

モデル

モデル作成
# 1つのデータのシーケンス数 None(後で与える), 要素数 1
inputs = keras.layers.Input(shape=(None,1))

# モデル作成時に重みが常に同じ値になるようにinitializerをセットする。
x = keras.layers.GRU(
    units=1,
    return_state=False,      # 最終状態を返す
    return_sequences=False,  # 入力シーケンスの個々の出力値を返す。
    kernel_initializer="ones",
    recurrent_initializer="ones",
    use_bias=False,
  )(inputs)
model = keras.models.Model(inputs=inputs,outputs=x)
model.summary()

# データ2つ、1つのデータのシーケンス2で要素数1
input_x = [ [[0],[1]], [[0],[-1]] ]
output_y = model.predict(input_x)
print(type(output_y))
print(output_y)

GRUで作成しています。SimpleRNNでも基本は同じです。LSTMの場合は内部状態が増えます。

入出力

入力データは2つあります。1つのデータは2つのシーケンスで、1つのシーケンスは1要素でできています。

return_state=False, return_sequences=False で実行した結果が一番上の黄色のものです。モデルの出力の要素数は 1 なので、データ1つに対して1つの出力が返ってきています。

return_state=Trueの場合、緑のデータの最終状態が追加されます。arrayと記述されているのは、pythonのリストの中にnumpyのarrayが入っているからです。

return_sequences=Trueの場合、青のデータが追加されます。青のデータは、入力シーケンスごとの出力です。今回の入力データはシーケンス数が2なので青と黄色と合わせて1データにつき2つになっています。

最後に両方をTrueにすると、戻り値の1つ目がシーケンスの出力が追加されたもの、2つ目が最終状態のものとなります。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?