module 'tensorflow._api.v2.train' has no attribute 'GradientDescentOptimizer'

≡放荡痞女 提交于 2020-12-01 09:36:19

问题


I used Python 3.7.3 and installed tensorflow 2.0.0-alpha0,But there are some problems。such as module 'tensorflow._api.v2.train' has no attribute 'GradientDescentOptimizer' Here's all my code

import  tensorflow as tf
import  numpy as np

x_data=np.random.rand(1,10).astype(np.float32)
y_data=x_data*0.1+0.3


Weights = tf.Variable(tf.random.uniform([1], -1.0, 1.0))
biases = tf.Variable(tf.zeros([1]))
y=Weights*x_data+biases

loss=tf.reduce_mean(tf.square(y-y_data))

optimizer=tf.train.GradientDescentOptimizer(0.5)
train=optimizer.minimize(loss)

init = tf.global_variables_initializer()  

sess = tf.Session()
sess.run(init)          

for step in range(201):
    sess.run(train)
    if step % 20 == 0:
        print(step, sess.run(Weights), sess.run(biases))

回答1:


In TensorFlow 2.0, Keras became the default high-level API, and optimizer functions migrated from tf.keras.optimizers into separate API called tf.optimizers. They inherit from Keras class Optimizer. Relevant functions from tf.train aren't included into TF 2.0. So to access GradientDescentOptimizer, call tf.optimizers.SGD




回答2:


You are using Tensorflow 2.0. The following code will be helpful:

import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()



回答3:


This is because you are using TensorFlow version 2.

`tf.train.GradientDescentOptimizer(0.5)`

The above call is for TensorFlow version 1(ex : 1.15.0).

You can try pip install tensorflow==1.15.0 to downgrade the TensorFlow and use the code as it is.

Else use the TensorFlow version 2(what you already has) with following call.

tf.optimizers.SGD (learning_rate=0.001, lr_decay=0.0, decay_step=100, staircase=False, use_locking=False, name='SGD')



回答4:


For the answer @HoyeolKim gave, it may be needed to add:

tf.disable_v2_behavior()

As it is suggested in this answer.



来源:https://stackoverflow.com/questions/55682718/module-tensorflow-api-v2-train-has-no-attribute-gradientdescentoptimizer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!