Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ImportError: cannot import name 'adam' from 'keras.optimizers'

Tags:

I am trying to import Keras but I get the following error:

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

The import is invoked here:

from tensorflow import keras from keras.layers import Conv2D, Input, MaxPool2D,Flatten, Dense, Permute, GlobalAveragePooling2D from keras.models import Model from keras.optimizers import adam import numpy as np import pickle import keras import cv2 import sys import dlib import os.path from keras.models import Sequential from keras.applications.resnet50 import ResNet50 from keras.applications.resnet50 import Dense from keras.optimizers import Adam import pickle import numpy as np import cv2 import os from keras.layers import Dropout 

I am sure Keras is installed along with Tensorflow:

python3 -c 'import keras; print(keras.__version__)' // 2.4.3 
like image 697
dclipca Avatar asked Jul 03 '20 02:07

dclipca


2 Answers

There are two types of modules -

  1. keras
  2. tensorflow.keras

Here we need to use tensorflow.keras

You need to import Adam (With Capital A) from tensorflow - Keras ( Not only Keras).

from tensorflow.keras.optimizers import Adam  from tensorflow.keras.optimizers import Adam # - Works from tensorflow.keras.optimizers import adam # - Does not work from keras.optimizers import Adam            # - Does not work from keras.optimizers import adam            # - Does not work 
like image 180
Anurag Sundaram Avatar answered Sep 28 '22 04:09

Anurag Sundaram


recently, in the latest update of Keras API 2.5.0 , importing Adam optimizer shows the following error:

from keras.optimizers import Adam ImportError: cannot import name 'Adam' from 'keras.optimizers'  

instead use the following for importing optimizers (i.e. Adam) :

from keras.optimizers import adam_v2 optimizer = adam_v2.Adam(learning_rate=lr, decay=lr/epochs) Model.compile(loss='--',  optimizer=optimizer  , metrics=['--']) 

for more details, please have a look at : https://programmerah.com/keras-nightly-import-package-error-cannot-import-name-adam-from-keras-optimizers-29815/

hopefully, this helps.

like image 40
ALI Q SAEED Avatar answered Sep 28 '22 05:09

ALI Q SAEED