4
3

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.optimizersから読み込む最適化手法のエラーについて

Last updated at Posted at 2022-05-25

画像分類に取り組んでいる際にkeras.optimizersの読み込みでエラーが出たので調べてみた。

環境

google colaboratory
Python 3.7.13
Keras 2.8.0

エラー内容

Adam
import keras
from keras.optimizers import Adam

# エラーコード----------------------------------------------------------------------------
---------------------------------------------------------------------------
ImportError                               Traceback (most recent call last)
<ipython-input-6-7e4e00d780ab> in <module>()
     1 import keras
---> 2 from keras.optimizers import Adam

ImportError: cannot import name 'Adam' from 'keras.optimizers' (/usr/local/lib/python3.7/dist-packages/keras/optimizers.py)

アップデートでkeras 2.5.0から読み込み方が変わったそう。
新しい読み込みは以下のとおり

修正後

adam_v2
# 修正前
from keras.optimizers import Adam

# 修正後
from keras.optimizers import adam_v2

また、compileで使う際には以下のようにしてAdamを指定する。

# 修正前
model.compile(loss='categorical_crossentropy',
              optimizer=Adam(learning_rate=0.001),
              metrics=['accuracy']) 

# 修正後
model.compile(loss='categorical_crossentropy',
              optimizer=adam_v2.Adam(learning_rate=0.001),
              metrics=['accuracy']) 

# オプティマイザを名前で指定すると,デフォルトパラメータが利用される
model.compile(loss='categorical_crossentropy',
              optimizer="Adam",
              metrics=['accuracy']) 

その他のoptimizerやパラメータの中身については、Kerasのドキュメントを参照。

4
3
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
4
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?