[英]module 'tensorflow._api.v2.train' has no attribute 'GradientDescentOptimizer'
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我使用 Python 3.7.3 并安装了 tensorflow 2.0.0-alpha0,但是存在一些问题。例如模块 'tensorflow._api.v2.train' 没有属性 'GradientDescentOptimizer' 这是我所有的代码
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))
You are using Tensorflow 2.0.您正在使用 Tensorflow 2.0。 The following code will be helpful:
以下代码会有所帮助:
import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
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 .在 TensorFlow 2.0 中,Keras 成为默认的高级 API,优化器函数从
tf.keras.optimizers
迁移到名为tf.optimizers的单独 API。 They inherit from Keras class Optimizer.它们继承自 Keras 类 Optimizer。 Relevant functions from
tf.train
aren't included into TF 2.0. tf.train
中的相关函数未包含在 TF 2.0 中。 So to access GradientDescentOptimizer
, call tf.optimizers.SGD
因此,要访问
GradientDescentOptimizer
,请调用tf.optimizers.SGD
This is because you are using TensorFlow version 2.这是因为您使用的是 TensorFlow 版本 2。
`tf.train.GradientDescentOptimizer(0.5)`
The above call is for TensorFlow version 1(ex: 1.15.0).以上调用适用于 TensorFlow 版本 1(例如:1.15.0)。
You can try pip install tensorflow==1.15.0
to downgrade the TensorFlow and use the code as it is.您可以尝试
pip install tensorflow==1.15.0
来降级 TensorFlow 并按原样使用代码。
Else use the TensorFlow version 2(what you already has) with following call.否则使用 TensorFlow 版本 2(你已经拥有的)进行以下调用。
tf.optimizers.SGD (learning_rate=0.001, lr_decay=0.0, decay_step=100, staircase=False, use_locking=False, name='SGD')
For the answer @HoyeolKim gave, it may be needed to add:对于@HoyeolKim 给出的答案,可能需要补充:
tf.disable_v2_behavior()
As it is suggested in this answer.正如此答案中所建议的那样。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.