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.
Related
Hello guys I am using Tensorflow 2.0
and in these lines of code:
import tensorflow as tf
hello = tf.constant('Hello World')
sess = tf.compat.v1.Session()
sess.run(hello) <-- Error in this line
RuntimeError: The Session graph is empty. Add operations to the graph
before calling run().
Any idea on how to solve it?
ok guys I found the way:
g = tf.Graph()
with g.as_default():
# Define operations and tensors in `g`.
hello = tf.constant('hello')
assert hello.graph is g
sess = tf.compat.v1.Session(graph=g)
sess.run(hello)
b'hello'
thank you for your time!
Tensorflow core r2.0 have enabled eager execution by default. so, without changing it we just have to change our code as like as below by Launch the graph in a session.
> with tf.compat.v1.Session() as sess:
> # Building a graph
> hello = tf.constant("hello")
> print(sess.run(hello))
According to the Tensorflow doc..
A default Graph is always registered, and accessible by calling
tf.compat.v1.get_default_graph
For this basic operations not required to declare a tf.Graph() , you can define a graph which has more computations and dataset you can define a graph and invoke into the session.
Please Refer: For More informations
https://www.tensorflow.org/api_docs/python/tf/Graph
https://github.com/OlafenwaMoses/ImageAI/issues/400
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())
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.
Since updating to tensoflow version 1.0 which introduced the new Saver V2, tf does not delete old files any more with the 'max_to_keep' argument. This is a problem on my system since my models are pretty big but my free space is limited.
Using the dummy program below I end up with following files for every number from 1 to 10 while I only expect the last 3 (8,9,10) to actually be there.
testfile-1.data-00000-of-00001
testfile-1.index
testfile-1.meta
program:
import tensorflow as tf
a = tf.Variable(name='a', initial_value=0)
addops = a+1
saver = tf.train.Saver(max_to_keep=3)
config = tf.ConfigProto()
config.gpu_options.allow_growth = True
sess = tf.Session(config=config)
sess.run(tf.global_variables_initializer())
for i in range(10):
sess.run(addops)
save_path = saver.save(sess, 'testfile', global_step=i+1)
sess.close()
Is this just me or this a known bug?
What are possible problems which could lead to this misbehavior?
Is there any log or smth similar I could get more information from?
I can reproduce this. It seems to be a bug.
However the problem is gone once I save into a different location (different from the executed .py file path)
save_path = saver.save(sess, 'data/testfile', global_step=i+1)
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