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

Viewed 68563

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.

5 Answers

This simple modification fixed my problem:

from tensorflow.keras.optimizers import SGD

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.

Write :

from keras.optimizers import gradient_descent_v2 

instead of :

from keras.optimizers import SGD

from tensorflow.keras.utils import to_categorical

It works just as well for to_categorical.

Related