本文整理汇总了Python中tensorflow.is_tensor方法的典型用法代码示例。如果您正苦于以下问题:Python tensorflow.is_tensor方法的具体用法?Python tensorflow.is_tensor怎么用?Python tensorflow.is_tensor使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类tensorflow
的用法示例。
在下文中一共展示了tensorflow.is_tensor方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _convert_to_binary_classification_predictions
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import is_tensor [as 别名]
def _convert_to_binary_classification_predictions(predictions):
"""Converts a `Tensor` into a set of binary classification predictions.
This function checks that the given `Tensor` is floating-point, and that it is
trivially convertible to rank-1, i.e. has only one "nontrivial" dimension
(e.g. the shapes [1000] and [1, 1, None, 1] are allowed, but [None, 1, None]
and [50, 10] are not). If it satisfies these conditions, then it is reshaped
to be rank-1 (if necessary) and returned.
Args:
predictions: a rank-1 floating-point `Tensor` of predictions.
Returns:
The predictions `Tensor`, reshaped to be rank-1, if necessary.
Raises:
TypeError: if "predictions" is not a floating-point `Tensor`.
ValueError: if "predictions" is not trivially convertible to rank-1.
"""
if not tf.is_tensor(predictions):
raise TypeError("predictions must be a Tensor")
if not predictions.dtype.is_floating:
raise TypeError("predictions must be floating-point")
return helpers.convert_to_1d_tensor(predictions, name="predictions")
示例2: __init__
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import is_tensor [as 别名]
def __init__(self, value, auto_cast):
"""Creates a new `_StaticExplicitDeferredTensorState`.
Args:
value: `Tensor`-like, the value of the `DeferredTensor`.
auto_cast: `Boolean`, whether the value should be automatically
type-promoted, if necessary. Only applies if "value" is a `Tensor`:
non-`Tensor` types are always auto-castable.
"""
assert not callable(value)
self._value = value
self._auto_cast = auto_cast
# For non-Tensor types, we make a deep copy to make extra-certain that it is
# immutable (since we'll hash it).
if not tf.is_tensor(self._value):
self._value = copy.deepcopy(self._value)
# We memoize the hash, since it can be expensive to compute.
self._hash = None
示例3: __eq__
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import is_tensor [as 别名]
def __eq__(self, other):
if not isinstance(other, _StaticExplicitDeferredTensorState):
return False
if self.auto_cast != other.auto_cast:
return False
# If at least one of the objects is a Tensor, then we check that they're the
# same object, instead of calling __eq__.
#
# In eager mode, we could potentially check for value-equality, by using the
# np.array_equal() code below after *explicitly* casting the Tensors to
# numpy arrays by calling Tensor.numpy(). This would probably be a bad idea,
# though, since if the Tensor is actually a tf.Variable, its value could
# change in the future.
if tf.is_tensor(self.value) or tf.is_tensor(other.value):
return self.value is other.value
# Every other allowed type can be handled by numpy.
#
# We can hope that in most cases, this will be quick (e.g. same object -->
# equal, different shapes --> unequal), but if we're unlucky, this has the
# potential to be slow.
return np.array_equal(self.value, other.value)
示例4: __init__
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import is_tensor [as 别名]
def __init__(self, bits=8, stochastic=True):
"""Initializer for the PerChannelUniformQuantizationEncodingStage.
Args:
bits: The number of bits to quantize to. Must be an integer between 1 and
16. Can be either a TensorFlow or a Python value.
stochastic: A Python bool, whether to use stochastic or deterministic
rounding. If `True`, the encoding is randomized and on expectation
unbiased. If `False`, the encoding is deterministic.
Raises:
ValueError: The inputs do not satisfy the above constraints.
"""
if (not tf.is_tensor(bits) and bits not in self._ALLOWED_BITS_ARG):
raise ValueError('The bits argument must be an integer between 1 and 16.')
self._bits = bits
if not isinstance(stochastic, bool):
raise TypeError('The stochastic argument must be a bool.')
self._stochastic = stochastic
示例5: static_or_dynamic_shape
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import is_tensor [as 别名]
def static_or_dynamic_shape(value):
"""Returns shape of the input `Tensor` or a `np.ndarray`.
If `value` is a `np.ndarray` or a `Tensor` with statically known shape, it
returns a Python object. Otherwise, returns result of `tf.shape(value)`.
Args:
value: A `Tensor` or a `np.ndarray` object.
Returns:
Static or dynamic shape of `value`.
Raises:
TypeError:
If the input is not a `Tensor` or a `np.ndarray` object.
"""
if tf.is_tensor(value):
return value.shape if value.shape.is_fully_defined() else tf.shape(value)
elif isinstance(value, np.ndarray):
return value.shape
else:
raise TypeError('The provided input is not a Tensor or numpy array.')
示例6: maybe_evaluate
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import is_tensor [as 别名]
def maybe_evaluate(self, fetches, session=None):
"""Evaluates `fetches`, if containing any `Tensor` objects.
Args:
fetches: Any nested structure compatible with `tf.nest`.
session: Optional. A `tf.Session` object in the context of which the
evaluation is to happen.
Returns:
`fetches` with any `Tensor` objects replaced by numpy values.
"""
if any((tf.is_tensor(t) for t in tf.nest.flatten(fetches))):
if session:
fetches = session.run(fetches)
else:
fetches = self.evaluate(fetches)
return fetches
示例7: _decode_after_sum_impl
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import is_tensor [as 别名]
def _decode_after_sum_impl(self, encoded_tensors, decode_params, num_summands,
shape):
"""Implementation for the `decode_after_sum` method."""
if not self.stage.commutes_with_sum:
# This should have been decoded earlier in the decode_before_sum method.
assert tf.is_tensor(encoded_tensors)
return encoded_tensors
temp_encoded_tensors = {}
for key, value in six.iteritems(encoded_tensors):
if key in self.children:
with tf.compat.v1.name_scope(None, '/'.join([self.stage.name, key])):
temp_encoded_tensors[key] = self.children[key]._decode_after_sum_impl( # pylint: disable=protected-access
value, decode_params[EncoderKeys.CHILDREN][key], num_summands,
shape[EncoderKeys.CHILDREN][key])
else:
temp_encoded_tensors[key] = value
return self.stage.decode(temp_encoded_tensors,
decode_params[EncoderKeys.PARAMS],
num_summands=num_summands,
shape=shape[EncoderKeys.SHAPE])
示例8: _detokenize
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import is_tensor [as 别名]
def _detokenize(self, tokens, sequence_length):
if isinstance(tokens, tf.RaggedTensor):
rank = len(tokens.shape)
if rank == 1:
return self._detokenize_tensor(tokens.values)
elif rank == 2:
return self._detokenize_ragged_tensor(tokens)
else:
raise ValueError("Unsupported RaggedTensor rank %d for detokenization" % rank)
elif tf.is_tensor(tokens):
rank = len(tokens.shape)
if rank == 1:
return self._detokenize_tensor(tokens)
elif rank == 2:
if sequence_length is None:
raise ValueError("sequence_length is required for Tensor detokenization")
return self._detokenize_batch_tensor(tokens, sequence_length)
else:
raise ValueError("Unsupported tensor rank %d for detokenization" % rank)
elif isinstance(tokens, list) and tokens and isinstance(tokens[0], list):
return list(map(self.detokenize, tokens))
else:
tokens = [tf.compat.as_text(token) for token in tokens]
return self._detokenize_string(tokens)
示例9: assert_state_is_compatible
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import is_tensor [as 别名]
def assert_state_is_compatible(expected_state, state):
"""Asserts that states are compatible.
Args:
expected_state: The reference state.
state: The state that must be compatible with :obj:`expected_state`.
Raises:
ValueError: if the states are incompatible.
"""
# Check structure compatibility.
tf.nest.assert_same_structure(expected_state, state)
# Check shape compatibility.
expected_state_flat = tf.nest.flatten(expected_state)
state_flat = tf.nest.flatten(state)
for x, y in zip(expected_state_flat, state_flat):
if tf.is_tensor(x):
expected_depth = x.shape[-1]
depth = y.shape[-1]
if depth != expected_depth:
raise ValueError("Tensor in state has shape %s which is incompatible "
"with the target shape %s" % (y.shape, x.shape))
示例10: is_scalar
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import is_tensor [as 别名]
def is_scalar(tensor):
"""Returns True iff the given tensor is a scalar.
Args:
tensor: The tensor to test for being a scalar.
Returns:
True if 'tensor' is a scalar, i.e. all dims are 1, False otherwise.
Raises:
TypeError: when the argument is not a tensor.
"""
if not tf.is_tensor(tensor):
raise TypeError('Expected a tensor, found "{}".'.format(
py_typecheck.type_string(type(tensor))))
return (hasattr(tensor, 'get_shape') and
all(dim == 1 for dim in tensor.get_shape()))
示例11: state_aegmm
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import is_tensor [as 别名]
def state_aegmm(od: OutlierAEGMM) -> Dict:
"""
OutlierAEGMM parameters to save.
Parameters
----------
od
Outlier detector object.
"""
if not all(tf.is_tensor(_) for _ in [od.phi, od.mu, od.cov, od.L, od.log_det_cov]):
logger.warning('Saving AEGMM detector that has not been fit.')
state_dict = {'threshold': od.threshold,
'n_gmm': od.aegmm.n_gmm,
'recon_features': od.aegmm.recon_features,
'phi': od.phi,
'mu': od.mu,
'cov': od.cov,
'L': od.L,
'log_det_cov': od.log_det_cov}
return state_dict
示例12: state_vaegmm
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import is_tensor [as 别名]
def state_vaegmm(od: OutlierVAEGMM) -> Dict:
"""
OutlierVAEGMM parameters to save.
Parameters
----------
od
Outlier detector object.
"""
if not all(tf.is_tensor(_) for _ in [od.phi, od.mu, od.cov, od.L, od.log_det_cov]):
logger.warning('Saving VAEGMM detector that has not been fit.')
state_dict = {'threshold': od.threshold,
'samples': od.samples,
'n_gmm': od.vaegmm.n_gmm,
'latent_dim': od.vaegmm.latent_dim,
'beta': od.vaegmm.beta,
'recon_features': od.vaegmm.recon_features,
'phi': od.phi,
'mu': od.mu,
'cov': od.cov,
'L': od.L,
'log_det_cov': od.log_det_cov}
return state_dict
示例13: run
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import is_tensor [as 别名]
def run(self, tensor, feed_dict=None):
"""Evaluates the given `Tensor`.
Unlike `tf.Session.run()`, this method expects a single `Tensor` argument
(i.e. not a list of `Tensor`s or any other more complex structure).
Args:
tensor: the `Tensor` to evaluate, or a nullary function returning a
`Tensor`.
feed_dict: dict mapping placeholder `Tensor`s to their desired values.
Returns:
The value of the given `Tensor`.
Raises:
TypeError: if (i) the given tensor is neither a `Tensor` nor a nullary
function returning a `Tensor`, or (ii) we're given a feed_dict but the
tensor argument is not callable.
"""
if callable(tensor):
tensor = tensor()
elif feed_dict:
raise TypeError("if a feed_dict is provided to run(), then the tensor "
"argument must be a nullary function returning a Tensor")
if not tf.is_tensor(tensor):
raise TypeError("_GraphWrappedSession.run expects a Tensor argument, "
"or a nullary function returning a Tensor")
return self._session.run(tensor, feed_dict=feed_dict)
开发者ID:google-research,项目名称:tensorflow_constrained_optimization,代码行数:32,代码来源:graph_and_eager_test_case.py
示例14: get_num_columns_of_2d_tensor
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import is_tensor [as 别名]
def get_num_columns_of_2d_tensor(tensor, name="tensor"):
"""Gets the number of columns of a rank-two `Tensor`.
Args:
tensor: a rank-2 `Tensor` with a known number of columns.
name: str, how to refer to the tensor in error messages.
Returns:
The number of columns in the tensor.
Raises:
TypeError: if "tensor" is not a `Tensor`.
ValueError: if "tensor" is not a rank-2 `Tensor` with a known number of
columns.
"""
if not tf.is_tensor(tensor):
raise TypeError("%s must be a Tensor" % name)
dims = tensor.shape.dims
if dims is None:
raise ValueError("%s must have a known rank" % name)
if len(dims) != 2:
raise ValueError("%s must be rank 2 (it is rank %d)" % (name, len(dims)))
columns = dims[1].value
if columns is None:
raise ValueError("%s must have a known number of columns" % name)
return columns
示例15: __init__
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import is_tensor [as 别名]
def __init__(self, bits=8, min_max=None, stochastic=True):
"""Initializer for the UniformQuantizationEncodingStage.
Args:
bits: The number of bits to quantize to. Must be an integer between 1 and
16. Can be either a TensorFlow or a Python value.
min_max: A range to be used for quantization. If `None`, the range of the
vector to be encoded will be used. If provided, must be an array of 2
elements, corresponding to the min and max value, respectively. Can be
either a TensorFlow or a Python value.
stochastic: A Python bool, whether to use stochastic or deterministic
rounding. If `True`, the encoding is randomized and on expectation
unbiased. If `False`, the encoding is deterministic.
Raises:
ValueError: The inputs do not satisfy the above constraints.
"""
if (not tf.is_tensor(bits) and bits not in self._ALLOWED_BITS_ARG):
raise ValueError('The bits argument must be an integer between 1 and 16.')
self._bits = bits
if min_max is not None:
if tf.is_tensor(min_max):
if min_max.shape.as_list() != [2]:
raise ValueError(
'The min_max argument must be Tensor with shape (2).')
else:
if not isinstance(min_max, list) or len(min_max) != 2:
raise ValueError(
'The min_max argument must be a list with two elements.')
if min_max[0] >= min_max[1]:
raise ValueError('The first element of the min_max argument must be '
'smaller than the second element.')
self._min_max = min_max
if not isinstance(stochastic, bool):
raise TypeError('The stochastic argument must be a bool.')
self._stochastic = stochastic