LoginSignup
12
1

More than 5 years have passed since last update.

Kerasメモ:AttributeError: 'Tensor' object has no attribute '_keras_history'

Last updated at Posted at 2017-12-13

動機

Kerasでモデルを組んでいる時、タイトルのエラー "AttributeError: 'Tensor' object has no attribute '_keras_history' "が出て、困りました。

解決したので、その備忘録。

エラーの原因

Kerasではモデルを組むとき、その計算過程のそれぞれがLayerオブジェクトである必要があるようです。Layerオブジェクトが持っているはずのattributeがないので、上記エラーが出るというわけです。

keras.layers以下に定義されているもの(DenseやActivationなど)を使う分には気にしなくてもいいのですが、Layerオブジェクトでないものを使ってオリジナルの計算過程を含めようとすると、上記のエラーが出ます。

例えば、以下のような場合です。意味をなさないコードですが...

from keras.models import Model
from keras.layers.core import Dense, Activation 
import keras.backend as K
from keras.activations import softmax

#疑似コードです
#backendはTensorflowです

output1 = Dense(100)(input1)
activated1 = Activation('softmax')(output1)

output2 = Dense(100)(input2)
activated2 = softmax(output2) #ダメ

concat = K.concatenate([activated1, activated2], axis=-1) # ダメ

model = Model([input1,input2], concat)
model.compile

上記のようなことをやろうとすると、ダメとコメントを入れたところでエラーが出ます。keras.backendのモジュールや、keras.activationsのモジュールを使っているためです。

解決方法 : from keras.layers import Lambda

keras.layersにLambdaというモジュールがあります。これは、任意の計算をLayerオブジェクトとして扱えるようにするためのラッパーです。

from keras.models import Model
from keras.layers.core import Dense, Activation 
from keras.layers import Lambda
import keras.backend as K
from keras.activations import softmax

#疑似コードです
#backendはTensorflowです

output1 = Dense(100)(input1)
activated1 = Activation('softmax')(output1)

output2 = Dense(100)(input2)
activated2 = Lambda(lambda x: softmax(x))(output2)

concat = Lambda(lambda x: K.concatenate([x[0], x[1]],axis=-1))([activated1, activated2])

model = Model([input1,input2], concat)
model.compile

12
1
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
12
1