from __future__ import absolute_import, division, print_function
import numpy as np
import tensorflow as tf
print(tf.__version__)
sess_config = tf.ConfigProto(gpu_options=tf.GPUOptions(allow_growth=True))
1.12.0
a = tf.add(3, 5)
print(a)
Tensor("Add:0", shape=(), dtype=int32)
sess = tf.Session(config = sess_config)
print(sess.run(a))
sess.close()
8
with tf.Session(config = sess_config) as sess:
print(a)
print(sess.run(a))
Tensor("Add:0", shape=(), dtype=int32) 8
print(tf.get_default_graph().get_operations())
[<tf.Operation 'Add/x' type=Const>, <tf.Operation 'Add/y' type=Const>, <tf.Operation 'Add' type=Add>]
tf.reset_default_graph()
x, y = 2, 3
add_op = tf.add(x,y)
mul_op = tf.multiply(x,y)
useless = tf.multiply(x, add_op)
pow_op = tf.pow(add_op, mul_op)
with tf.Session(config = sess_config) as sess:
z, not_useless = sess.run([pow_op, useless])
print(z, not_useless)
15625 10
print(tf.get_default_graph().get_operations())
[<tf.Operation 'Add/x' type=Const>, <tf.Operation 'Add/y' type=Const>, <tf.Operation 'Add' type=Add>, <tf.Operation 'Mul/x' type=Const>, <tf.Operation 'Mul/y' type=Const>, <tf.Operation 'Mul' type=Mul>, <tf.Operation 'Mul_1/x' type=Const>, <tf.Operation 'Mul_1' type=Mul>, <tf.Operation 'Pow' type=Pow>]
tf.reset_default_graph()
g = tf.Graph()
with g.as_default():
x = tf.add(3,5)
with tf.Session(config = sess_config) as sess: # graph argument is none -> launch default graph
print(sess.run(x))
--------------------------------------------------------------------------- RuntimeError Traceback (most recent call last) <ipython-input-8-3cb1b3c3e0e6> in <module> 5 x = tf.add(3,5) 6 with tf.Session(config = sess_config) as sess: # graph argument is none -> launch default graph ----> 7 print(sess.run(x)) /usr/local/var/pyenv/versions/3.6.6/envs/tensorflow/lib/python3.6/site-packages/tensorflow/python/client/session.py in run(self, fetches, feed_dict, options, run_metadata) 927 try: 928 result = self._run(None, fetches, feed_dict, options_ptr, --> 929 run_metadata_ptr) 930 if run_metadata: 931 proto_data = tf_session.TF_GetBuffer(run_metadata_ptr) /usr/local/var/pyenv/versions/3.6.6/envs/tensorflow/lib/python3.6/site-packages/tensorflow/python/client/session.py in _run(self, handle, fetches, feed_dict, options, run_metadata) 1075 raise RuntimeError('Attempted to use a closed Session.') 1076 if self.graph.version == 0: -> 1077 raise RuntimeError('The Session graph is empty. Add operations to the ' 1078 'graph before calling run().') 1079 RuntimeError: The Session graph is empty. Add operations to the graph before calling run().
print(g.get_operations())
[<tf.Operation 'Add/x' type=Const>, <tf.Operation 'Add/y' type=Const>, <tf.Operation 'Add' type=Add>]
print(tf.get_default_graph().get_operations())
[]