简体   繁体   中英

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.

This simple modification fixed my problem:

from tensorflow.keras.optimizers import SGD

Write:

from keras.optimizers import gradient_descent_v2 

instead of:

from keras.optimizers import SGD

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.

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.

from tensorflow.keras.utils import to_categorical

It works just as well for to_categorical.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM