Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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))
like image 737
qy235806 Avatar asked Apr 15 '19 04:04

qy235806


3 Answers

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

import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
like image 172
Hoyeol Kim Avatar answered Oct 31 '22 07:10

Hoyeol Kim


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

like image 17
Sharky Avatar answered Oct 31 '22 06:10

Sharky


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')
like image 1
Gihan Gamage Avatar answered Oct 31 '22 07:10

Gihan Gamage