How to set optimizer in tensorflow 2.4.1

I follow a code to learn image classification. However, this code uses a structure with the optimizer in the compile function:

optimizer=optimizers.Adam(lr=lr)

But I obtain an error:

File "C:\Users\jucar\PycharmProjects\AIRecProject\Scode.py", line 69, in <module>
optimizer=optimizers.Adam(lr=lr),NameError: name 'optimizers' is not defined

I changed the structure following a similar solution of this problem with:

optimizer='adam'(lr=lr)

But this error is presented:

File "C:\Users\jucar\PycharmProjects\AIRecProject\Scode.py", line 69, in <module>
optimizer='adam'(lr=lr),TypeError: 'str' object is not callable

I was looking for the information available on Keras and TensorFlow, and this information is provided

tf.keras.optimizers.Adam(
learning_rate=0.001, beta_1=0.9, beta_2=0.999, epsilon=1e-07, amsgrad=False,
name='Adam', **kwargs

)

Therefore I use this:

from tensorflow.python.keras import optimizers as opt

and later:

opt = opt(learning_rate=0.001, gradient_aggregator=None, gradient_transformers=None)

SD.compile(loss='categorical_crossentropy',
        optimizer=opt,
        metrics=['accuracy'])

With this error:

File "C:\Users\jucar\PycharmProjects\AIRecProject\Scode.py", line 67, in <module>
opt = opt(learning_rate=0.001)TypeError: 'module' object is not callable

And I changed to:

opt = opt.Adam(learning_rate=0.001)

Obtaining this error:

File "C:\Users\jucar\PycharmProjects\AIRecProject\Scode.py", line 67, in <module>
opt = opt.Adam(learning_rate=0.001)
AttributeError: module 'tensorflow.python.keras.optimizers' has no attribute 'Adam'

How I can solve this issue?

Upvotes: 2

Views: 13944

Answers (2)

user1543042
user1543042

Reputation: 3440

Try this

import tensorflow as tf
opt = tf.keras.optimizers.Adam(learning_rate=0.001)

You had it as tensorflow.python

Upvotes: 4

Abhilash Rajan
Abhilash Rajan

Reputation: 349

The easiest option is to use optimizer='adam'. For more details, visit: https://keras.io/api/optimizers/

Upvotes: 0

Related Questions