Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to import SGD and Adam from 'keras.optimizers'

Trying to run---
from keras.optimizers import SGD, Adam,
I get this error---

Traceback (most recent call last):
  File "C:\Users\usn\Downloads\CNN-Image-Denoising-master ------after the stopping\CNN-Image-Denoising-master\CNN_Image_Denoising.py", line 15, in <module>
    from keras.optimizers import SGD, Adam
ImportError: cannot import name 'SGD' from 'keras.optimizers'

as well as this error, if I remove the SGD from import statement---

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

I can't find a single solution for this.
I have Keras and TensorFlow installed. I tried running the program in a virtualenv (no idea how that would help, but a guide similar to what I want mentioned it) but it still doesn't work. If anything, virtualenv makes it worse because it doesn't recognize any of the installed modules. I am using Python 3.9. Running the program in cmd because all the IDEs just create more trouble.

I am stumped. My knowledge of Python is extremely basic; I just found this thing on GitHub. Any help would be greatly appreciated.

like image 595
Sarath Amay Nair Avatar asked May 19 '21 14:05

Sarath Amay Nair


4 Answers

This simple modification fixed my problem:

from tensorflow.keras.optimizers import SGD
like image 154
Shayan Avatar answered Oct 23 '22 11:10

Shayan


Instead of :

from keras.optimizers import SGD

write :

from keras.optimizers import gradient_descent_v2

and then use it like this:

sgd = gradient_descent_v2.SGD(...)

--

To the people suggesting using

from tensorflow.keras.optimizers import SGD

it only works if you use TensorFlow throughout your whole program. If you want to use keras specifically, importing tensorflow.keras.optimizers won't work as it will conflict with other parts of your program. In this case use my solution instead.

like image 6
Богдан Холоденко Avatar answered Oct 23 '22 11:10

Богдан Холоденко


Have a look at https://github.com/tensorflow/tensorflow/issues/23728:

from tensorflow.keras.optimizers import RMSprop

instead of :

from keras.optimizers import RMSprop

It worked for me.

like image 4
George Avatar answered Oct 23 '22 10:10

George


Write :

from keras.optimizers import gradient_descent_v2 

instead of :

from keras.optimizers import SGD
like image 1
ALI Q SAEED Avatar answered Oct 23 '22 10:10

ALI Q SAEED