本文整理汇总了Python中tensorflow.python.framework.dtypes.as_dtype方法的典型用法代码示例。如果您正苦于以下问题:Python dtypes.as_dtype方法的具体用法?Python dtypes.as_dtype怎么用?Python dtypes.as_dtype使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类tensorflow.python.framework.dtypes
的用法示例。
在下文中一共展示了dtypes.as_dtype方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _restore_slice
# 需要导入模块: from tensorflow.python.framework import dtypes [as 别名]
# 或者: from tensorflow.python.framework.dtypes import as_dtype [as 别名]
def _restore_slice(file_pattern, tensor_name, shape_and_slice, tensor_type,
name="restore_slice", preferred_shard=-1):
"""Restore a tensor slice from a set of files with a given pattern.
Example usage:
RestoreSlice("/foo/bar-?????-of-?????", "w", "10 10 0,2:-", DT_FLOAT)
Args:
file_pattern: the file pattern used to match a set of checkpoint files.
tensor_name: the name of the tensor to restore.
shape_and_slice: the shape-and-slice spec of the slice.
tensor_type: the type of the tensor to restore.
name: string. Optional name for the op.
preferred_shard: Int. Optional shard to open first in the checkpoint file.
Returns:
A tensor of type "tensor_type".
"""
base_type = dtypes.as_dtype(tensor_type).base_dtype
return gen_io_ops._restore_slice(
file_pattern, tensor_name, shape_and_slice, base_type,
preferred_shard, name=name)
示例2: __init__
# 需要导入模块: from tensorflow.python.framework import dtypes [as 别名]
# 或者: from tensorflow.python.framework.dtypes import as_dtype [as 别名]
def __init__(self, scale=1.0,
mode="fan_in",
distribution="normal",
seed=None,
dtype=dtypes.float32):
if scale <= 0.:
raise ValueError("`scale` must be positive float.")
if mode not in {"fan_in", "fan_out", "fan_avg"}:
raise ValueError("Invalid `mode` argument:", mode)
distribution = distribution.lower()
if distribution not in {"normal", "uniform"}:
raise ValueError("Invalid `distribution` argument:", distribution)
self.scale = scale
self.mode = mode
self.distribution = distribution
self.seed = seed
self.dtype = _assert_float_dtype(dtypes.as_dtype(dtype))
示例3: __init__
# 需要导入模块: from tensorflow.python.framework import dtypes [as 别名]
# 或者: from tensorflow.python.framework.dtypes import as_dtype [as 别名]
def __init__(self, op, value_index, dtype):
"""Creates a new `Tensor`.
Args:
op: An `Operation`. `Operation` that computes this tensor.
value_index: An `int`. Index of the operation's endpoint that produces
this tensor.
dtype: A `DType`. Type of elements stored in this tensor.
Raises:
TypeError: If the op is not an `Operation`.
"""
if not isinstance(op, Operation):
raise TypeError("op needs to be an Operation: %s" % op)
self._op = op
self._value_index = value_index
self._dtype = dtypes.as_dtype(dtype)
self._shape = tensor_shape.unknown_shape()
# List of operations that use this Tensor as input. We maintain this list
# to easily navigate a computation graph.
self._consumers = []
# Attributes used for C++ shape inference. Not inspected, only forwarded.
self._handle_shape = tensor_shape_pb2.TensorShapeProto()
self._handle_dtype = types_pb2.DT_INVALID
示例4: random_positive_definite_matrix
# 需要导入模块: from tensorflow.python.framework import dtypes [as 别名]
# 或者: from tensorflow.python.framework.dtypes import as_dtype [as 别名]
def random_positive_definite_matrix(shape, dtype, force_well_conditioned=False):
"""[batch] positive definite matrix.
Args:
shape: `TensorShape` or Python list. Shape of the returned matrix.
dtype: `TensorFlow` `dtype` or Python dtype.
force_well_conditioned: Python bool. If `True`, returned matrix has
eigenvalues with modulus in `(1, 4)`. Otherwise, eigenvalues are
chi-squared random variables.
Returns:
`Tensor` with desired shape and dtype.
"""
dtype = dtypes.as_dtype(dtype)
if not contrib_tensor_util.is_tensor(shape):
shape = tensor_shape.TensorShape(shape)
# Matrix must be square.
shape[-1].assert_is_compatible_with(shape[-2])
with ops.name_scope("random_positive_definite_matrix"):
tril = random_tril_matrix(
shape, dtype, force_well_conditioned=force_well_conditioned)
return math_ops.matmul(tril, tril, adjoint_b=True)
示例5: _VerifyGeneratedGradients
# 需要导入模块: from tensorflow.python.framework import dtypes [as 别名]
# 或者: from tensorflow.python.framework.dtypes import as_dtype [as 别名]
def _VerifyGeneratedGradients(grads, op):
"""Verify that gradients are valid in number and type.
Args:
grads: List of generated gradients.
op: Operation for which the gradients where generated.
Raises:
ValueError: if the gradients are invalid.
"""
if len(grads) != len(op.inputs):
raise ValueError("Num gradients %d generated for op %s do not match num "
"inputs %d" % (len(grads), op.node_def, len(op.inputs)))
for i in xrange(len(grads)):
grad = grads[i]
inp = op.inputs[i]
if grad is not None:
if not grad.dtype.is_compatible_with(inp.dtype):
raise ValueError("Gradient type %s generated for op %s does "
"not match input type %s" %
(dtypes.as_dtype(grad.dtype).name, op.node_def,
dtypes.as_dtype(inp.dtype).name))
示例6: _prepare_output_as_AppendArrayToTensorProto
# 需要导入模块: from tensorflow.python.framework import dtypes [as 别名]
# 或者: from tensorflow.python.framework.dtypes import as_dtype [as 别名]
def _prepare_output_as_AppendArrayToTensorProto(
inference_output,
model_available_outputs):
response = predict_pb2.PredictResponse()
for response_output_name, model_output_name in \
model_available_outputs.items():
if model_output_name in inference_output:
dtype = dtypes.as_dtype(inference_output[model_output_name].dtype)
output_tensor = tensor_pb2.TensorProto(
dtype=dtype.as_datatype_enum,
tensor_shape=tensor_shape.as_shape(
inference_output[model_output_name].shape).as_proto())
result = inference_output[model_output_name].flatten()
tensor_util._NP_TO_APPEND_FN[dtype.as_numpy_dtype](output_tensor,
result)
response.outputs[response_output_name].CopyFrom(output_tensor)
return response
示例7: __init__
# 需要导入模块: from tensorflow.python.framework import dtypes [as 别名]
# 或者: from tensorflow.python.framework.dtypes import as_dtype [as 别名]
def __init__(self,
payloads,
labels,
dtype=dtypes.float32,
seed=None):
"""Construct a DataSet.
one_hot arg is used only if fake_data is true. `dtype` can be either
`uint8` to leave the input as `[0, 255]`, or `float32` to rescale into
`[0, 1]`. Seed arg provides for convenient deterministic testing.
"""
seed1, seed2 = random_seed.get_seed(seed)
# If op level seed is not set, use whatever graph level seed is returned
np.random.seed(seed1 if seed is None else seed2)
dtype = dtypes.as_dtype(dtype).base_dtype
if dtype not in (dtypes.uint8, dtypes.float32):
raise TypeError('Invalid payload dtype %r, expected uint8 or float32' %
dtype)
assert payloads.shape[0] == labels.shape[0], (
'payloads.shape: %s labels.shape: %s' % (payloads.shape, labels.shape))
self._num_examples = payloads.shape[0]
if dtype == dtypes.float32:
# Convert from [0, 255] -> [0.0, 1.0].
payloads = payloads.astype(np.float32)
payloads = np.multiply(payloads, 1.0 / 255.0)
self._payloads = payloads
self._labels = labels
self._epochs_completed = 0
self._index_in_epoch = 0
示例8: __init__
# 需要导入模块: from tensorflow.python.framework import dtypes [as 别名]
# 或者: from tensorflow.python.framework.dtypes import as_dtype [as 别名]
def __init__(self,
images,
labels,
start_id=0,
fake_data=False,
one_hot=False,
dtype=dtypes.float32):
"""Construct a DataSet.
one_hot arg is used only if fake_data is true. `dtype` can be either
`uint8` to leave the input as `[0, 255]`, or `float32` to rescale into
`[0, 1]`.
"""
dtype = dtypes.as_dtype(dtype).base_dtype
if dtype not in (dtypes.uint8, dtypes.float32):
raise TypeError('Invalid image dtype %r, expected uint8 or float32' %
dtype)
if fake_data:
self._num_examples = 10000
self.one_hot = one_hot
else:
assert images.shape[0] == labels.shape[0], (
'images.shape: %s labels.shape: %s' % (images.shape, labels.shape))
self._num_examples = images.shape[0]
# Convert shape from [num examples, rows, columns, depth]
# to [num examples, rows*columns] (assuming depth == 1)
assert images.shape[3] == 1
images = images.reshape(images.shape[0],
images.shape[1] * images.shape[2])
if dtype == dtypes.float32:
# Convert from [0, 255] -> [0.0, 1.0].
images = images.astype(numpy.float32)
images = numpy.multiply(images, 1.0 / 255.0)
self._ids = numpy.arange(start_id, start_id + self._num_examples)
self._images = images
self._labels = labels
self._epochs_completed = 0
self._index_in_epoch = 0
示例9: _assert_dtype
# 需要导入模块: from tensorflow.python.framework import dtypes [as 别名]
# 或者: from tensorflow.python.framework.dtypes import as_dtype [as 别名]
def _assert_dtype(images):
""" Make sure the images are of the correct data type """
dtype = dtypes.as_dtype(images.dtype).base_dtype
if dtype not in (dtypes.uint8, dtypes.float32):
raise TypeError('Invalid image dtype {0}, expected uint8 or float32'.format(dtype))
return dtype
示例10: build_tensor_info
# 需要导入模块: from tensorflow.python.framework import dtypes [as 别名]
# 或者: from tensorflow.python.framework.dtypes import as_dtype [as 别名]
def build_tensor_info(tensor):
"""Utility function to build TensorInfo proto.
Args:
tensor: Tensor whose name, dtype and shape are used to build the TensorInfo.
Returns:
A TensorInfo protocol buffer constructed based on the supplied argument.
"""
dtype_enum = dtypes.as_dtype(tensor.dtype).as_datatype_enum
return meta_graph_pb2.TensorInfo(
name=tensor.name,
dtype=dtype_enum,
tensor_shape=tensor.get_shape().as_proto())
示例11: __init__
# 需要导入模块: from tensorflow.python.framework import dtypes [as 别名]
# 或者: from tensorflow.python.framework.dtypes import as_dtype [as 别名]
def __init__(self, scores=None, classes=None):
"""Constructor for `ClassifyOutput`.
Args:
scores: A float `Tensor` giving scores (sometimes but not always
interpretable as probabilities) for each class. May be `None`, but
only if `classes` is set. Interpretation varies-- see class doc.
classes: A string `Tensor` giving predicted class labels. May be `None`,
but only if `scores` is set. Interpretation varies-- see class doc.
Raises:
ValueError: if neither classes nor scores is set, or one of them is not a
`Tensor` with the correct dtype.
"""
if (scores is not None
and not (isinstance(scores, ops.Tensor)
and scores.dtype.is_floating)):
raise ValueError('Classification scores must be a float32 Tensor; '
'got {}'.format(scores))
if (classes is not None
and not (isinstance(classes, ops.Tensor)
and dtypes.as_dtype(classes.dtype) == dtypes.string)):
raise ValueError('Classification classes must be a string Tensor; '
'got {}'.format(classes))
if scores is None and classes is None:
raise ValueError('At least one of scores and classes must be set.')
self._scores = scores
self._classes = classes
示例12: as_signature_def
# 需要导入模块: from tensorflow.python.framework import dtypes [as 别名]
# 或者: from tensorflow.python.framework.dtypes import as_dtype [as 别名]
def as_signature_def(self, receiver_tensors):
if len(receiver_tensors) != 1:
raise ValueError('Classification input must be a single string Tensor; '
'got {}'.format(receiver_tensors))
(_, examples), = receiver_tensors.items()
if dtypes.as_dtype(examples.dtype) != dtypes.string:
raise ValueError('Classification input must be a single string Tensor; '
'got {}'.format(receiver_tensors))
return signature_def_utils.classification_signature_def(
examples, self.classes, self.scores)
示例13: zeros
# 需要导入模块: from tensorflow.python.framework import dtypes [as 别名]
# 或者: from tensorflow.python.framework.dtypes import as_dtype [as 别名]
def zeros(shape, dtype=dtypes.float32, name=None):
"""Creates a tensor with all elements set to zero.
This operation returns a tensor of type `dtype` with shape `shape` and
all elements set to zero.
For example:
```python
tf.zeros([3, 4], tf.int32) ==> [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
```
Args:
shape: Either a list of integers, or a 1-D `Tensor` of type `int32`.
dtype: The type of an element in the resulting `Tensor`.
name: A name for the operation (optional).
Returns:
A `Tensor` with all elements set to zero.
"""
dtype = dtypes.as_dtype(dtype).base_dtype
with ops.name_scope(name, "zeros", [shape]) as name:
if dtype == dtypes.bool:
zero = False
elif dtype == dtypes.string:
zero = ""
else:
zero = 0
try:
shape = tensor_shape.as_shape(shape)
output = constant(zero, shape=shape, dtype=dtype, name=name)
except (TypeError, ValueError):
shape = ops.convert_to_tensor(shape, dtype=dtypes.int32, name="shape")
output = fill(shape, constant(zero, dtype=dtype), name=name)
assert output.dtype.base_dtype == dtype
return output
示例14: ones
# 需要导入模块: from tensorflow.python.framework import dtypes [as 别名]
# 或者: from tensorflow.python.framework.dtypes import as_dtype [as 别名]
def ones(shape, dtype=dtypes.float32, name=None):
"""Creates a tensor with all elements set to 1.
This operation returns a tensor of type `dtype` with shape `shape` and all
elements set to 1.
For example:
```python
tf.ones([2, 3], tf.int32) ==> [[1, 1, 1], [1, 1, 1]]
```
Args:
shape: Either a list of integers, or a 1-D `Tensor` of type `int32`.
dtype: The type of an element in the resulting `Tensor`.
name: A name for the operation (optional).
Returns:
A `Tensor` with all elements set to 1.
"""
dtype = dtypes.as_dtype(dtype).base_dtype
with ops.name_scope(name, "ones", [shape]) as name:
one = True if dtype == dtypes.bool else 1
try:
shape = tensor_shape.as_shape(shape)
output = constant(one, shape=shape, dtype=dtype, name=name)
except (TypeError, ValueError):
shape = ops.convert_to_tensor(shape, dtype=dtypes.int32, name="shape")
output = fill(shape, constant(one, dtype=dtype), name=name)
assert output.dtype.base_dtype == dtype
return output
示例15: cast
# 需要导入模块: from tensorflow.python.framework import dtypes [as 别名]
# 或者: from tensorflow.python.framework.dtypes import as_dtype [as 别名]
def cast(x, dtype, name=None):
"""Casts a tensor to a new type.
The operation casts `x` (in case of `Tensor`) or `x.values`
(in case of `SparseTensor`) to `dtype`.
For example:
```python
# tensor `a` is [1.8, 2.2], dtype=tf.float
tf.cast(a, tf.int32) ==> [1, 2] # dtype=tf.int32
```
Args:
x: A `Tensor` or `SparseTensor`.
dtype: The destination type.
name: A name for the operation (optional).
Returns:
A `Tensor` or `SparseTensor` with same shape as `x`.
Raises:
TypeError: If `x` cannot be cast to the `dtype`.
"""
base_type = dtypes.as_dtype(dtype).base_dtype
with ops.name_scope(name, "Cast", [x]) as name:
if isinstance(x, sparse_tensor.SparseTensor):
values_cast = cast(x.values, base_type, name=name)
return sparse_tensor.SparseTensor(x.indices, values_cast, x.dense_shape)
else:
# TODO(touts): Handle what Josh said.
#
# Could return ops.convert_to_tensor(x, dtype=dtype, ...) here, but that
# allows some conversions that cast() can't do, e.g. casting numbers to
# strings.
x = ops.convert_to_tensor(x, name="x")
if x.dtype.base_dtype == base_type:
return x
return gen_math_ops.cast(x, base_type, name=name)