I am new to tensorflow.
Have tried this simple example:
import tensorflow as tf
sess = tf.Session()
x = tf.placeholder(tf.float32)
y = tf.placeholder(tf.float32)
z = x + y
print(sess.run(z, feed_dict={x: 3.0, y: 4.5}))
and got some warnings The name tf.Session is deprecated. Please use tf.compat.v1.Session instead. and the right answer - 7.5
After reading here, I understand that the warnings are due to upgrading from tf 1.x to 2.0, the steps described are "simple" but they don't give any example....
I have tried:
#tf.function
def f1(x1, y1):
return tf.math.add(x1, y1)
print(f1(tf.constant(3.0), tf.constant(4.5)))
Is my code correct (in the sense defined in the link)?
Now, I am getting Tensor("PartitionedCall:0", shape=(), dtype=float32) as output, how can I get the actual value?
You code is indeed correct. The warning that you get indicates that as from Tensorflow 2.0, tf.Session() won't exist in the API. Therefore, if you want you code to be compatible with Tensorflow 2.0, you should use tf.compat.v1.Session instead. So, just change this line:
sess = tf.Session()
To:
sess = tf.compat.v1.Session()
Then, even if you update Tensorflow from 1.xx to 2.xx, your code would execute in the same way. As for the code in Tensorflow 2.0:
#tf.function
def f1(x1, y1):
return tf.math.add(x1, y1)
print(f1(tf.constant(3.0), tf.constant(4.5)))
it is fine if you run it in Tensorflow 2.0. If you want to run the same code, without installing Tensorflow 2.0, you can do the following:
import tensorflow as tf
tf.enable_eager_execution()
#tf.function
def f1(x1, y1):
return tf.math.add(x1, y1)
print(f1(tf.constant(3.0), tf.constant(4.5)).numpy())
The reason for this is because the default way of executing Tensorflow operations starting from Tensorflow 2.0 is in eager mode. The way of activating eager mode in Tensorflow 1.xx, is to enable it right after the import of Tensorflow, as I am doing it in the example above.
Your code is correct as per Tensorflow 2.0. Tensorflow 2.0 is even more tightly bonded with numpy so if you want to get the result of the operation, you could use the numpy() method:
print(f1(tf.constant(3.0), tf.constant(4.5)).numpy())
Related
I am receiving different errors when trying to print a TensorFlow object.
import numpy as np
import tensorflow as tf
The versions of both TensorFlow and numpy are 2.6 and 1.19.5, respectively.
print("np version:", np.__version__)
print("tf version:" ,tf.version.VERSION)
print("eager is on? ", tf.executing_eagerly())
#np version: 1.19.5
#tf version: 2.6.0
#eager is on? True
Now, let me create a small array and turn it into a tf object.
arr= [0,1.2,-0.8]
arr = tf.constant(arr, dtype = tf.float32)
When I use tf.print or tf.compat.v1.print(arr), nothing happens. When I call numpy, I do receive an error.
tf.compat.v1.print(arr.numpy())
AttributeError: 'Tensor' object has no attribute 'numpy'
The only thing that has worked so far is ;
with tf.compat.v1.Session() as sess: print(arr.eval())
#[ 0. 1.2 -0.8]
However, I would like to use numpy since my goal is to print certain features of the network during the traning phase. For instance, if I want to print the learning rate, I call with tf.compat.v1.Session() as sess: print(model.optimizer.learning_rate.eval()) . Yet, it returns me another error.
'ExponentialDecay' object has no attribute 'eval'
I was able to use numpy to print everything before, however, I updated both TensorFlow and numpy packages and now am facing so many incompatibilities. The worst thing is that I don't remember which versions I was using.
I followed every step explainedd in this post
AttributeError: 'Tensor' object has no attribute 'numpy'. It did not help me.
Following code gives me an output -
import numpy as np
import tensorflow as tf
print("np version:", np.__version__)
print("tf version:" ,tf.version.VERSION)
print("eager is on? ", tf.executing_eagerly())
tf.enable_eager_execution()
arr= [0,1.2,-0.8]
arr = tf.constant(arr, dtype = tf.float32)
tf.compat.v1.print(arr.numpy())
Output: array([ 0. , 1.2, -0.8], dtype=float32)
Did you add tf.enable_eager_execution() ?
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))
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
You are using Tensorflow 2.0.
The following code will be helpful:
import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
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')
For the answer #HoyeolKim gave, it may be needed to add:
tf.disable_v2_behavior()
As it is suggested in this answer.
I want to use tf.print to show tensor value, but it has no result?
This is my code and is there something wrong for that:
from __future__ import print_function
import tensorflow as tf
sess = tf.InteractiveSession()
a = tf.constant([1.0, 3.0])
tf.print(a)
From the documentation of tf.Print - that's deprecated and suggests to use tf.print:
Note that tf.print returns a no-output operator that directly prints the output. Outside of defuns or eager mode, this operator will not be executed unless it is directly specified in session.run or used as a control dependency for other operators.
This is only a concern in graph mode. Below is an example of how to ensure tf.print executes in graph mode:
sess = tf.Session()
with sess.as_default():
tensor = tf.range(10)
print_op = tf.print(tensor)
with tf.control_dependencies([print_op]):
out = tf.add(tensor, tensor)
sess.run(out)
Hence, if you enable the eager mode your code will work as you expected, if you want to continue using the static-graph mode you have to use sess.run
import tensorflow as tf
a = tf.constant([1.0, 3.0])
init_op = tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init_op)
print(sess.run(a))
is what I'd do. Import tensorflow, set up your variables, set up and run the initializer for them, and then print the session evaluating the constant
I have a code as follows:
import tensorflow as tf
a = tf.constant([1,2,3])
with tf.Session() as sess:
print('12')
print(sess.run(a))
However, I get results
12
[1 2 3]
when I run the code. It seems the sess does not close automatically. Can someone explain how it happens? Thanks.
I can reproduce it with tensorflow 1.7.
This has been fixed in version 1.8 of tensorflow.
I am working on tensorflow 0.12 and am having problem with casting.
The following snippet of code does a strange thing:
sess = tf.InteractiveSession()
a = tf.constant(1)
b = tf.cast(a, tf.float32)
print b.eval()
I get a value:
6.86574233e-36
I also tried using tf.to_float() and tf.saturate_cast. Both gave the same result.
Please help.
sess = tf.InteractiveSession()
a = tf.constant(1, tf.int64) <--------
b = tf.cast(a, tf.float32)
print b.eval() # 1.0
You need to declare the dtype for your tf.constant: https://www.tensorflow.org/api_docs/python/tf/constant
Since I see that this is still getting some attention, I should mention that the newer versions of tensorflow do not show this behavior, I suggest working with tensorflow version 1.13 or higher
I checked the code in python3 and python2 for the same tensorflow version as well the code seems to be working correctly as in both the cases I got the following output for python2
print b.eval()
1.0
I would suggest checking the tensorflow installation or the virtualenv.
No error in your program.
import tensorflow as tf
sess = tf.InteractiveSession()
a = tf.constant(1)
b = tf.cast(a, tf.float32)
print b.eval()
This is an online environment for TF https://codeenv.com/env/run/gXGpnR/
Test your code there to run, use
click on test_tf.py
add your code
in left side CLI, type ipython test_tf.py