本文整理汇总了Python中tensorflow.Operation方法的典型用法代码示例。如果您正苦于以下问题:Python tensorflow.Operation方法的具体用法?Python tensorflow.Operation怎么用?Python tensorflow.Operation使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类tensorflow
的用法示例。
在下文中一共展示了tensorflow.Operation方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: get_op
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import Operation [as 别名]
def get_op(tfobj_or_name, graph):
"""
Get a :py:class:`tf.Operation` object.
:param tfobj_or_name: either a :py:class:`tf.Tensor`, :py:class:`tf.Operation` or
a name to either.
:param graph: a :py:class:`tf.Graph` object containing the operation.
By default the graph we don't require this argument to be provided.
"""
graph = validated_graph(graph)
_assert_same_graph(tfobj_or_name, graph)
if isinstance(tfobj_or_name, tf.Operation):
return tfobj_or_name
name = tfobj_or_name
if isinstance(tfobj_or_name, tf.Tensor):
name = tfobj_or_name.name
if not isinstance(name, six.string_types):
raise TypeError('invalid op request for [type {}] {}'.format(type(name), name))
_op_name = op_name(name, graph=None)
op = graph.get_operation_by_name(_op_name) # pylint: disable=invalid-name
err_msg = 'cannot locate op {} in the current graph, got [type {}] {}'
assert isinstance(op, tf.Operation), err_msg.format(_op_name, type(op), op)
return op
示例2: get_tensor
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import Operation [as 别名]
def get_tensor(tfobj_or_name, graph):
"""
Get a :py:class:`tf.Tensor` object
:param tfobj_or_name: either a :py:class:`tf.Tensor`, :py:class:`tf.Operation` or
a name to either.
:param graph: a :py:class:`tf.Graph` object containing the tensor.
By default the graph we don't require this argument to be provided.
"""
graph = validated_graph(graph)
_assert_same_graph(tfobj_or_name, graph)
if isinstance(tfobj_or_name, tf.Tensor):
return tfobj_or_name
name = tfobj_or_name
if isinstance(tfobj_or_name, tf.Operation):
name = tfobj_or_name.name
if not isinstance(name, six.string_types):
raise TypeError('invalid tensor request for {} of {}'.format(name, type(name)))
_tensor_name = tensor_name(name, graph=None)
tnsr = graph.get_tensor_by_name(_tensor_name)
err_msg = 'cannot locate tensor {} in the current graph, got [type {}] {}'
assert isinstance(tnsr, tf.Tensor), err_msg.format(_tensor_name, type(tnsr), tnsr)
return tnsr
示例3: __init__
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import Operation [as 别名]
def __init__(self, inputs, outputs, updates, givens):
"""
Theano like function
:param inputs: (TensorFlow Tensor or Object with make_feed_dict) list of input arguments
:param outputs: (TensorFlow Tensor) list of outputs or a single output to be returned from function. Returned
value will also have the same shape.
:param updates: ([tf.Operation] or tf.Operation)
list of update functions or single update function that will be run whenever
the function is called. The return is ignored.
:param givens: (dict) the values known for the output
"""
for inpt in inputs:
if not hasattr(inpt, 'make_feed_dict') and not (isinstance(inpt, tf.Tensor) and len(inpt.op.inputs) == 0):
assert False, "inputs should all be placeholders, constants, or have a make_feed_dict method"
self.inputs = inputs
updates = updates or []
self.update_group = tf.group(*updates)
self.outputs_update = list(outputs) + [self.update_group]
self.givens = {} if givens is None else givens
示例4: get_train_op
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import Operation [as 别名]
def get_train_op(self, model_results: ModelResults) -> tf.Operation:
"""
Create train operation using optimization handler. Also will add the
update operation to it
Parameters
----------
model_results
model results
Returns
-------
train_with_update_op
train operation together with update operation
"""
with tf.variable_scope(ScopeNames.TRAIN_OP):
train_op = self.optimization_handler.get_train_op(
model_results.grads_and_vars,
model_results.regularization_grads_and_vars,
trainable_variables=self.model.trainable_variables)
update_op = self._get_update_op()
train_with_update_op = tf.group(
train_op, update_op, name='train_op')
return train_with_update_op
示例5: matmul_resources
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import Operation [as 别名]
def matmul_resources(self, op):
"""
checks which one of the direct ancestor tf.Operations is a constant and returns the underlying tensor as a numpy.ndarray inside a tuple. The matrix is manipulated in a way that it can be
used as the left multiplier in the matrix multiplication.
Arguments
---------
op : tf.Operation
must have type "MatMul"
Return
------
output : tuple
tuple with the matrix (of type numpy.ndarray) as its only item
"""
inputs = op.inputs
left = inputs[0]
right = inputs[1]
if left.op.type == "Const":
matrix = self.sess.run(left) if not op.get_attr("transpose_a") else self.sess.run(left).transpose()
else:
matrix = self.sess.run(right).transpose() if not op.get_attr("transpose_b") else self.sess.run(right)
return (matrix,)
示例6: add_resources
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import Operation [as 别名]
def add_resources(self, op):
"""
checks which one of the direct ancestor tf.Operations is a constant and returns the underlying tensor as a numpy.ndarray inside a tuple.
Arguments
---------
op : tf.Operation
must have type "Add"
Return
------
output : tuple
tuple with the addend (of type numpy.ndarray) as its only item
"""
inputs = op.inputs
left = inputs[0]
right = inputs[1]
if left.op.type == "Const":
addend = self.sess.run(left)
else:
addend = self.sess.run(right)
return (addend,)
示例7: conv2d_resources
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import Operation [as 别名]
def conv2d_resources(self, op):
"""
Extracts the filter, the stride of the filter, and the padding from op as well as the shape of the input coming into op
Arguments
---------
op : tf.Operation
must have type "Conv2D"
Return
------
output : tuple
has 4 entries (numpy.ndarray, numpy.ndarray, numpy.ndarray, str)
"""
inputs = op.inputs
image = inputs[0]
filters = op.inputs[1]
filters = self.sess.run(filters)
image_shape = tensorshape_to_intlist(image.shape)[1:]
strides = op.get_attr('strides')[1:3]
padding_str = op.get_attr('padding').decode('utf-8')
pad_top, pad_left = calculate_padding(padding_str, image_shape, filters.shape, strides)
return filters, image_shape, strides, pad_top, pad_left
示例8: pool_resources
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import Operation [as 别名]
def pool_resources(self, op):
"""
Extracts the incoming image size (heigth, width, channels), the size of the maxpool/averagepool window (heigth, width), and the strides of the window (heigth, width)
Arguments
---------
op : tf.Operation
must have type "MaxPool" or "AvgPool"
Return
------
output : tuple
has 4 entries - (list, numpy.ndarray, numpy.ndarray, str)
"""
image = op.inputs[0]
image_shape = tensorshape_to_intlist(image.shape)[1:]
window_size = op.get_attr('ksize')[1:3]
strides = op.get_attr('strides')[1:3]
padding_str = op.get_attr('padding').decode('utf-8')
pad_top, pad_left = calculate_padding(padding_str, image_shape, window_size, strides)
return image_shape, window_size, strides, pad_top, pad_left
示例9: _to_names
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import Operation [as 别名]
def _to_names(self, graph_item):
# Base cases
if isinstance(graph_item, tf.Tensor):
return ('Tensor', graph_item.name)
if isinstance(graph_item, tf.Operation):
return ('Operation', graph_item.name)
if isinstance(graph_item, tf.Variable):
return ('Variable', graph_item.op.name)
if isinstance(graph_item, (bool, str, int, float)) or graph_item is None:
return graph_item
# Handle different containers
if isinstance(graph_item, (list, tuple, np.ndarray)):
return type(graph_item)([self._to_names(item) for item in graph_item])
if isinstance(graph_item, (dict, Config)):
return type(graph_item)({key: self._to_names(graph_item[key]) for key in graph_item.keys()})
raise ValueError('Unrecognized type of value.')
示例10: _to_graph_items
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import Operation [as 别名]
def _to_graph_items(self, name):
# Base cases
if isinstance(name, (bool, str, int, float)) or name is None:
return name
# Handle different containers
if isinstance(name, (list, tuple, np.ndarray)):
if len(name) == 2:
type_, name_ = name
if type_ == 'Variable':
with self.graph.as_default():
return tf.global_variables(name_)[0]
if type_ == 'Tensor':
return self.graph.get_tensor_by_name(name_)
if type_ == 'Operation':
return self.graph.get_operation_by_name(name_)
return type(name)([self._to_graph_items(item) for item in name])
if isinstance(name, (dict, Config)):
return type(name)({key: self._to_graph_items(name[key]) for key in name.keys()})
raise ValueError('Unrecognized type of value.')
示例11: minimize
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import Operation [as 别名]
def minimize(self, loss):
"""Create an optimizer to minimize the model loss
Parameters
----------
loss: tf.Tensor
Node which needs to be evaluated for computing the model loss.
Returns
-------
train: tf.Operation
Node that needs to be evaluated for minimizing the loss during training
"""
self.optimizer = tf.train.AdagradOptimizer(learning_rate=self._optimizer_params['lr'])
train = self.optimizer.minimize(loss)
return train
示例12: testTrainingConstructionClassificationSparse
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import Operation [as 别名]
def testTrainingConstructionClassificationSparse(self):
input_data = tf.SparseTensor(
indices=[[0, 0], [0, 3],
[1, 0], [1, 7],
[2, 1],
[3, 9]],
values=[-1.0, 0.0,
-1., 2.,
1.,
-2.0],
shape=[4, 10])
input_labels = [0, 1, 2, 3]
params = tensor_forest.ForestHParams(
num_classes=4, num_features=10, num_trees=10, max_nodes=1000,
split_after_samples=25).fill()
graph_builder = tensor_forest.RandomForestGraphs(params)
graph = graph_builder.training_graph(input_data, input_labels)
self.assertTrue(isinstance(graph, tf.Operation))
示例13: tf_num_params
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import Operation [as 别名]
def tf_num_params(x):
"""Number of parameters in a TensorFlow subgraph.
Args:
x: root of the subgraph (Tensor, Operation)
Returns:
Total number of elements found in all Variables
in the subgraph.
"""
if isinstance(x, tf.Tensor):
shape = x.get_shape()
x = x.op
if x.type == "Variable":
return shape.num_elements()
totals = [tf_num_params(y) for y in x.inputs]
return sum(totals)
示例14: tf_left_split
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import Operation [as 别名]
def tf_left_split(op):
"""Split the parameters of op for left recursion.
Args:
op: tf.Operation
Returns:
A tuple of the leftmost input tensor and a list of the
remaining arguments.
"""
if len(op.inputs) < 1:
return None, []
if op.type == "Concat":
return op.inputs[1], op.inputs[2:]
return op.inputs[0], op.inputs[1:]
示例15: tf_parameter_iter
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import Operation [as 别名]
def tf_parameter_iter(x):
"""Iterate over the left branches of a graph and yield sizes.
Args:
x: root of the subgraph (Tensor, Operation)
Yields:
A triple of name, number of params, and shape.
"""
while 1:
if isinstance(x, tf.Tensor):
shape = x.get_shape().as_list()
x = x.op
else:
shape = ""
left, right = tf_left_split(x)
totals = [tf_num_params(y) for y in right]
total = sum(totals)
yield x.name, total, shape
if left is None: break
x = left