Sarath Amay Nair
Sarath Amay Nair

Reputation: 173

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.

Upvotes: 17

Views: 89484

Answers (5)

Teddy
Teddy

Reputation: 1

from tensorflow.keras.utils import to_categorical

It works just as well for to_categorical.

Upvotes: 0

Bohdan Kholodenko
Bohdan Kholodenko

Reputation: 101

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.

Upvotes: 7

ALI Q SAEED
ALI Q SAEED

Reputation: 521

Write :

from keras.optimizers import gradient_descent_v2 

instead of :

from keras.optimizers import SGD

Upvotes: 1

Shayan
Shayan

Reputation: 599

This simple modification fixed my problem:

from tensorflow.keras.optimizers import SGD

Upvotes: 49

George
George

Reputation: 113

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.

Upvotes: 4

Related Questions