本文整理汇总了Python中tensorflow.compat.v1.InteractiveSession方法的典型用法代码示例。如果您正苦于以下问题:Python v1.InteractiveSession方法的具体用法?Python v1.InteractiveSession怎么用?Python v1.InteractiveSession使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类tensorflow.compat.v1
的用法示例。
在下文中一共展示了v1.InteractiveSession方法的7个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _load_frozen_graph
# 需要导入模块: from tensorflow.compat import v1 [as 别名]
# 或者: from tensorflow.compat.v1 import InteractiveSession [as 别名]
def _load_frozen_graph(self, frozen_graph_path):
frozen_graph = tf.GraphDef()
with open(frozen_graph_path, 'rb') as f:
frozen_graph.ParseFromString(f.read())
self.graph = tf.Graph()
with self.graph.as_default():
self.output_node = tf.import_graph_def(
frozen_graph, return_elements=[
'probabilities:0',
])
self.session = tf.InteractiveSession(graph=self.graph)
tf_probabilities = self.graph.get_tensor_by_name('import/probabilities:0')
self._output_nodes = [tf_probabilities]
self.sliding_window = None
self.frames_since_last_inference = self.config.inference_rate
self.last_annotations = []
示例2: _load_frozen_graph
# 需要导入模块: from tensorflow.compat import v1 [as 别名]
# 或者: from tensorflow.compat.v1 import InteractiveSession [as 别名]
def _load_frozen_graph(self, frozen_graph_path):
trt_graph = tf.GraphDef()
with open(frozen_graph_path, 'rb') as f:
trt_graph.ParseFromString(f.read())
self._is_lstm = self._check_lstm(trt_graph)
if self._is_lstm:
print('Loading an LSTM model.')
self.graph = tf.Graph()
with self.graph.as_default():
self.output_node = tf.import_graph_def(
trt_graph,
return_elements=[
'detection_boxes:0', 'detection_classes:0', 'detection_scores:0',
'num_detections:0'
] + (['raw_outputs/lstm_c:0', 'raw_outputs/lstm_h:0']
if self._is_lstm else []))
self.session = tf.InteractiveSession(graph=self.graph)
tf_scores = self.graph.get_tensor_by_name('import/detection_scores:0')
tf_boxes = self.graph.get_tensor_by_name('import/detection_boxes:0')
tf_classes = self.graph.get_tensor_by_name('import/detection_classes:0')
tf_num_detections = self.graph.get_tensor_by_name('import/num_detections:0')
if self._is_lstm:
tf_lstm_c = self.graph.get_tensor_by_name('import/raw_outputs/lstm_c:0')
tf_lstm_h = self.graph.get_tensor_by_name('import/raw_outputs/lstm_h:0')
self._output_nodes = [tf_scores, tf_boxes, tf_classes, tf_num_detections
] + ([tf_lstm_c, tf_lstm_h] if self._is_lstm else [])
if self._is_lstm:
self.lstm_c = np.ones((1, 8, 8, 320))
self.lstm_h = np.ones((1, 8, 8, 320))
示例3: trainer
# 需要导入模块: from tensorflow.compat import v1 [as 别名]
# 或者: from tensorflow.compat.v1 import InteractiveSession [as 别名]
def trainer(model_params):
"""Train a sketch-rnn model."""
np.set_printoptions(precision=8, edgeitems=6, linewidth=200, suppress=True)
tf.logging.info('sketch-rnn')
tf.logging.info('Hyperparams:')
tf.logging.info('Loading data files.')
datasets = load_dataset(FLAGS.data_dir, model_params)
train_set = datasets[0]
valid_set = datasets[1]
test_set = datasets[2]
model_params = datasets[3]
eval_model_params = datasets[4]
reset_graph()
model = sketch_rnn_model.Model(model_params)
eval_model = sketch_rnn_model.Model(eval_model_params, reuse=True)
sess = tf.InteractiveSession()
sess.run(tf.global_variables_initializer())
if FLAGS.resume_training:
load_checkpoint(sess, FLAGS.log_root)
# Write config file to json file.
tf.gfile.MakeDirs(FLAGS.log_root)
with tf.gfile.Open(
os.path.join(FLAGS.log_root, 'model_config.json'), 'w') as f:
json.dump(list(model_params.values()), f, indent=True)
train(sess, model, eval_model, train_set, valid_set, test_set)
示例4: make_session
# 需要导入模块: from tensorflow.compat import v1 [as 别名]
# 或者: from tensorflow.compat.v1 import InteractiveSession [as 别名]
def make_session(config=None, num_cpu=None, make_default=False, graph=None):
"""Returns a session that will use <num_cpu> CPU's only"""
if num_cpu is None:
num_cpu = int(os.getenv('RCALL_NUM_CPU', multiprocessing.cpu_count()))
if config is None:
config = tf.ConfigProto(
allow_soft_placement=True,
inter_op_parallelism_threads=num_cpu,
intra_op_parallelism_threads=num_cpu)
config.gpu_options.allow_growth = True
if make_default:
return tf.InteractiveSession(config=config, graph=graph)
else:
return tf.Session(config=config, graph=graph)
示例5: _fit
# 需要导入模块: from tensorflow.compat import v1 [as 别名]
# 或者: from tensorflow.compat.v1 import InteractiveSession [as 别名]
def _fit(self, X, weights, log_coincidence,
vocab=None,
initial_embedding_dict=None,
fixed_initialization=None):
if fixed_initialization is not None:
raise AttributeError("Tensorflow version of Mittens does "
"not support specifying initializations.")
# Start the session:
tf.reset_default_graph()
self.sess = tf.InteractiveSession()
# Build the computation graph.
self._build_graph(vocab, initial_embedding_dict)
# Optimizer set-up:
self.cost = self._get_cost_function()
self.optimizer = self._get_optimizer()
# Set up logging for Tensorboard
if self.log_dir:
n_subdirs = len(os.listdir(self.log_dir))
subdir = self.log_subdir or str(n_subdirs + 1)
directory = os.path.join(self.log_dir, subdir)
log_writer = tf.summary.FileWriter(directory, flush_secs=1)
# Run training
self.sess.run(tf.global_variables_initializer())
if self.test_mode:
self.W_start = self.sess.run(self.W)
self.C_start = self.sess.run(self.C)
self.bw_start = self.sess.run(self.bw)
self.bc_start = self.sess.run(self.bc)
merged_logs = tf.summary.merge_all()
for i in range(1, self.max_iter+1):
_, loss, stats = self.sess.run(
[self.optimizer, self.cost, merged_logs],
feed_dict={
self.weights: weights,
self.log_coincidence: log_coincidence})
# Keep track of losses
if self.log_dir and i % 10 == 0:
log_writer.add_summary(stats)
self.errors.append(loss)
if loss < self.tol:
# Quit early if tolerance is met
self._progressbar("stopping with loss < self.tol", i)
break
else:
self._progressbar("loss: {}".format(loss), i)
# Return the sum of the two learned matrices, as recommended
# in the paper:
return self.sess.run(tf.add(self.W, self.C))
示例6: test
# 需要导入模块: from tensorflow.compat import v1 [as 别名]
# 或者: from tensorflow.compat.v1 import InteractiveSession [as 别名]
def test(sess, network, acc, X_test, y_test, x, y_, batch_size, cost=None):
"""
Test a given non time-series network by the given test data and metric.
Parameters
----------
sess : TensorFlow session
sess = tf.InteractiveSession()
network : a TensorLayer layer
the network will be trained
acc : the TensorFlow expression of accuracy (or other metric) or None
if None, would not display the metric
X_test : numpy array
the input of test data
y_test : numpy array
the target of test data
x : placeholder
for inputs
y_ : placeholder
for targets
batch_size : int or None
batch size for testing, when dataset is large, we should use minibatche for testing.
when dataset is small, we can set it to None.
cost : the TensorFlow expression of cost or None
if None, would not display the cost
Examples
--------
>>> see tutorial_mnist_simple.py
>>> tl.utils.test(sess, network, acc, X_test, y_test, x, y_, batch_size=None, cost=cost)
"""
print('Start testing the network ...')
if batch_size is None:
dp_dict = dict_to_one( network.all_drop )
feed_dict = {x: X_test, y_: y_test}
feed_dict.update(dp_dict)
if cost is not None:
print(" test loss: %f" % sess.run(cost, feed_dict=feed_dict))
print(" test acc: %f" % sess.run(acc, feed_dict=feed_dict))
# print(" test acc: %f" % np.mean(y_test == sess.run(y_op,
# feed_dict=feed_dict)))
else:
test_loss, test_acc, n_batch = 0, 0, 0
for X_test_a, y_test_a in iterate.minibatches(
X_test, y_test, batch_size, shuffle=True):
dp_dict = dict_to_one( network.all_drop ) # disable noise layers
feed_dict = {x: X_test_a, y_: y_test_a}
feed_dict.update(dp_dict)
if cost is not None:
err, ac = sess.run([cost, acc], feed_dict=feed_dict)
test_loss += err
else:
ac = sess.run(acc, feed_dict=feed_dict)
test_acc += ac; n_batch += 1
if cost is not None:
print(" test loss: %f" % (test_loss/ n_batch))
print(" test acc: %f" % (test_acc/ n_batch))
示例7: predict
# 需要导入模块: from tensorflow.compat import v1 [as 别名]
# 或者: from tensorflow.compat.v1 import InteractiveSession [as 别名]
def predict(sess, network, X, x, y_op, batch_size=None):
"""
Return the predict results of given non time-series network.
Parameters
----------
sess : TensorFlow session
sess = tf.InteractiveSession()
network : a TensorLayer layer
the network will be trained
X : numpy array
the input
x : placeholder
for inputs
y_op : placeholder
the argmax expression of softmax outputs
batch_size : int or None
batch size for prediction, when dataset is large, we should use minibatche for prediction.
when dataset is small, we can set it to None.
Examples
--------
>>> see tutorial_mnist_simple.py
>>> y = network.outputs
>>> y_op = tf.argmax(tf.nn.softmax(y), 1)
>>> print(tl.utils.predict(sess, network, X_test, x, y_op))
"""
if batch_size is None:
dp_dict = dict_to_one( network.all_drop ) # disable noise layers
feed_dict = {x: X,}
feed_dict.update(dp_dict)
return sess.run(y_op, feed_dict=feed_dict)
else:
result = None
for X_a, _ in iterate.minibatches(
X, X, batch_size, shuffle=False):
dp_dict = dict_to_one( network.all_drop )
feed_dict = {x: X_a, }
feed_dict.update(dp_dict)
result_a = sess.run(y_op, feed_dict=feed_dict)
if result is None:
result = result_a
else:
result = np.hstack((result, result_a))
return result
## Evaluation