pythontensorflowkerasanacondasgd

Anaconda: ValueError: Could not interpret optimizer identifier


I try to run this code:

from keras.models import Sequential
from keras.layers import Dense, Activation
from keras.optimizers import SGD

and I get this error:

ImportError: cannot import name 'SGD' from 'keras.optimizers' (C:\Users\user\AppData\Roaming\Python\Python38\site-packages\keras\optimizers.py)

Earlier when I was trying to learn keras with python, I did not encounter this problem, but later I encountered other errors. After I updated all the plugins and reinstalled anaconda3, I encountered this problem.

I changed the code content by referring to the information I found, and there is no error afterwards.

from keras.models import Sequential
from keras.layers import Dense, Activation
from tensorflow.keras.optimizers import SGD

But later I encountered the following error:

model.compile(loss='mse', optimizer=SGD(lr=0.1),
             metrics=['accuracy'])

ValueError: Could not interpret optimizer identifier: <tensorflow.python.keras.optimizer_v2.gradient_descent.SGD object at 0x0000023987198520>

Are the above 2 questions related to connectivity? Where is the error of from keras.optimizers import SGD? model.compile(loss='mse', optimizer=SGD(lr=0.1),metrics=['accuracy']) How should I modify it?

Please know that the seniors helped to point out the problem and the solution, thank you.


Solution

  • If you want to use anything from tf.keras (e.g. SGD) you should consistently use everything from tf.keras. I.e. tf.keras.models and tf.keras.layers

    This is the recommendation for TF2. Please see: https://www.tensorflow.org/tutorials/quickstart/beginner