简体   繁体   中英

error : module 'tensorflow._api.v2.train' has no attribute 'GradientDescentOptimizer' what is the solution

import tensorflow as tf
# the equation is  : 4x+2 = 0
unknownvalue = tf.Variable(0.0)

a = tf.constant(4.0)
b = tf.constant(2.0)
c = tf.multiply(unknownvalue,a)  # 4x
equation  = tf.add(c,b) # 4x+2
zerovalue = tf.constant(0.0)
diff = tf.square(equation-zerovalue) # differnce is : 4x+2  -  0 
solving = tf.train.GradientDescentOptimizer(0.01).minimize(diff)
init = tf.global_variables_initializer()
tf.print(init)
for n in range(1000):
    tf.print(solving)

The code was written in the new version from his tensorflow library The program does not run because of this error and it is AttributeError: module 'tensorflow._api.v2.train' has no attribute 'GradientDescentOptimizer' What is the solution?

tensorflow 2 has the gradient descent located in keras.optimizers, change it to this: tf.keras.optimizers.SGD().minimize(var_list=diff)

Packages have been moved around and reorganized.

Here is a link that will show you the changes that you need to make in order to transition your code from using tensorflow 1 to tensorflow 2: link

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