本文整理汇总了Python中tensorflow.compat.v2.shape方法的典型用法代码示例。如果您正苦于以下问题:Python v2.shape方法的具体用法?Python v2.shape怎么用?Python v2.shape使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类tensorflow.compat.v2
的用法示例。
在下文中一共展示了v2.shape方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: zeros
# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import shape [as 别名]
def zeros(shape, dtype=float): # pylint: disable=redefined-outer-name
"""Returns an ndarray with the given shape and type filled with zeros.
Args:
shape: A fully defined shape. Could be - NumPy array or a python scalar,
list or tuple of integers, - TensorFlow tensor/ndarray of integer type and
rank <=1.
dtype: Optional, defaults to float. The type of the resulting ndarray. Could
be a python type, a NumPy type or a TensorFlow `DType`.
Returns:
An ndarray.
"""
if dtype:
dtype = utils.result_type(dtype)
if isinstance(shape, arrays_lib.ndarray):
shape = shape.data
return arrays_lib.tensor_to_ndarray(tf.zeros(shape, dtype=dtype))
示例2: zeros_like
# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import shape [as 别名]
def zeros_like(a, dtype=None):
"""Returns an array of zeros with the shape and type of the input array.
Args:
a: array_like. Could be an ndarray, a Tensor or any object that can be
converted to a Tensor using `tf.convert_to_tensor`.
dtype: Optional, defaults to dtype of the input array. The type of the
resulting ndarray. Could be a python type, a NumPy type or a TensorFlow
`DType`.
Returns:
An ndarray.
"""
if isinstance(a, arrays_lib.ndarray):
a = a.data
if dtype is None:
# We need to let utils.result_type decide the dtype, not tf.zeros_like
dtype = utils.result_type(a)
else:
# TF and numpy has different interpretations of Python types such as
# `float`, so we let `utils.result_type` decide.
dtype = utils.result_type(dtype)
dtype = tf.as_dtype(dtype) # Work around b/149877262
return arrays_lib.tensor_to_ndarray(tf.zeros_like(a, dtype))
示例3: ones
# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import shape [as 别名]
def ones(shape, dtype=float): # pylint: disable=redefined-outer-name
"""Returns an ndarray with the given shape and type filled with ones.
Args:
shape: A fully defined shape. Could be - NumPy array or a python scalar,
list or tuple of integers, - TensorFlow tensor/ndarray of integer type and
rank <=1.
dtype: Optional, defaults to float. The type of the resulting ndarray. Could
be a python type, a NumPy type or a TensorFlow `DType`.
Returns:
An ndarray.
"""
if dtype:
dtype = utils.result_type(dtype)
if isinstance(shape, arrays_lib.ndarray):
shape = shape.data
return arrays_lib.tensor_to_ndarray(tf.ones(shape, dtype=dtype))
示例4: full_like
# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import shape [as 别名]
def full_like(a, fill_value, dtype=None, order='K', subok=True, shape=None): # pylint: disable=missing-docstring,redefined-outer-name
"""order, subok and shape arguments mustn't be changed."""
if order != 'K':
raise ValueError('Non-standard orders are not supported.')
if not subok:
raise ValueError('subok being False is not supported.')
if shape:
raise ValueError('Overriding the shape is not supported.')
a = asarray(a).data
dtype = dtype or utils.result_type(a)
fill_value = asarray(fill_value, dtype=dtype)
return arrays_lib.tensor_to_ndarray(
tf.broadcast_to(fill_value.data, tf.shape(a)))
# TODO(wangpeng): investigate whether we can make `copy` default to False.
# TODO(wangpeng): utils.np_doc can't handle np.array because np.array is a
# builtin function. Make utils.np_doc support builtin functions.
示例5: imag
# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import shape [as 别名]
def imag(a):
"""Returns imaginary parts of all elements in `a`.
Uses `tf.imag`.
Args:
a: array_like. Could be an ndarray, a Tensor or any object that can
be converted to a Tensor using `tf.convert_to_tensor`.
Returns:
An ndarray with the same shape as `a`.
"""
a = asarray(a)
# TODO(srbs): np.imag returns a scalar if a is a scalar, whereas we always
# return an ndarray.
return utils.tensor_to_ndarray(tf.math.imag(a.data))
示例6: real
# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import shape [as 别名]
def real(val):
"""Returns real parts of all elements in `a`.
Uses `tf.real`.
Args:
val: array_like. Could be an ndarray, a Tensor or any object that can
be converted to a Tensor using `tf.convert_to_tensor`.
Returns:
An ndarray with the same shape as `a`.
"""
val = asarray(val)
# TODO(srbs): np.real returns a scalar if val is a scalar, whereas we always
# return an ndarray.
return utils.tensor_to_ndarray(tf.math.real(val.data))
示例7: take
# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import shape [as 别名]
def take(a, indices, axis=None, out=None, mode='clip'):
"""out argument is not supported, and default mode is clip."""
if out is not None:
raise ValueError('out argument is not supported in take.')
if mode not in {'raise', 'clip', 'wrap'}:
raise ValueError("Invalid mode '{}' for take".format(mode))
a = asarray(a).data
indices = asarray(indices).data
if axis is None:
a = tf.reshape(a, [-1])
axis = 0
axis_size = tf.shape(a, indices.dtype)[axis]
if mode == 'clip':
indices = tf.clip_by_value(indices, 0, axis_size-1)
elif mode == 'wrap':
indices = tf.math.floormod(indices, axis_size)
else:
raise ValueError("The 'raise' mode to take is not supported.")
return utils.tensor_to_ndarray(tf.gather(a, indices, axis=axis))
示例8: tril
# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import shape [as 别名]
def tril(m, k=0): # pylint: disable=missing-docstring
m = asarray(m).data
m_shape = m.shape.as_list()
if len(m_shape) < 2:
raise ValueError('Argument to tril must have rank at least 2')
if m_shape[-1] is None or m_shape[-2] is None:
raise ValueError('Currently, the last two dimensions of the input array '
'need to be known.')
z = tf.constant(0, m.dtype)
mask = tri(*m_shape[-2:], k=k, dtype=bool)
return utils.tensor_to_ndarray(
tf.where(tf.broadcast_to(mask, tf.shape(m)), m, z))
示例9: triu
# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import shape [as 别名]
def triu(m, k=0): # pylint: disable=missing-docstring
m = asarray(m).data
m_shape = m.shape.as_list()
if len(m_shape) < 2:
raise ValueError('Argument to triu must have rank at least 2')
if m_shape[-1] is None or m_shape[-2] is None:
raise ValueError('Currently, the last two dimensions of the input array '
'need to be known.')
z = tf.constant(0, m.dtype)
mask = tri(*m_shape[-2:], k=k - 1, dtype=bool)
return utils.tensor_to_ndarray(
tf.where(tf.broadcast_to(mask, tf.shape(m)), z, m))
示例10: tf_broadcast
# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import shape [as 别名]
def tf_broadcast(*args):
"""Broadcast tensors.
Args:
*args: a list of tensors whose shapes are broadcastable against each other.
Returns:
Tensors broadcasted to the common shape.
"""
if len(args) <= 1:
return args
sh = tf.shape(args[0])
for arg in args[1:]:
sh = tf.broadcast_dynamic_shape(sh, tf.shape(arg))
return [tf.broadcast_to(arg, sh) for arg in args]
# TODO(wangpeng): Move the following functions to a separate file and check for
# float dtypes in each of them.
示例11: _scalar
# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import shape [as 别名]
def _scalar(tf_fn, x, promote_to_float=False):
"""Computes the tf_fn(x) for each element in `x`.
Args:
tf_fn: function that takes a single Tensor argument.
x: array_like. Could be an ndarray, a Tensor or any object that can
be converted to a Tensor using `tf.convert_to_tensor`.
promote_to_float: whether to cast the argument to a float dtype
(`dtypes.default_float_type`) if it is not already.
Returns:
An ndarray with the same shape as `x`. The default output dtype is
determined by `dtypes.default_float_type`, unless x is an ndarray with a
floating point type, in which case the output type is same as x.dtype.
"""
x = array_ops.asarray(x)
if promote_to_float and not np.issubdtype(x.dtype, np.inexact):
x = x.astype(dtypes.default_float_type())
return utils.tensor_to_ndarray(tf_fn(x.data))
示例12: diff
# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import shape [as 别名]
def diff(a, n=1, axis=-1):
def f(a):
nd = a.shape.rank
if (axis + nd if axis < 0 else axis) >= nd:
raise ValueError("axis %s is out of bounds for array of dimension %s" %
(axis, nd))
if n < 0:
raise ValueError("order must be non-negative but got %s" % n)
slice1 = [slice(None)] * nd
slice2 = [slice(None)] * nd
slice1[axis] = slice(1, None)
slice2[axis] = slice(None, -1)
slice1 = tuple(slice1)
slice2 = tuple(slice2)
op = tf.not_equal if a.dtype == tf.bool else tf.subtract
for _ in range(n):
a = op(a[slice1], a[slice2])
return a
return _scalar(f, a)
示例13: tf_randint
# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import shape [as 别名]
def tf_randint(key, shape, minval, maxval, dtype=np.int32):
"""Sample uniform random values in [minval, maxval) with given shape/dtype.
Args:
key: a PRNGKey used as the random key.
shape: a tuple of nonnegative integers representing the shape.
minval: int or array of ints broadcast-compatible with ``shape``, a minimum
(inclusive) value for the range.
maxval: int or array of ints broadcast-compatible with ``shape``, a maximum
(exclusive) value for the range.
dtype: optional, an int dtype for the returned values (default int32).
Returns:
A random array with the specified shape and dtype.
"""
return tf_np_extensions.uniform(key, shape, minval=minval, maxval=maxval,
dtype=dtype)
示例14: call
# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import shape [as 别名]
def call(self, inputs):
"""Generates mask (whether example is valid) from features.
Args:
inputs: (dict) Features with a mix of context (2D) and example features
(3D).
Returns:
mask: (tf.Tensor) Mask is a tensor of shape [batch_size, list_size], which
is True for a valid example and False for invalid one.
"""
example_feature = inputs[next(six.iterkeys(self._example_feature_columns))]
list_size = tf.shape(example_feature)[1]
sizes = inputs[self._size_feature_name]
mask = tf.sequence_mask(sizes, maxlen=list_size)
return mask
示例15: transform
# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import shape [as 别名]
def transform(self, features=None, training=None, mask=None):
"""Transforms the features into dense context features and example features.
The user can overwrite this function for custom transformations.
Mask is provided as an argument so that inherited models can have access
to it for custom feature transformations, without modifying
`call` explicitly.
Args:
features: (dict) with a mix of context (2D) and example features (3D).
training: (bool) whether in train or inference mode.
mask: (tf.Tensor) Mask is a tensor of shape [batch_size, list_size], which
is True for a valid example and False for invalid one.
Returns:
context_features: (dict) context feature names to dense 2D tensors of
shape [batch_size, feature_dims].
example_features: (dict) example feature names to dense 3D tensors of
shape [batch_size, list_size, feature_dims].
"""
del mask
context_features, example_features = self._listwise_dense_layer(
inputs=features, training=training)
return context_features, example_features