简体   繁体   中英

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

Trying to run---

import tensorflow as tf
from tensorflow import keras

from tensorflow.python.keras.models import Sequential
from tensorflow.python.keras.layers import Flatten, Dense
from tensorflow.python.keras.optimizers import SGD, Adam

import numpy as np

print(tf.__version__)

I get this error---

---------------------------------------------------------------------------
ImportError                               Traceback (most recent call last)
<ipython-input-8-f05f8f753c47> in <module>()
      4 from tensorflow.python.keras.models import Sequential
      5 from tensorflow.python.keras.layers import Flatten, Dense
----> 6 from tensorflow.python.keras.optimizers import SGD, Adam
      7 
      8 import numpy as np

ImportError: cannot import name 'SGD' from 'tensorflow.python.keras.optimizers' (/usr/local/lib/python3.7/dist-packages/tensorflow/python/keras/optimizers.py)

---------------------------------------------------------------------------
NOTE: If your import is failing due to a missing package, you can
manually install dependencies using either !pip or !apt.

---------------------------------------------------------------------------

I'm studying machine learning in Google Colab. I pasted the example code and run it, and get error message.

I could find similar errors in Google, but I couldn't find anything to solve this problem.

I tried 'from tensorflow.keras.optimizers import SGD, Adam', 'from tf.keras.optimizers import SGD, Adam', and 'from keras.optimizers import SGD, Adam'. But everything didn't work.

尝试这个:

from tensorflow.python.keras.optimizer_v1 import SGD

You need to mention the exact updated alias name while importing the model( Sequential ),layers ( Flatten , Dense ) and optimizers ( SGD , Adam ).

Please try again using the below code in new Google Colab notebook.

import tensorflow as tf
from tensorflow import keras

from tensorflow.keras.models import Sequential  #removed python from each layer
from tensorflow.keras.layers import Flatten, Dense
from tensorflow.keras.optimizers import SGD, Adam

import numpy as np

print(tf.__version__)

Output:

2.8.2

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