body
stringlengths 26
98.2k
| body_hash
int64 -9,222,864,604,528,158,000
9,221,803,474B
| docstring
stringlengths 1
16.8k
| path
stringlengths 5
230
| name
stringlengths 1
96
| repository_name
stringlengths 7
89
| lang
stringclasses 1
value | body_without_docstring
stringlengths 20
98.2k
|
---|---|---|---|---|---|---|---|
@tf_export('math.imag', v1=['math.imag', 'imag'])
@deprecation.deprecated_endpoints('imag')
@dispatch.add_dispatch_support
def imag(input, name=None):
'Returns the imaginary part of a complex (or real) tensor.\n\n Given a tensor `input`, this operation returns a tensor of type `float` that\n is the imaginary part of each element in `input` considered as a complex\n number. If `input` is real, a tensor of all zeros is returned.\n\n For example:\n\n ```python\n x = tf.constant([-2.25 + 4.75j, 3.25 + 5.75j])\n tf.imag(x) # [4.75, 5.75]\n ```\n\n Args:\n input: A `Tensor`. Must be one of the following types: `float`, `double`,\n `complex64`, `complex128`.\n name: A name for the operation (optional).\n\n Returns:\n A `Tensor` of type `float32` or `float64`.\n '
with ops.name_scope(name, 'Imag', [input]) as name:
if input.dtype.is_complex:
return gen_math_ops.imag(input, Tout=input.dtype.real_dtype, name=name)
else:
return array_ops.zeros_like(input) | 551,267,326,716,524,900 | Returns the imaginary part of a complex (or real) tensor.
Given a tensor `input`, this operation returns a tensor of type `float` that
is the imaginary part of each element in `input` considered as a complex
number. If `input` is real, a tensor of all zeros is returned.
For example:
```python
x = tf.constant([-2.25 + 4.75j, 3.25 + 5.75j])
tf.imag(x) # [4.75, 5.75]
```
Args:
input: A `Tensor`. Must be one of the following types: `float`, `double`,
`complex64`, `complex128`.
name: A name for the operation (optional).
Returns:
A `Tensor` of type `float32` or `float64`. | tensorflow/python/ops/math_ops.py | imag | minminsun/tensorflow | python | @tf_export('math.imag', v1=['math.imag', 'imag'])
@deprecation.deprecated_endpoints('imag')
@dispatch.add_dispatch_support
def imag(input, name=None):
'Returns the imaginary part of a complex (or real) tensor.\n\n Given a tensor `input`, this operation returns a tensor of type `float` that\n is the imaginary part of each element in `input` considered as a complex\n number. If `input` is real, a tensor of all zeros is returned.\n\n For example:\n\n ```python\n x = tf.constant([-2.25 + 4.75j, 3.25 + 5.75j])\n tf.imag(x) # [4.75, 5.75]\n ```\n\n Args:\n input: A `Tensor`. Must be one of the following types: `float`, `double`,\n `complex64`, `complex128`.\n name: A name for the operation (optional).\n\n Returns:\n A `Tensor` of type `float32` or `float64`.\n '
with ops.name_scope(name, 'Imag', [input]) as name:
if input.dtype.is_complex:
return gen_math_ops.imag(input, Tout=input.dtype.real_dtype, name=name)
else:
return array_ops.zeros_like(input) |
@tf_export('math.angle', v1=['math.angle', 'angle'])
@deprecation.deprecated_endpoints('angle')
@dispatch.add_dispatch_support
def angle(input, name=None):
"Returns the element-wise argument of a complex (or real) tensor.\n\n Given a tensor `input`, this operation returns a tensor of type `float` that\n is the argument of each element in `input` considered as a complex number.\n\n The elements in `input` are considered to be complex numbers of the form\n \\\\(a + bj\\\\), where *a* is the real part and *b* is the imaginary part.\n If `input` is real then *b* is zero by definition.\n\n The argument returned by this function is of the form \\\\(atan2(b, a)\\\\).\n If `input` is real, a tensor of all zeros is returned.\n\n For example:\n\n ```\n # tensor 'input' is [-2.25 + 4.75j, 3.25 + 5.75j]\n tf.angle(input) ==> [2.0132, 1.056]\n ```\n\n Args:\n input: A `Tensor`. Must be one of the following types: `float`, `double`,\n `complex64`, `complex128`.\n name: A name for the operation (optional).\n\n Returns:\n A `Tensor` of type `float32` or `float64`.\n "
with ops.name_scope(name, 'Angle', [input]) as name:
if input.dtype.is_complex:
return gen_math_ops.angle(input, Tout=input.dtype.real_dtype, name=name)
else:
return array_ops.zeros_like(input) | 694,283,158,599,546,800 | Returns the element-wise argument of a complex (or real) tensor.
Given a tensor `input`, this operation returns a tensor of type `float` that
is the argument of each element in `input` considered as a complex number.
The elements in `input` are considered to be complex numbers of the form
\\(a + bj\\), where *a* is the real part and *b* is the imaginary part.
If `input` is real then *b* is zero by definition.
The argument returned by this function is of the form \\(atan2(b, a)\\).
If `input` is real, a tensor of all zeros is returned.
For example:
```
# tensor 'input' is [-2.25 + 4.75j, 3.25 + 5.75j]
tf.angle(input) ==> [2.0132, 1.056]
```
Args:
input: A `Tensor`. Must be one of the following types: `float`, `double`,
`complex64`, `complex128`.
name: A name for the operation (optional).
Returns:
A `Tensor` of type `float32` or `float64`. | tensorflow/python/ops/math_ops.py | angle | minminsun/tensorflow | python | @tf_export('math.angle', v1=['math.angle', 'angle'])
@deprecation.deprecated_endpoints('angle')
@dispatch.add_dispatch_support
def angle(input, name=None):
"Returns the element-wise argument of a complex (or real) tensor.\n\n Given a tensor `input`, this operation returns a tensor of type `float` that\n is the argument of each element in `input` considered as a complex number.\n\n The elements in `input` are considered to be complex numbers of the form\n \\\\(a + bj\\\\), where *a* is the real part and *b* is the imaginary part.\n If `input` is real then *b* is zero by definition.\n\n The argument returned by this function is of the form \\\\(atan2(b, a)\\\\).\n If `input` is real, a tensor of all zeros is returned.\n\n For example:\n\n ```\n # tensor 'input' is [-2.25 + 4.75j, 3.25 + 5.75j]\n tf.angle(input) ==> [2.0132, 1.056]\n ```\n\n Args:\n input: A `Tensor`. Must be one of the following types: `float`, `double`,\n `complex64`, `complex128`.\n name: A name for the operation (optional).\n\n Returns:\n A `Tensor` of type `float32` or `float64`.\n "
with ops.name_scope(name, 'Angle', [input]) as name:
if input.dtype.is_complex:
return gen_math_ops.angle(input, Tout=input.dtype.real_dtype, name=name)
else:
return array_ops.zeros_like(input) |
@tf_export('math.round', 'round')
@dispatch.add_dispatch_support
def round(x, name=None):
'Rounds the values of a tensor to the nearest integer, element-wise.\n\n Rounds half to even. Also known as bankers rounding. If you want to round\n according to the current system rounding mode use tf::cint.\n For example:\n\n ```python\n x = tf.constant([0.9, 2.5, 2.3, 1.5, -4.5])\n tf.round(x) # [ 1.0, 2.0, 2.0, 2.0, -4.0 ]\n ```\n\n Args:\n x: A `Tensor` of type `float16`, `float32`, `float64`, `int32`, or `int64`.\n name: A name for the operation (optional).\n\n Returns:\n A `Tensor` of same shape and type as `x`.\n '
x = ops.convert_to_tensor(x, name='x')
if x.dtype.is_integer:
return x
else:
return gen_math_ops.round(x, name=name) | 4,454,927,360,459,215,400 | Rounds the values of a tensor to the nearest integer, element-wise.
Rounds half to even. Also known as bankers rounding. If you want to round
according to the current system rounding mode use tf::cint.
For example:
```python
x = tf.constant([0.9, 2.5, 2.3, 1.5, -4.5])
tf.round(x) # [ 1.0, 2.0, 2.0, 2.0, -4.0 ]
```
Args:
x: A `Tensor` of type `float16`, `float32`, `float64`, `int32`, or `int64`.
name: A name for the operation (optional).
Returns:
A `Tensor` of same shape and type as `x`. | tensorflow/python/ops/math_ops.py | round | minminsun/tensorflow | python | @tf_export('math.round', 'round')
@dispatch.add_dispatch_support
def round(x, name=None):
'Rounds the values of a tensor to the nearest integer, element-wise.\n\n Rounds half to even. Also known as bankers rounding. If you want to round\n according to the current system rounding mode use tf::cint.\n For example:\n\n ```python\n x = tf.constant([0.9, 2.5, 2.3, 1.5, -4.5])\n tf.round(x) # [ 1.0, 2.0, 2.0, 2.0, -4.0 ]\n ```\n\n Args:\n x: A `Tensor` of type `float16`, `float32`, `float64`, `int32`, or `int64`.\n name: A name for the operation (optional).\n\n Returns:\n A `Tensor` of same shape and type as `x`.\n '
x = ops.convert_to_tensor(x, name='x')
if x.dtype.is_integer:
return x
else:
return gen_math_ops.round(x, name=name) |
@tf_export('dtypes.cast', 'cast')
@dispatch.add_dispatch_support
def cast(x, dtype, name=None):
'Casts a tensor to a new type.\n\n The operation casts `x` (in case of `Tensor`) or `x.values`\n (in case of `SparseTensor` or `IndexedSlices`) to `dtype`.\n\n For example:\n\n ```python\n x = tf.constant([1.8, 2.2], dtype=tf.float32)\n tf.cast(x, tf.int32) # [1, 2], dtype=tf.int32\n ```\n\n The operation supports data types (for `x` and `dtype`) of\n `uint8`, `uint16`, `uint32`, `uint64`, `int8`, `int16`, `int32`, `int64`,\n `float16`, `float32`, `float64`, `complex64`, `complex128`, `bfloat16`.\n In case of casting from complex types (`complex64`, `complex128`) to real\n types, only the real part of `x` is returned. In case of casting from real\n types to complex types (`complex64`, `complex128`), the imaginary part of the\n returned value is set to `0`. The handling of complex types here matches the\n behavior of numpy.\n\n Args:\n x: A `Tensor` or `SparseTensor` or `IndexedSlices` of numeric type. It could\n be `uint8`, `uint16`, `uint32`, `uint64`, `int8`, `int16`, `int32`,\n `int64`, `float16`, `float32`, `float64`, `complex64`, `complex128`,\n `bfloat16`.\n dtype: The destination type. The list of supported dtypes is the same as\n `x`.\n name: A name for the operation (optional).\n\n Returns:\n A `Tensor` or `SparseTensor` or `IndexedSlices` with same shape as `x` and\n same type as `dtype`.\n\n Raises:\n TypeError: If `x` cannot be cast to the `dtype`.\n '
base_type = dtypes.as_dtype(dtype).base_dtype
if (isinstance(x, (ops.Tensor, _resource_variable_type)) and (base_type == x.dtype)):
return x
with ops.name_scope(name, 'Cast', [x]) as name:
if isinstance(x, sparse_tensor.SparseTensor):
values_cast = cast(x.values, base_type, name=name)
x = sparse_tensor.SparseTensor(x.indices, values_cast, x.dense_shape)
elif isinstance(x, ops.IndexedSlices):
values_cast = cast(x.values, base_type, name=name)
x = ops.IndexedSlices(values_cast, x.indices, x.dense_shape)
else:
x = ops.convert_to_tensor(x, name='x')
if (x.dtype.base_dtype != base_type):
x = gen_math_ops.cast(x, base_type, name=name)
if (x.dtype.is_complex and base_type.is_floating):
logging.warn('Casting complex to real discards imaginary part.')
return x | 4,099,450,131,418,936,000 | Casts a tensor to a new type.
The operation casts `x` (in case of `Tensor`) or `x.values`
(in case of `SparseTensor` or `IndexedSlices`) to `dtype`.
For example:
```python
x = tf.constant([1.8, 2.2], dtype=tf.float32)
tf.cast(x, tf.int32) # [1, 2], dtype=tf.int32
```
The operation supports data types (for `x` and `dtype`) of
`uint8`, `uint16`, `uint32`, `uint64`, `int8`, `int16`, `int32`, `int64`,
`float16`, `float32`, `float64`, `complex64`, `complex128`, `bfloat16`.
In case of casting from complex types (`complex64`, `complex128`) to real
types, only the real part of `x` is returned. In case of casting from real
types to complex types (`complex64`, `complex128`), the imaginary part of the
returned value is set to `0`. The handling of complex types here matches the
behavior of numpy.
Args:
x: A `Tensor` or `SparseTensor` or `IndexedSlices` of numeric type. It could
be `uint8`, `uint16`, `uint32`, `uint64`, `int8`, `int16`, `int32`,
`int64`, `float16`, `float32`, `float64`, `complex64`, `complex128`,
`bfloat16`.
dtype: The destination type. The list of supported dtypes is the same as
`x`.
name: A name for the operation (optional).
Returns:
A `Tensor` or `SparseTensor` or `IndexedSlices` with same shape as `x` and
same type as `dtype`.
Raises:
TypeError: If `x` cannot be cast to the `dtype`. | tensorflow/python/ops/math_ops.py | cast | minminsun/tensorflow | python | @tf_export('dtypes.cast', 'cast')
@dispatch.add_dispatch_support
def cast(x, dtype, name=None):
'Casts a tensor to a new type.\n\n The operation casts `x` (in case of `Tensor`) or `x.values`\n (in case of `SparseTensor` or `IndexedSlices`) to `dtype`.\n\n For example:\n\n ```python\n x = tf.constant([1.8, 2.2], dtype=tf.float32)\n tf.cast(x, tf.int32) # [1, 2], dtype=tf.int32\n ```\n\n The operation supports data types (for `x` and `dtype`) of\n `uint8`, `uint16`, `uint32`, `uint64`, `int8`, `int16`, `int32`, `int64`,\n `float16`, `float32`, `float64`, `complex64`, `complex128`, `bfloat16`.\n In case of casting from complex types (`complex64`, `complex128`) to real\n types, only the real part of `x` is returned. In case of casting from real\n types to complex types (`complex64`, `complex128`), the imaginary part of the\n returned value is set to `0`. The handling of complex types here matches the\n behavior of numpy.\n\n Args:\n x: A `Tensor` or `SparseTensor` or `IndexedSlices` of numeric type. It could\n be `uint8`, `uint16`, `uint32`, `uint64`, `int8`, `int16`, `int32`,\n `int64`, `float16`, `float32`, `float64`, `complex64`, `complex128`,\n `bfloat16`.\n dtype: The destination type. The list of supported dtypes is the same as\n `x`.\n name: A name for the operation (optional).\n\n Returns:\n A `Tensor` or `SparseTensor` or `IndexedSlices` with same shape as `x` and\n same type as `dtype`.\n\n Raises:\n TypeError: If `x` cannot be cast to the `dtype`.\n '
base_type = dtypes.as_dtype(dtype).base_dtype
if (isinstance(x, (ops.Tensor, _resource_variable_type)) and (base_type == x.dtype)):
return x
with ops.name_scope(name, 'Cast', [x]) as name:
if isinstance(x, sparse_tensor.SparseTensor):
values_cast = cast(x.values, base_type, name=name)
x = sparse_tensor.SparseTensor(x.indices, values_cast, x.dense_shape)
elif isinstance(x, ops.IndexedSlices):
values_cast = cast(x.values, base_type, name=name)
x = ops.IndexedSlices(values_cast, x.indices, x.dense_shape)
else:
x = ops.convert_to_tensor(x, name='x')
if (x.dtype.base_dtype != base_type):
x = gen_math_ops.cast(x, base_type, name=name)
if (x.dtype.is_complex and base_type.is_floating):
logging.warn('Casting complex to real discards imaginary part.')
return x |
@tf_export('dtypes.saturate_cast', 'saturate_cast')
@dispatch.add_dispatch_support
def saturate_cast(value, dtype, name=None):
'Performs a safe saturating cast of `value` to `dtype`.\n\n This function casts the input to `dtype` without applying any scaling. If\n there is a danger that values would over or underflow in the cast, this op\n applies the appropriate clamping before the cast.\n\n Args:\n value: A `Tensor`.\n dtype: The desired output `DType`.\n name: A name for the operation (optional).\n\n Returns:\n `value` safely cast to `dtype`.\n '
with ops.name_scope(name, 'saturate_cast', [value]) as name:
value = ops.convert_to_tensor(value, name='value')
dtype = dtypes.as_dtype(dtype).base_dtype
if (value.dtype.min < dtype.min):
value = gen_math_ops.maximum(value, ops.convert_to_tensor(dtype.min, dtype=value.dtype, name='min'))
if (value.dtype.max > dtype.max):
value = gen_math_ops.minimum(value, ops.convert_to_tensor(dtype.max, dtype=value.dtype, name='max'))
return cast(value, dtype, name=name) | 2,521,787,870,536,432,000 | Performs a safe saturating cast of `value` to `dtype`.
This function casts the input to `dtype` without applying any scaling. If
there is a danger that values would over or underflow in the cast, this op
applies the appropriate clamping before the cast.
Args:
value: A `Tensor`.
dtype: The desired output `DType`.
name: A name for the operation (optional).
Returns:
`value` safely cast to `dtype`. | tensorflow/python/ops/math_ops.py | saturate_cast | minminsun/tensorflow | python | @tf_export('dtypes.saturate_cast', 'saturate_cast')
@dispatch.add_dispatch_support
def saturate_cast(value, dtype, name=None):
'Performs a safe saturating cast of `value` to `dtype`.\n\n This function casts the input to `dtype` without applying any scaling. If\n there is a danger that values would over or underflow in the cast, this op\n applies the appropriate clamping before the cast.\n\n Args:\n value: A `Tensor`.\n dtype: The desired output `DType`.\n name: A name for the operation (optional).\n\n Returns:\n `value` safely cast to `dtype`.\n '
with ops.name_scope(name, 'saturate_cast', [value]) as name:
value = ops.convert_to_tensor(value, name='value')
dtype = dtypes.as_dtype(dtype).base_dtype
if (value.dtype.min < dtype.min):
value = gen_math_ops.maximum(value, ops.convert_to_tensor(dtype.min, dtype=value.dtype, name='min'))
if (value.dtype.max > dtype.max):
value = gen_math_ops.minimum(value, ops.convert_to_tensor(dtype.max, dtype=value.dtype, name='max'))
return cast(value, dtype, name=name) |
@deprecation.deprecated(date=None, instructions='Use tf.cast instead.')
@tf_export(v1=['to_float'])
def to_float(x, name='ToFloat'):
'Casts a tensor to type `float32`.\n\n Args:\n x: A `Tensor` or `SparseTensor` or `IndexedSlices`.\n name: A name for the operation (optional).\n\n Returns:\n A `Tensor` or `SparseTensor` or `IndexedSlices` with same shape as `x` with\n type `float32`.\n\n Raises:\n TypeError: If `x` cannot be cast to the `float32`.\n '
return cast(x, dtypes.float32, name=name) | -813,214,755,723,743,600 | Casts a tensor to type `float32`.
Args:
x: A `Tensor` or `SparseTensor` or `IndexedSlices`.
name: A name for the operation (optional).
Returns:
A `Tensor` or `SparseTensor` or `IndexedSlices` with same shape as `x` with
type `float32`.
Raises:
TypeError: If `x` cannot be cast to the `float32`. | tensorflow/python/ops/math_ops.py | to_float | minminsun/tensorflow | python | @deprecation.deprecated(date=None, instructions='Use tf.cast instead.')
@tf_export(v1=['to_float'])
def to_float(x, name='ToFloat'):
'Casts a tensor to type `float32`.\n\n Args:\n x: A `Tensor` or `SparseTensor` or `IndexedSlices`.\n name: A name for the operation (optional).\n\n Returns:\n A `Tensor` or `SparseTensor` or `IndexedSlices` with same shape as `x` with\n type `float32`.\n\n Raises:\n TypeError: If `x` cannot be cast to the `float32`.\n '
return cast(x, dtypes.float32, name=name) |
@deprecation.deprecated(date=None, instructions='Use tf.cast instead.')
@tf_export(v1=['to_double'])
def to_double(x, name='ToDouble'):
'Casts a tensor to type `float64`.\n\n Args:\n x: A `Tensor` or `SparseTensor` or `IndexedSlices`.\n name: A name for the operation (optional).\n\n Returns:\n A `Tensor` or `SparseTensor` or `IndexedSlices` with same shape as `x` with\n type `float64`.\n\n Raises:\n TypeError: If `x` cannot be cast to the `float64`.\n '
return cast(x, dtypes.float64, name=name) | 3,930,520,254,991,824,400 | Casts a tensor to type `float64`.
Args:
x: A `Tensor` or `SparseTensor` or `IndexedSlices`.
name: A name for the operation (optional).
Returns:
A `Tensor` or `SparseTensor` or `IndexedSlices` with same shape as `x` with
type `float64`.
Raises:
TypeError: If `x` cannot be cast to the `float64`. | tensorflow/python/ops/math_ops.py | to_double | minminsun/tensorflow | python | @deprecation.deprecated(date=None, instructions='Use tf.cast instead.')
@tf_export(v1=['to_double'])
def to_double(x, name='ToDouble'):
'Casts a tensor to type `float64`.\n\n Args:\n x: A `Tensor` or `SparseTensor` or `IndexedSlices`.\n name: A name for the operation (optional).\n\n Returns:\n A `Tensor` or `SparseTensor` or `IndexedSlices` with same shape as `x` with\n type `float64`.\n\n Raises:\n TypeError: If `x` cannot be cast to the `float64`.\n '
return cast(x, dtypes.float64, name=name) |
@deprecation.deprecated(date=None, instructions='Use tf.cast instead.')
@tf_export(v1=['to_int32'])
def to_int32(x, name='ToInt32'):
'Casts a tensor to type `int32`.\n\n Args:\n x: A `Tensor` or `SparseTensor` or `IndexedSlices`.\n name: A name for the operation (optional).\n\n Returns:\n A `Tensor` or `SparseTensor` or `IndexedSlices` with same shape as `x` with\n type `int32`.\n\n Raises:\n TypeError: If `x` cannot be cast to the `int32`.\n '
return cast(x, dtypes.int32, name=name) | -4,256,511,591,987,859,000 | Casts a tensor to type `int32`.
Args:
x: A `Tensor` or `SparseTensor` or `IndexedSlices`.
name: A name for the operation (optional).
Returns:
A `Tensor` or `SparseTensor` or `IndexedSlices` with same shape as `x` with
type `int32`.
Raises:
TypeError: If `x` cannot be cast to the `int32`. | tensorflow/python/ops/math_ops.py | to_int32 | minminsun/tensorflow | python | @deprecation.deprecated(date=None, instructions='Use tf.cast instead.')
@tf_export(v1=['to_int32'])
def to_int32(x, name='ToInt32'):
'Casts a tensor to type `int32`.\n\n Args:\n x: A `Tensor` or `SparseTensor` or `IndexedSlices`.\n name: A name for the operation (optional).\n\n Returns:\n A `Tensor` or `SparseTensor` or `IndexedSlices` with same shape as `x` with\n type `int32`.\n\n Raises:\n TypeError: If `x` cannot be cast to the `int32`.\n '
return cast(x, dtypes.int32, name=name) |
@deprecation.deprecated(date=None, instructions='Use tf.cast instead.')
@tf_export(v1=['to_int64'])
def to_int64(x, name='ToInt64'):
'Casts a tensor to type `int64`.\n\n Args:\n x: A `Tensor` or `SparseTensor` or `IndexedSlices`.\n name: A name for the operation (optional).\n\n Returns:\n A `Tensor` or `SparseTensor` or `IndexedSlices` with same shape as `x` with\n type `int64`.\n\n Raises:\n TypeError: If `x` cannot be cast to the `int64`.\n '
return cast(x, dtypes.int64, name=name) | -619,806,351,360,548,900 | Casts a tensor to type `int64`.
Args:
x: A `Tensor` or `SparseTensor` or `IndexedSlices`.
name: A name for the operation (optional).
Returns:
A `Tensor` or `SparseTensor` or `IndexedSlices` with same shape as `x` with
type `int64`.
Raises:
TypeError: If `x` cannot be cast to the `int64`. | tensorflow/python/ops/math_ops.py | to_int64 | minminsun/tensorflow | python | @deprecation.deprecated(date=None, instructions='Use tf.cast instead.')
@tf_export(v1=['to_int64'])
def to_int64(x, name='ToInt64'):
'Casts a tensor to type `int64`.\n\n Args:\n x: A `Tensor` or `SparseTensor` or `IndexedSlices`.\n name: A name for the operation (optional).\n\n Returns:\n A `Tensor` or `SparseTensor` or `IndexedSlices` with same shape as `x` with\n type `int64`.\n\n Raises:\n TypeError: If `x` cannot be cast to the `int64`.\n '
return cast(x, dtypes.int64, name=name) |
@deprecation.deprecated(date=None, instructions='Use tf.cast instead.')
@tf_export(v1=['to_bfloat16'])
def to_bfloat16(x, name='ToBFloat16'):
'Casts a tensor to type `bfloat16`.\n\n Args:\n x: A `Tensor` or `SparseTensor` or `IndexedSlices`.\n name: A name for the operation (optional).\n\n Returns:\n A `Tensor` or `SparseTensor` or `IndexedSlices` with same shape as `x` with\n type `bfloat16`.\n\n Raises:\n TypeError: If `x` cannot be cast to the `bfloat16`.\n '
return cast(x, dtypes.bfloat16, name=name) | 4,192,086,204,877,583,400 | Casts a tensor to type `bfloat16`.
Args:
x: A `Tensor` or `SparseTensor` or `IndexedSlices`.
name: A name for the operation (optional).
Returns:
A `Tensor` or `SparseTensor` or `IndexedSlices` with same shape as `x` with
type `bfloat16`.
Raises:
TypeError: If `x` cannot be cast to the `bfloat16`. | tensorflow/python/ops/math_ops.py | to_bfloat16 | minminsun/tensorflow | python | @deprecation.deprecated(date=None, instructions='Use tf.cast instead.')
@tf_export(v1=['to_bfloat16'])
def to_bfloat16(x, name='ToBFloat16'):
'Casts a tensor to type `bfloat16`.\n\n Args:\n x: A `Tensor` or `SparseTensor` or `IndexedSlices`.\n name: A name for the operation (optional).\n\n Returns:\n A `Tensor` or `SparseTensor` or `IndexedSlices` with same shape as `x` with\n type `bfloat16`.\n\n Raises:\n TypeError: If `x` cannot be cast to the `bfloat16`.\n '
return cast(x, dtypes.bfloat16, name=name) |
@deprecation.deprecated(date=None, instructions='Use tf.cast instead.')
@tf_export(v1=['to_complex64'])
def to_complex64(x, name='ToComplex64'):
'Casts a tensor to type `complex64`.\n\n Args:\n x: A `Tensor` or `SparseTensor` or `IndexedSlices`.\n name: A name for the operation (optional).\n\n Returns:\n A `Tensor` or `SparseTensor` or `IndexedSlices` with same shape as `x` with\n type `complex64`.\n\n Raises:\n TypeError: If `x` cannot be cast to the `complex64`.\n '
return cast(x, dtypes.complex64, name=name) | 2,519,490,909,626,641,000 | Casts a tensor to type `complex64`.
Args:
x: A `Tensor` or `SparseTensor` or `IndexedSlices`.
name: A name for the operation (optional).
Returns:
A `Tensor` or `SparseTensor` or `IndexedSlices` with same shape as `x` with
type `complex64`.
Raises:
TypeError: If `x` cannot be cast to the `complex64`. | tensorflow/python/ops/math_ops.py | to_complex64 | minminsun/tensorflow | python | @deprecation.deprecated(date=None, instructions='Use tf.cast instead.')
@tf_export(v1=['to_complex64'])
def to_complex64(x, name='ToComplex64'):
'Casts a tensor to type `complex64`.\n\n Args:\n x: A `Tensor` or `SparseTensor` or `IndexedSlices`.\n name: A name for the operation (optional).\n\n Returns:\n A `Tensor` or `SparseTensor` or `IndexedSlices` with same shape as `x` with\n type `complex64`.\n\n Raises:\n TypeError: If `x` cannot be cast to the `complex64`.\n '
return cast(x, dtypes.complex64, name=name) |
@deprecation.deprecated(date=None, instructions='Use tf.cast instead.')
@tf_export(v1=['to_complex128'])
def to_complex128(x, name='ToComplex128'):
'Casts a tensor to type `complex128`.\n\n Args:\n x: A `Tensor` or `SparseTensor` or `IndexedSlices`.\n name: A name for the operation (optional).\n\n Returns:\n A `Tensor` or `SparseTensor` or `IndexedSlices` with same shape as `x` with\n type `complex128`.\n\n Raises:\n TypeError: If `x` cannot be cast to the `complex128`.\n '
return cast(x, dtypes.complex128, name=name) | -7,577,377,853,692,675,000 | Casts a tensor to type `complex128`.
Args:
x: A `Tensor` or `SparseTensor` or `IndexedSlices`.
name: A name for the operation (optional).
Returns:
A `Tensor` or `SparseTensor` or `IndexedSlices` with same shape as `x` with
type `complex128`.
Raises:
TypeError: If `x` cannot be cast to the `complex128`. | tensorflow/python/ops/math_ops.py | to_complex128 | minminsun/tensorflow | python | @deprecation.deprecated(date=None, instructions='Use tf.cast instead.')
@tf_export(v1=['to_complex128'])
def to_complex128(x, name='ToComplex128'):
'Casts a tensor to type `complex128`.\n\n Args:\n x: A `Tensor` or `SparseTensor` or `IndexedSlices`.\n name: A name for the operation (optional).\n\n Returns:\n A `Tensor` or `SparseTensor` or `IndexedSlices` with same shape as `x` with\n type `complex128`.\n\n Raises:\n TypeError: If `x` cannot be cast to the `complex128`.\n '
return cast(x, dtypes.complex128, name=name) |
def _OverrideBinaryOperatorHelper(func, op_name, clazz_object=ops.Tensor):
'Register operators with different tensor and scalar versions.\n\n If `clazz_object` is `SparseTensor`, assumes `func` takes `(sp_indices,\n sp_values, sp_shape, dense)` and outputs `(new_sp_values)`.\n\n Args:\n func: the operator\n op_name: name of the operator being overridden\n clazz_object: class to override for. Either `Tensor` or `SparseTensor`.\n '
def binary_op_wrapper(x, y):
with ops.name_scope(None, op_name, [x, y]) as name:
if (isinstance(x, ops.Tensor) and isinstance(y, ops.Tensor)):
return func(x, y, name=name)
elif (not isinstance(y, sparse_tensor.SparseTensor)):
try:
y = ops.convert_to_tensor_v2(y, dtype_hint=x.dtype.base_dtype, name='y')
except TypeError:
if hasattr(type(y), ('__r%s__' % op_name)):
return NotImplemented
else:
raise
return func(x, y, name=name)
def binary_op_wrapper_sparse(sp_x, y):
with ops.name_scope(None, op_name, [sp_x, y]) as name:
y = ops.convert_to_tensor(y, dtype=sp_x.dtype.base_dtype, name='y')
return sparse_tensor.SparseTensor(sp_x.indices, func(sp_x.indices, sp_x.values, sp_x.dense_shape, y, name=name), sp_x.dense_shape)
def r_binary_op_wrapper(y, x):
with ops.name_scope(None, op_name, [x, y]) as name:
x = ops.convert_to_tensor(x, dtype=y.dtype.base_dtype, name='x')
return func(x, y, name=name)
try:
doc = func.__doc__
except AttributeError:
doc = None
binary_op_wrapper.__doc__ = doc
r_binary_op_wrapper.__doc__ = doc
binary_op_wrapper_sparse.__doc__ = doc
if (clazz_object is ops.Tensor):
clazz_object._override_operator(('__%s__' % op_name), binary_op_wrapper)
del binary_op_wrapper
clazz_object._override_operator(('__r%s__' % op_name), r_binary_op_wrapper)
del r_binary_op_wrapper
else:
clazz_object._override_operator(('__%s__' % op_name), binary_op_wrapper_sparse)
del binary_op_wrapper_sparse | 3,399,817,921,854,198,000 | Register operators with different tensor and scalar versions.
If `clazz_object` is `SparseTensor`, assumes `func` takes `(sp_indices,
sp_values, sp_shape, dense)` and outputs `(new_sp_values)`.
Args:
func: the operator
op_name: name of the operator being overridden
clazz_object: class to override for. Either `Tensor` or `SparseTensor`. | tensorflow/python/ops/math_ops.py | _OverrideBinaryOperatorHelper | minminsun/tensorflow | python | def _OverrideBinaryOperatorHelper(func, op_name, clazz_object=ops.Tensor):
'Register operators with different tensor and scalar versions.\n\n If `clazz_object` is `SparseTensor`, assumes `func` takes `(sp_indices,\n sp_values, sp_shape, dense)` and outputs `(new_sp_values)`.\n\n Args:\n func: the operator\n op_name: name of the operator being overridden\n clazz_object: class to override for. Either `Tensor` or `SparseTensor`.\n '
def binary_op_wrapper(x, y):
with ops.name_scope(None, op_name, [x, y]) as name:
if (isinstance(x, ops.Tensor) and isinstance(y, ops.Tensor)):
return func(x, y, name=name)
elif (not isinstance(y, sparse_tensor.SparseTensor)):
try:
y = ops.convert_to_tensor_v2(y, dtype_hint=x.dtype.base_dtype, name='y')
except TypeError:
if hasattr(type(y), ('__r%s__' % op_name)):
return NotImplemented
else:
raise
return func(x, y, name=name)
def binary_op_wrapper_sparse(sp_x, y):
with ops.name_scope(None, op_name, [sp_x, y]) as name:
y = ops.convert_to_tensor(y, dtype=sp_x.dtype.base_dtype, name='y')
return sparse_tensor.SparseTensor(sp_x.indices, func(sp_x.indices, sp_x.values, sp_x.dense_shape, y, name=name), sp_x.dense_shape)
def r_binary_op_wrapper(y, x):
with ops.name_scope(None, op_name, [x, y]) as name:
x = ops.convert_to_tensor(x, dtype=y.dtype.base_dtype, name='x')
return func(x, y, name=name)
try:
doc = func.__doc__
except AttributeError:
doc = None
binary_op_wrapper.__doc__ = doc
r_binary_op_wrapper.__doc__ = doc
binary_op_wrapper_sparse.__doc__ = doc
if (clazz_object is ops.Tensor):
clazz_object._override_operator(('__%s__' % op_name), binary_op_wrapper)
del binary_op_wrapper
clazz_object._override_operator(('__r%s__' % op_name), r_binary_op_wrapper)
del r_binary_op_wrapper
else:
clazz_object._override_operator(('__%s__' % op_name), binary_op_wrapper_sparse)
del binary_op_wrapper_sparse |
def _sparse_dense_truediv(sp_indices, sp_values, sp_shape, y, name=None):
"Internal helper function for 'sp_t / dense_t'."
with ops.name_scope(name, 'truediv', [sp_indices, sp_values, sp_shape, y]) as name:
sp_values = ops.convert_to_tensor(sp_values, name='sp_values')
y = ops.convert_to_tensor(y, name='y')
x_dtype = sp_values.dtype.base_dtype
y_dtype = y.dtype.base_dtype
if (x_dtype != y_dtype):
raise TypeError(('x and y must have the same dtype, got %r != %r' % (x_dtype, y_dtype)))
try:
dtype = _TRUEDIV_TABLE[x_dtype]
except KeyError:
raise TypeError(('Invalid dtype %r in __truediv__' % x_dtype))
if (dtype is not None):
sp_values = cast(sp_values, dtype)
y = cast(y, dtype)
return gen_sparse_ops.sparse_dense_cwise_div(sp_indices, sp_values, sp_shape, y, name=name) | -6,240,260,722,322,193,000 | Internal helper function for 'sp_t / dense_t'. | tensorflow/python/ops/math_ops.py | _sparse_dense_truediv | minminsun/tensorflow | python | def _sparse_dense_truediv(sp_indices, sp_values, sp_shape, y, name=None):
with ops.name_scope(name, 'truediv', [sp_indices, sp_values, sp_shape, y]) as name:
sp_values = ops.convert_to_tensor(sp_values, name='sp_values')
y = ops.convert_to_tensor(y, name='y')
x_dtype = sp_values.dtype.base_dtype
y_dtype = y.dtype.base_dtype
if (x_dtype != y_dtype):
raise TypeError(('x and y must have the same dtype, got %r != %r' % (x_dtype, y_dtype)))
try:
dtype = _TRUEDIV_TABLE[x_dtype]
except KeyError:
raise TypeError(('Invalid dtype %r in __truediv__' % x_dtype))
if (dtype is not None):
sp_values = cast(sp_values, dtype)
y = cast(y, dtype)
return gen_sparse_ops.sparse_dense_cwise_div(sp_indices, sp_values, sp_shape, y, name=name) |
def _div_python2(x, y, name=None):
'Divide two values using Python 2 semantics. Used for Tensor.__div__.\n\n Args:\n x: `Tensor` numerator of real numeric type.\n y: `Tensor` denominator of real numeric type.\n name: A name for the operation (optional).\n Returns:\n `x / y` returns the quotient of x and y.\n '
with ops.name_scope(name, 'div', [x, y]) as name:
x = ops.convert_to_tensor(x, name='x')
y = ops.convert_to_tensor(y, name='y', dtype=x.dtype.base_dtype)
x_dtype = x.dtype.base_dtype
y_dtype = y.dtype.base_dtype
if (x_dtype != y_dtype):
raise TypeError(('x and y must have the same dtype, got %r != %r' % (x_dtype, y_dtype)))
if (x_dtype.is_floating or x_dtype.is_complex):
return gen_math_ops.real_div(x, y, name=name)
else:
return gen_math_ops.floor_div(x, y, name=name) | 3,866,777,411,707,680,000 | Divide two values using Python 2 semantics. Used for Tensor.__div__.
Args:
x: `Tensor` numerator of real numeric type.
y: `Tensor` denominator of real numeric type.
name: A name for the operation (optional).
Returns:
`x / y` returns the quotient of x and y. | tensorflow/python/ops/math_ops.py | _div_python2 | minminsun/tensorflow | python | def _div_python2(x, y, name=None):
'Divide two values using Python 2 semantics. Used for Tensor.__div__.\n\n Args:\n x: `Tensor` numerator of real numeric type.\n y: `Tensor` denominator of real numeric type.\n name: A name for the operation (optional).\n Returns:\n `x / y` returns the quotient of x and y.\n '
with ops.name_scope(name, 'div', [x, y]) as name:
x = ops.convert_to_tensor(x, name='x')
y = ops.convert_to_tensor(y, name='y', dtype=x.dtype.base_dtype)
x_dtype = x.dtype.base_dtype
y_dtype = y.dtype.base_dtype
if (x_dtype != y_dtype):
raise TypeError(('x and y must have the same dtype, got %r != %r' % (x_dtype, y_dtype)))
if (x_dtype.is_floating or x_dtype.is_complex):
return gen_math_ops.real_div(x, y, name=name)
else:
return gen_math_ops.floor_div(x, y, name=name) |
@tf_export('math.truediv', 'truediv')
@dispatch.add_dispatch_support
def truediv(x, y, name=None):
'Divides x / y elementwise (using Python 3 division operator semantics).\n\n NOTE: Prefer using the Tensor operator or tf.divide which obey Python\n division operator semantics.\n\n This function forces Python 3 division operator semantics where all integer\n arguments are cast to floating types first. This op is generated by normal\n `x / y` division in Python 3 and in Python 2.7 with\n `from __future__ import division`. If you want integer division that rounds\n down, use `x // y` or `tf.math.floordiv`.\n\n `x` and `y` must have the same numeric type. If the inputs are floating\n point, the output will have the same type. If the inputs are integral, the\n inputs are cast to `float32` for `int8` and `int16` and `float64` for `int32`\n and `int64` (matching the behavior of Numpy).\n\n Args:\n x: `Tensor` numerator of numeric type.\n y: `Tensor` denominator of numeric type.\n name: A name for the operation (optional).\n\n Returns:\n `x / y` evaluated in floating point.\n\n Raises:\n TypeError: If `x` and `y` have different dtypes.\n '
return _truediv_python3(x, y, name) | 4,563,443,741,959,751,000 | Divides x / y elementwise (using Python 3 division operator semantics).
NOTE: Prefer using the Tensor operator or tf.divide which obey Python
division operator semantics.
This function forces Python 3 division operator semantics where all integer
arguments are cast to floating types first. This op is generated by normal
`x / y` division in Python 3 and in Python 2.7 with
`from __future__ import division`. If you want integer division that rounds
down, use `x // y` or `tf.math.floordiv`.
`x` and `y` must have the same numeric type. If the inputs are floating
point, the output will have the same type. If the inputs are integral, the
inputs are cast to `float32` for `int8` and `int16` and `float64` for `int32`
and `int64` (matching the behavior of Numpy).
Args:
x: `Tensor` numerator of numeric type.
y: `Tensor` denominator of numeric type.
name: A name for the operation (optional).
Returns:
`x / y` evaluated in floating point.
Raises:
TypeError: If `x` and `y` have different dtypes. | tensorflow/python/ops/math_ops.py | truediv | minminsun/tensorflow | python | @tf_export('math.truediv', 'truediv')
@dispatch.add_dispatch_support
def truediv(x, y, name=None):
'Divides x / y elementwise (using Python 3 division operator semantics).\n\n NOTE: Prefer using the Tensor operator or tf.divide which obey Python\n division operator semantics.\n\n This function forces Python 3 division operator semantics where all integer\n arguments are cast to floating types first. This op is generated by normal\n `x / y` division in Python 3 and in Python 2.7 with\n `from __future__ import division`. If you want integer division that rounds\n down, use `x // y` or `tf.math.floordiv`.\n\n `x` and `y` must have the same numeric type. If the inputs are floating\n point, the output will have the same type. If the inputs are integral, the\n inputs are cast to `float32` for `int8` and `int16` and `float64` for `int32`\n and `int64` (matching the behavior of Numpy).\n\n Args:\n x: `Tensor` numerator of numeric type.\n y: `Tensor` denominator of numeric type.\n name: A name for the operation (optional).\n\n Returns:\n `x / y` evaluated in floating point.\n\n Raises:\n TypeError: If `x` and `y` have different dtypes.\n '
return _truediv_python3(x, y, name) |
@deprecation.deprecated(date=None, instructions='Deprecated in favor of operator or tf.math.divide.')
@tf_export(v1=['div'])
def div(x, y, name=None):
'Divides x / y elementwise (using Python 2 division operator semantics).\n\n NOTE: Prefer using the Tensor division operator or tf.divide which obey Python\n division operator semantics.\n\n This function divides `x` and `y`, forcing Python 2.7 semantics. That is,\n if one of `x` or `y` is a float, then the result will be a float.\n Otherwise, the output will be an integer type. Flooring semantics are used\n for integer division.\n\n Args:\n x: `Tensor` numerator of real numeric type.\n y: `Tensor` denominator of real numeric type.\n name: A name for the operation (optional).\n Returns:\n `x / y` returns the quotient of x and y.\n '
return _div_python2(x, y, name) | -2,647,516,656,319,070,000 | Divides x / y elementwise (using Python 2 division operator semantics).
NOTE: Prefer using the Tensor division operator or tf.divide which obey Python
division operator semantics.
This function divides `x` and `y`, forcing Python 2.7 semantics. That is,
if one of `x` or `y` is a float, then the result will be a float.
Otherwise, the output will be an integer type. Flooring semantics are used
for integer division.
Args:
x: `Tensor` numerator of real numeric type.
y: `Tensor` denominator of real numeric type.
name: A name for the operation (optional).
Returns:
`x / y` returns the quotient of x and y. | tensorflow/python/ops/math_ops.py | div | minminsun/tensorflow | python | @deprecation.deprecated(date=None, instructions='Deprecated in favor of operator or tf.math.divide.')
@tf_export(v1=['div'])
def div(x, y, name=None):
'Divides x / y elementwise (using Python 2 division operator semantics).\n\n NOTE: Prefer using the Tensor division operator or tf.divide which obey Python\n division operator semantics.\n\n This function divides `x` and `y`, forcing Python 2.7 semantics. That is,\n if one of `x` or `y` is a float, then the result will be a float.\n Otherwise, the output will be an integer type. Flooring semantics are used\n for integer division.\n\n Args:\n x: `Tensor` numerator of real numeric type.\n y: `Tensor` denominator of real numeric type.\n name: A name for the operation (optional).\n Returns:\n `x / y` returns the quotient of x and y.\n '
return _div_python2(x, y, name) |
@tf_export('div_no_nan')
@dispatch.add_dispatch_support
def div_no_nan(x, y, name=None):
'Computes an unsafe divide which returns 0 if the y is zero.\n\n Args:\n x: A `Tensor`. Must be one of the following types: `float32`, `float64`.\n y: A `Tensor` whose dtype is compatible with `x`.\n name: A name for the operation (optional).\n Returns:\n The element-wise value of the x divided by y.\n '
with ops.name_scope(name, 'div_no_nan', [x, y]) as name:
x = ops.convert_to_tensor(x, name='x')
y = ops.convert_to_tensor(y, name='y', dtype=x.dtype.base_dtype)
x_dtype = x.dtype.base_dtype
y_dtype = y.dtype.base_dtype
if (x_dtype != y_dtype):
raise TypeError(('x and y must have the same dtype, got %r != %r' % (x_dtype, y_dtype)))
return gen_math_ops.div_no_nan(x, y, name=name) | 1,129,862,942,993,974,500 | Computes an unsafe divide which returns 0 if the y is zero.
Args:
x: A `Tensor`. Must be one of the following types: `float32`, `float64`.
y: A `Tensor` whose dtype is compatible with `x`.
name: A name for the operation (optional).
Returns:
The element-wise value of the x divided by y. | tensorflow/python/ops/math_ops.py | div_no_nan | minminsun/tensorflow | python | @tf_export('div_no_nan')
@dispatch.add_dispatch_support
def div_no_nan(x, y, name=None):
'Computes an unsafe divide which returns 0 if the y is zero.\n\n Args:\n x: A `Tensor`. Must be one of the following types: `float32`, `float64`.\n y: A `Tensor` whose dtype is compatible with `x`.\n name: A name for the operation (optional).\n Returns:\n The element-wise value of the x divided by y.\n '
with ops.name_scope(name, 'div_no_nan', [x, y]) as name:
x = ops.convert_to_tensor(x, name='x')
y = ops.convert_to_tensor(y, name='y', dtype=x.dtype.base_dtype)
x_dtype = x.dtype.base_dtype
y_dtype = y.dtype.base_dtype
if (x_dtype != y_dtype):
raise TypeError(('x and y must have the same dtype, got %r != %r' % (x_dtype, y_dtype)))
return gen_math_ops.div_no_nan(x, y, name=name) |
@tf_export('math.floordiv', v1=['math.floordiv', 'floordiv'])
@dispatch.add_dispatch_support
@deprecation.deprecated_endpoints('floordiv')
def floordiv(x, y, name=None):
'Divides `x / y` elementwise, rounding toward the most negative integer.\n\n The same as `tf.div(x,y)` for integers, but uses `tf.floor(tf.div(x,y))` for\n floating point arguments so that the result is always an integer (though\n possibly an integer represented as floating point). This op is generated by\n `x // y` floor division in Python 3 and in Python 2.7 with\n `from __future__ import division`.\n\n `x` and `y` must have the same type, and the result will have the same type\n as well.\n\n Args:\n x: `Tensor` numerator of real numeric type.\n y: `Tensor` denominator of real numeric type.\n name: A name for the operation (optional).\n\n Returns:\n `x / y` rounded down.\n\n Raises:\n TypeError: If the inputs are complex.\n '
with ops.name_scope(name, 'floordiv', [x, y]) as name:
return gen_math_ops.floor_div(x, y, name=name) | 7,450,040,279,089,519,000 | Divides `x / y` elementwise, rounding toward the most negative integer.
The same as `tf.div(x,y)` for integers, but uses `tf.floor(tf.div(x,y))` for
floating point arguments so that the result is always an integer (though
possibly an integer represented as floating point). This op is generated by
`x // y` floor division in Python 3 and in Python 2.7 with
`from __future__ import division`.
`x` and `y` must have the same type, and the result will have the same type
as well.
Args:
x: `Tensor` numerator of real numeric type.
y: `Tensor` denominator of real numeric type.
name: A name for the operation (optional).
Returns:
`x / y` rounded down.
Raises:
TypeError: If the inputs are complex. | tensorflow/python/ops/math_ops.py | floordiv | minminsun/tensorflow | python | @tf_export('math.floordiv', v1=['math.floordiv', 'floordiv'])
@dispatch.add_dispatch_support
@deprecation.deprecated_endpoints('floordiv')
def floordiv(x, y, name=None):
'Divides `x / y` elementwise, rounding toward the most negative integer.\n\n The same as `tf.div(x,y)` for integers, but uses `tf.floor(tf.div(x,y))` for\n floating point arguments so that the result is always an integer (though\n possibly an integer represented as floating point). This op is generated by\n `x // y` floor division in Python 3 and in Python 2.7 with\n `from __future__ import division`.\n\n `x` and `y` must have the same type, and the result will have the same type\n as well.\n\n Args:\n x: `Tensor` numerator of real numeric type.\n y: `Tensor` denominator of real numeric type.\n name: A name for the operation (optional).\n\n Returns:\n `x / y` rounded down.\n\n Raises:\n TypeError: If the inputs are complex.\n '
with ops.name_scope(name, 'floordiv', [x, y]) as name:
return gen_math_ops.floor_div(x, y, name=name) |
def _mul_dispatch(x, y, name=None):
'Dispatches cwise mul for "Dense*Dense" and "Dense*Sparse".'
is_tensor_y = isinstance(y, ops.Tensor)
if is_tensor_y:
return gen_math_ops.mul(x, y, name=name)
else:
assert isinstance(y, sparse_tensor.SparseTensor)
new_vals = gen_sparse_ops.sparse_dense_cwise_mul(y.indices, y.values, y.dense_shape, x, name)
return sparse_tensor.SparseTensor(y.indices, new_vals, y.dense_shape) | 3,161,422,901,298,774,000 | Dispatches cwise mul for "Dense*Dense" and "Dense*Sparse". | tensorflow/python/ops/math_ops.py | _mul_dispatch | minminsun/tensorflow | python | def _mul_dispatch(x, y, name=None):
is_tensor_y = isinstance(y, ops.Tensor)
if is_tensor_y:
return gen_math_ops.mul(x, y, name=name)
else:
assert isinstance(y, sparse_tensor.SparseTensor)
new_vals = gen_sparse_ops.sparse_dense_cwise_mul(y.indices, y.values, y.dense_shape, x, name)
return sparse_tensor.SparseTensor(y.indices, new_vals, y.dense_shape) |
@tf_export('math.logical_xor', v1=['math.logical_xor', 'logical_xor'])
@dispatch.add_dispatch_support
@deprecation.deprecated_endpoints('logical_xor')
def logical_xor(x, y, name='LogicalXor'):
'x ^ y = (x | y) & ~(x & y).'
return gen_math_ops.logical_and(gen_math_ops.logical_or(x, y), gen_math_ops.logical_not(gen_math_ops.logical_and(x, y)), name=name) | 7,408,680,893,332,393,000 | x ^ y = (x | y) & ~(x & y). | tensorflow/python/ops/math_ops.py | logical_xor | minminsun/tensorflow | python | @tf_export('math.logical_xor', v1=['math.logical_xor', 'logical_xor'])
@dispatch.add_dispatch_support
@deprecation.deprecated_endpoints('logical_xor')
def logical_xor(x, y, name='LogicalXor'):
return gen_math_ops.logical_and(gen_math_ops.logical_or(x, y), gen_math_ops.logical_not(gen_math_ops.logical_and(x, y)), name=name) |
@tf_export('range')
def range(start, limit=None, delta=1, dtype=None, name='range'):
'Creates a sequence of numbers.\n\n Creates a sequence of numbers that begins at `start` and extends by\n increments of `delta` up to but not including `limit`.\n\n The dtype of the resulting tensor is inferred from the inputs unless\n it is provided explicitly.\n\n Like the Python builtin `range`, `start` defaults to 0, so that\n `range(n) = range(0, n)`.\n\n For example:\n\n ```python\n start = 3\n limit = 18\n delta = 3\n tf.range(start, limit, delta) # [3, 6, 9, 12, 15]\n\n start = 3\n limit = 1\n delta = -0.5\n tf.range(start, limit, delta) # [3, 2.5, 2, 1.5]\n\n limit = 5\n tf.range(limit) # [0, 1, 2, 3, 4]\n ```\n\n Args:\n start: A 0-D `Tensor` (scalar). Acts as first entry in the range if\n `limit` is not None; otherwise, acts as range limit and first entry\n defaults to 0.\n limit: A 0-D `Tensor` (scalar). Upper limit of sequence,\n exclusive. If None, defaults to the value of `start` while the first\n entry of the range defaults to 0.\n delta: A 0-D `Tensor` (scalar). Number that increments\n `start`. Defaults to 1.\n dtype: The type of the elements of the resulting tensor.\n name: A name for the operation. Defaults to "range".\n\n Returns:\n An 1-D `Tensor` of type `dtype`.\n\n @compatibility(numpy)\n Equivalent to np.arange\n @end_compatibility\n '
if (limit is None):
(start, limit) = (0, start)
with ops.name_scope(name, 'Range', [start, limit, delta]) as name:
start = ops.convert_to_tensor(start, dtype=dtype, name='start')
limit = ops.convert_to_tensor(limit, dtype=dtype, name='limit')
delta = ops.convert_to_tensor(delta, dtype=dtype, name='delta')
if (dtype is None):
dtype_hierarchy = [dtypes.int32, dtypes.int64, dtypes.float32, dtypes.float64]
assert all(((arg.dtype in dtype_hierarchy) for arg in [start, limit, delta]))
inferred_dtype = max([arg.dtype for arg in [start, limit, delta]], key=dtype_hierarchy.index)
start = cast(start, inferred_dtype)
limit = cast(limit, inferred_dtype)
delta = cast(delta, inferred_dtype)
return gen_math_ops._range(start, limit, delta, name=name) | 2,806,946,857,738,272,000 | Creates a sequence of numbers.
Creates a sequence of numbers that begins at `start` and extends by
increments of `delta` up to but not including `limit`.
The dtype of the resulting tensor is inferred from the inputs unless
it is provided explicitly.
Like the Python builtin `range`, `start` defaults to 0, so that
`range(n) = range(0, n)`.
For example:
```python
start = 3
limit = 18
delta = 3
tf.range(start, limit, delta) # [3, 6, 9, 12, 15]
start = 3
limit = 1
delta = -0.5
tf.range(start, limit, delta) # [3, 2.5, 2, 1.5]
limit = 5
tf.range(limit) # [0, 1, 2, 3, 4]
```
Args:
start: A 0-D `Tensor` (scalar). Acts as first entry in the range if
`limit` is not None; otherwise, acts as range limit and first entry
defaults to 0.
limit: A 0-D `Tensor` (scalar). Upper limit of sequence,
exclusive. If None, defaults to the value of `start` while the first
entry of the range defaults to 0.
delta: A 0-D `Tensor` (scalar). Number that increments
`start`. Defaults to 1.
dtype: The type of the elements of the resulting tensor.
name: A name for the operation. Defaults to "range".
Returns:
An 1-D `Tensor` of type `dtype`.
@compatibility(numpy)
Equivalent to np.arange
@end_compatibility | tensorflow/python/ops/math_ops.py | range | minminsun/tensorflow | python | @tf_export('range')
def range(start, limit=None, delta=1, dtype=None, name='range'):
'Creates a sequence of numbers.\n\n Creates a sequence of numbers that begins at `start` and extends by\n increments of `delta` up to but not including `limit`.\n\n The dtype of the resulting tensor is inferred from the inputs unless\n it is provided explicitly.\n\n Like the Python builtin `range`, `start` defaults to 0, so that\n `range(n) = range(0, n)`.\n\n For example:\n\n ```python\n start = 3\n limit = 18\n delta = 3\n tf.range(start, limit, delta) # [3, 6, 9, 12, 15]\n\n start = 3\n limit = 1\n delta = -0.5\n tf.range(start, limit, delta) # [3, 2.5, 2, 1.5]\n\n limit = 5\n tf.range(limit) # [0, 1, 2, 3, 4]\n ```\n\n Args:\n start: A 0-D `Tensor` (scalar). Acts as first entry in the range if\n `limit` is not None; otherwise, acts as range limit and first entry\n defaults to 0.\n limit: A 0-D `Tensor` (scalar). Upper limit of sequence,\n exclusive. If None, defaults to the value of `start` while the first\n entry of the range defaults to 0.\n delta: A 0-D `Tensor` (scalar). Number that increments\n `start`. Defaults to 1.\n dtype: The type of the elements of the resulting tensor.\n name: A name for the operation. Defaults to "range".\n\n Returns:\n An 1-D `Tensor` of type `dtype`.\n\n @compatibility(numpy)\n Equivalent to np.arange\n @end_compatibility\n '
if (limit is None):
(start, limit) = (0, start)
with ops.name_scope(name, 'Range', [start, limit, delta]) as name:
start = ops.convert_to_tensor(start, dtype=dtype, name='start')
limit = ops.convert_to_tensor(limit, dtype=dtype, name='limit')
delta = ops.convert_to_tensor(delta, dtype=dtype, name='delta')
if (dtype is None):
dtype_hierarchy = [dtypes.int32, dtypes.int64, dtypes.float32, dtypes.float64]
assert all(((arg.dtype in dtype_hierarchy) for arg in [start, limit, delta]))
inferred_dtype = max([arg.dtype for arg in [start, limit, delta]], key=dtype_hierarchy.index)
start = cast(start, inferred_dtype)
limit = cast(limit, inferred_dtype)
delta = cast(delta, inferred_dtype)
return gen_math_ops._range(start, limit, delta, name=name) |
def _ReductionDims(x, axis, reduction_indices=None):
'Returns range(0, rank(x)) if reduction_indices is None.'
if (reduction_indices is not None):
if (axis is not None):
raise ValueError("Can't specify both axis' and 'reduction_indices'.")
axis = reduction_indices
if (axis is not None):
return axis
else:
rank = common_shapes.rank(x)
if (rank is not None):
return constant_op.constant(np.arange(rank), dtype=dtypes.int32)
if (isinstance(x, sparse_tensor.SparseTensor) and x.dense_shape.shape.is_fully_defined()):
rank = x.dense_shape.shape.dims[0].value
return constant_op.constant(np.arange(rank), dtype=dtypes.int32)
return range(0, array_ops.rank(x)) | -1,727,942,052,001,307,100 | Returns range(0, rank(x)) if reduction_indices is None. | tensorflow/python/ops/math_ops.py | _ReductionDims | minminsun/tensorflow | python | def _ReductionDims(x, axis, reduction_indices=None):
if (reduction_indices is not None):
if (axis is not None):
raise ValueError("Can't specify both axis' and 'reduction_indices'.")
axis = reduction_indices
if (axis is not None):
return axis
else:
rank = common_shapes.rank(x)
if (rank is not None):
return constant_op.constant(np.arange(rank), dtype=dtypes.int32)
if (isinstance(x, sparse_tensor.SparseTensor) and x.dense_shape.shape.is_fully_defined()):
rank = x.dense_shape.shape.dims[0].value
return constant_op.constant(np.arange(rank), dtype=dtypes.int32)
return range(0, array_ops.rank(x)) |
def _may_reduce_to_scalar(keepdims, axis, output):
"Set a reduction's output shape to be a scalar if we are certain."
if ((not common_shapes.has_fully_defined_shape(output)) and (not keepdims) and (axis is None)):
output.set_shape(())
return output | -7,311,594,891,318,815,000 | Set a reduction's output shape to be a scalar if we are certain. | tensorflow/python/ops/math_ops.py | _may_reduce_to_scalar | minminsun/tensorflow | python | def _may_reduce_to_scalar(keepdims, axis, output):
if ((not common_shapes.has_fully_defined_shape(output)) and (not keepdims) and (axis is None)):
output.set_shape(())
return output |
@tf_export(v1=['math.reduce_sum', 'reduce_sum'])
@deprecation.deprecated_args(None, 'keep_dims is deprecated, use keepdims instead', 'keep_dims')
def reduce_sum_v1(input_tensor, axis=None, keepdims=None, name=None, reduction_indices=None, keep_dims=None):
'Computes the sum of elements across dimensions of a tensor.\n\n Reduces `input_tensor` along the dimensions given in `axis`.\n Unless `keepdims` is true, the rank of the tensor is reduced by 1 for each\n entry in `axis`. If `keepdims` is true, the reduced dimensions\n are retained with length 1.\n\n If `axis` is None, all dimensions are reduced, and a\n tensor with a single element is returned.\n\n For example:\n\n ```python\n x = tf.constant([[1, 1, 1], [1, 1, 1]])\n tf.reduce_sum(x) # 6\n tf.reduce_sum(x, 0) # [2, 2, 2]\n tf.reduce_sum(x, 1) # [3, 3]\n tf.reduce_sum(x, 1, keepdims=True) # [[3], [3]]\n tf.reduce_sum(x, [0, 1]) # 6\n ```\n\n Args:\n input_tensor: The tensor to reduce. Should have numeric type.\n axis: The dimensions to reduce. If `None` (the default),\n reduces all dimensions. Must be in the range\n `[-rank(input_tensor), rank(input_tensor))`.\n keepdims: If true, retains reduced dimensions with length 1.\n name: A name for the operation (optional).\n reduction_indices: The old (deprecated) name for axis.\n keep_dims: Deprecated alias for `keepdims`.\n\n Returns:\n The reduced tensor, of the same dtype as the input_tensor.\n\n @compatibility(numpy)\n Equivalent to np.sum apart the fact that numpy upcast uint8 and int32 to\n int64 while tensorflow returns the same dtype as the input.\n @end_compatibility\n '
axis = deprecation.deprecated_argument_lookup('axis', axis, 'reduction_indices', reduction_indices)
keepdims = deprecation.deprecated_argument_lookup('keepdims', keepdims, 'keep_dims', keep_dims)
return reduce_sum(input_tensor, axis, keepdims, name) | -643,192,823,238,918,900 | Computes the sum of elements across dimensions of a tensor.
Reduces `input_tensor` along the dimensions given in `axis`.
Unless `keepdims` is true, the rank of the tensor is reduced by 1 for each
entry in `axis`. If `keepdims` is true, the reduced dimensions
are retained with length 1.
If `axis` is None, all dimensions are reduced, and a
tensor with a single element is returned.
For example:
```python
x = tf.constant([[1, 1, 1], [1, 1, 1]])
tf.reduce_sum(x) # 6
tf.reduce_sum(x, 0) # [2, 2, 2]
tf.reduce_sum(x, 1) # [3, 3]
tf.reduce_sum(x, 1, keepdims=True) # [[3], [3]]
tf.reduce_sum(x, [0, 1]) # 6
```
Args:
input_tensor: The tensor to reduce. Should have numeric type.
axis: The dimensions to reduce. If `None` (the default),
reduces all dimensions. Must be in the range
`[-rank(input_tensor), rank(input_tensor))`.
keepdims: If true, retains reduced dimensions with length 1.
name: A name for the operation (optional).
reduction_indices: The old (deprecated) name for axis.
keep_dims: Deprecated alias for `keepdims`.
Returns:
The reduced tensor, of the same dtype as the input_tensor.
@compatibility(numpy)
Equivalent to np.sum apart the fact that numpy upcast uint8 and int32 to
int64 while tensorflow returns the same dtype as the input.
@end_compatibility | tensorflow/python/ops/math_ops.py | reduce_sum_v1 | minminsun/tensorflow | python | @tf_export(v1=['math.reduce_sum', 'reduce_sum'])
@deprecation.deprecated_args(None, 'keep_dims is deprecated, use keepdims instead', 'keep_dims')
def reduce_sum_v1(input_tensor, axis=None, keepdims=None, name=None, reduction_indices=None, keep_dims=None):
'Computes the sum of elements across dimensions of a tensor.\n\n Reduces `input_tensor` along the dimensions given in `axis`.\n Unless `keepdims` is true, the rank of the tensor is reduced by 1 for each\n entry in `axis`. If `keepdims` is true, the reduced dimensions\n are retained with length 1.\n\n If `axis` is None, all dimensions are reduced, and a\n tensor with a single element is returned.\n\n For example:\n\n ```python\n x = tf.constant([[1, 1, 1], [1, 1, 1]])\n tf.reduce_sum(x) # 6\n tf.reduce_sum(x, 0) # [2, 2, 2]\n tf.reduce_sum(x, 1) # [3, 3]\n tf.reduce_sum(x, 1, keepdims=True) # [[3], [3]]\n tf.reduce_sum(x, [0, 1]) # 6\n ```\n\n Args:\n input_tensor: The tensor to reduce. Should have numeric type.\n axis: The dimensions to reduce. If `None` (the default),\n reduces all dimensions. Must be in the range\n `[-rank(input_tensor), rank(input_tensor))`.\n keepdims: If true, retains reduced dimensions with length 1.\n name: A name for the operation (optional).\n reduction_indices: The old (deprecated) name for axis.\n keep_dims: Deprecated alias for `keepdims`.\n\n Returns:\n The reduced tensor, of the same dtype as the input_tensor.\n\n @compatibility(numpy)\n Equivalent to np.sum apart the fact that numpy upcast uint8 and int32 to\n int64 while tensorflow returns the same dtype as the input.\n @end_compatibility\n '
axis = deprecation.deprecated_argument_lookup('axis', axis, 'reduction_indices', reduction_indices)
keepdims = deprecation.deprecated_argument_lookup('keepdims', keepdims, 'keep_dims', keep_dims)
return reduce_sum(input_tensor, axis, keepdims, name) |
@tf_export('math.reduce_sum', 'reduce_sum', v1=[])
@dispatch.add_dispatch_support
def reduce_sum(input_tensor, axis=None, keepdims=False, name=None):
'Computes the sum of elements across dimensions of a tensor.\n\n Reduces `input_tensor` along the dimensions given in `axis`.\n Unless `keepdims` is true, the rank of the tensor is reduced by 1 for each\n entry in `axis`. If `keepdims` is true, the reduced dimensions\n are retained with length 1.\n\n If `axis` is None, all dimensions are reduced, and a\n tensor with a single element is returned.\n\n For example:\n\n ```python\n x = tf.constant([[1, 1, 1], [1, 1, 1]])\n tf.reduce_sum(x) # 6\n tf.reduce_sum(x, 0) # [2, 2, 2]\n tf.reduce_sum(x, 1) # [3, 3]\n tf.reduce_sum(x, 1, keepdims=True) # [[3], [3]]\n tf.reduce_sum(x, [0, 1]) # 6\n ```\n\n Args:\n input_tensor: The tensor to reduce. Should have numeric type.\n axis: The dimensions to reduce. If `None` (the default), reduces all\n dimensions. Must be in the range `[-rank(input_tensor),\n rank(input_tensor))`.\n keepdims: If true, retains reduced dimensions with length 1.\n name: A name for the operation (optional).\n\n Returns:\n The reduced tensor, of the same dtype as the input_tensor.\n\n @compatibility(numpy)\n Equivalent to np.sum apart the fact that numpy upcast uint8 and int32 to\n int64 while tensorflow returns the same dtype as the input.\n @end_compatibility\n '
keepdims = (False if (keepdims is None) else keepdims)
return _may_reduce_to_scalar(keepdims, axis, gen_math_ops._sum(input_tensor, _ReductionDims(input_tensor, axis), keepdims, name=name)) | -6,350,055,839,824,817,000 | Computes the sum of elements across dimensions of a tensor.
Reduces `input_tensor` along the dimensions given in `axis`.
Unless `keepdims` is true, the rank of the tensor is reduced by 1 for each
entry in `axis`. If `keepdims` is true, the reduced dimensions
are retained with length 1.
If `axis` is None, all dimensions are reduced, and a
tensor with a single element is returned.
For example:
```python
x = tf.constant([[1, 1, 1], [1, 1, 1]])
tf.reduce_sum(x) # 6
tf.reduce_sum(x, 0) # [2, 2, 2]
tf.reduce_sum(x, 1) # [3, 3]
tf.reduce_sum(x, 1, keepdims=True) # [[3], [3]]
tf.reduce_sum(x, [0, 1]) # 6
```
Args:
input_tensor: The tensor to reduce. Should have numeric type.
axis: The dimensions to reduce. If `None` (the default), reduces all
dimensions. Must be in the range `[-rank(input_tensor),
rank(input_tensor))`.
keepdims: If true, retains reduced dimensions with length 1.
name: A name for the operation (optional).
Returns:
The reduced tensor, of the same dtype as the input_tensor.
@compatibility(numpy)
Equivalent to np.sum apart the fact that numpy upcast uint8 and int32 to
int64 while tensorflow returns the same dtype as the input.
@end_compatibility | tensorflow/python/ops/math_ops.py | reduce_sum | minminsun/tensorflow | python | @tf_export('math.reduce_sum', 'reduce_sum', v1=[])
@dispatch.add_dispatch_support
def reduce_sum(input_tensor, axis=None, keepdims=False, name=None):
'Computes the sum of elements across dimensions of a tensor.\n\n Reduces `input_tensor` along the dimensions given in `axis`.\n Unless `keepdims` is true, the rank of the tensor is reduced by 1 for each\n entry in `axis`. If `keepdims` is true, the reduced dimensions\n are retained with length 1.\n\n If `axis` is None, all dimensions are reduced, and a\n tensor with a single element is returned.\n\n For example:\n\n ```python\n x = tf.constant([[1, 1, 1], [1, 1, 1]])\n tf.reduce_sum(x) # 6\n tf.reduce_sum(x, 0) # [2, 2, 2]\n tf.reduce_sum(x, 1) # [3, 3]\n tf.reduce_sum(x, 1, keepdims=True) # [[3], [3]]\n tf.reduce_sum(x, [0, 1]) # 6\n ```\n\n Args:\n input_tensor: The tensor to reduce. Should have numeric type.\n axis: The dimensions to reduce. If `None` (the default), reduces all\n dimensions. Must be in the range `[-rank(input_tensor),\n rank(input_tensor))`.\n keepdims: If true, retains reduced dimensions with length 1.\n name: A name for the operation (optional).\n\n Returns:\n The reduced tensor, of the same dtype as the input_tensor.\n\n @compatibility(numpy)\n Equivalent to np.sum apart the fact that numpy upcast uint8 and int32 to\n int64 while tensorflow returns the same dtype as the input.\n @end_compatibility\n '
keepdims = (False if (keepdims is None) else keepdims)
return _may_reduce_to_scalar(keepdims, axis, gen_math_ops._sum(input_tensor, _ReductionDims(input_tensor, axis), keepdims, name=name)) |
@tf_export(v1=['math.count_nonzero', 'count_nonzero'])
@deprecation.deprecated_args(None, 'keep_dims is deprecated, use keepdims instead', 'keep_dims')
@deprecation.deprecated_args(None, 'reduction_indices is deprecated, use axis instead', 'axis')
def count_nonzero(input_tensor, axis=None, keepdims=None, dtype=dtypes.int64, name=None, reduction_indices=None, keep_dims=None):
'Computes number of nonzero elements across dimensions of a tensor.\n\n Reduces `input_tensor` along the dimensions given in `axis`.\n Unless `keepdims` is true, the rank of the tensor is reduced by 1 for each\n entry in `axis`. If `keepdims` is true, the reduced dimensions\n are retained with length 1.\n\n If `axis` has no entries, all dimensions are reduced, and a\n tensor with a single element is returned.\n\n **NOTE** Floating point comparison to zero is done by exact floating point\n equality check. Small values are **not** rounded to zero for purposes of\n the nonzero check.\n\n For example:\n\n ```python\n x = tf.constant([[0, 1, 0], [1, 1, 0]])\n tf.count_nonzero(x) # 3\n tf.count_nonzero(x, 0) # [1, 2, 0]\n tf.count_nonzero(x, 1) # [1, 2]\n tf.count_nonzero(x, 1, keepdims=True) # [[1], [2]]\n tf.count_nonzero(x, [0, 1]) # 3\n ```\n\n **NOTE** Strings are compared against zero-length empty string `""`. Any\n string with a size greater than zero is already considered as nonzero.\n\n For example:\n ```python\n x = tf.constant(["", "a", " ", "b", ""])\n tf.count_nonzero(x) # 3, with "a", " ", and "b" as nonzero strings.\n ```\n\n Args:\n input_tensor: The tensor to reduce. Should be of numeric type, `bool`,\n or `string`.\n axis: The dimensions to reduce. If `None` (the default),\n reduces all dimensions. Must be in the range\n `[-rank(input_tensor), rank(input_tensor))`.\n keepdims: If true, retains reduced dimensions with length 1.\n dtype: The output dtype; defaults to `tf.int64`.\n name: A name for the operation (optional).\n reduction_indices: The old (deprecated) name for axis.\n keep_dims: Deprecated alias for `keepdims`.\n\n Returns:\n The reduced tensor (number of nonzero values).\n '
keepdims = deprecation.deprecated_argument_lookup('keepdims', keepdims, 'keep_dims', keep_dims)
axis = deprecation.deprecated_argument_lookup('axis', axis, 'reduction_indices', reduction_indices)
return count_nonzero_v2(input_tensor, axis, keepdims, dtype, name) | 7,200,931,276,229,210,000 | Computes number of nonzero elements across dimensions of a tensor.
Reduces `input_tensor` along the dimensions given in `axis`.
Unless `keepdims` is true, the rank of the tensor is reduced by 1 for each
entry in `axis`. If `keepdims` is true, the reduced dimensions
are retained with length 1.
If `axis` has no entries, all dimensions are reduced, and a
tensor with a single element is returned.
**NOTE** Floating point comparison to zero is done by exact floating point
equality check. Small values are **not** rounded to zero for purposes of
the nonzero check.
For example:
```python
x = tf.constant([[0, 1, 0], [1, 1, 0]])
tf.count_nonzero(x) # 3
tf.count_nonzero(x, 0) # [1, 2, 0]
tf.count_nonzero(x, 1) # [1, 2]
tf.count_nonzero(x, 1, keepdims=True) # [[1], [2]]
tf.count_nonzero(x, [0, 1]) # 3
```
**NOTE** Strings are compared against zero-length empty string `""`. Any
string with a size greater than zero is already considered as nonzero.
For example:
```python
x = tf.constant(["", "a", " ", "b", ""])
tf.count_nonzero(x) # 3, with "a", " ", and "b" as nonzero strings.
```
Args:
input_tensor: The tensor to reduce. Should be of numeric type, `bool`,
or `string`.
axis: The dimensions to reduce. If `None` (the default),
reduces all dimensions. Must be in the range
`[-rank(input_tensor), rank(input_tensor))`.
keepdims: If true, retains reduced dimensions with length 1.
dtype: The output dtype; defaults to `tf.int64`.
name: A name for the operation (optional).
reduction_indices: The old (deprecated) name for axis.
keep_dims: Deprecated alias for `keepdims`.
Returns:
The reduced tensor (number of nonzero values). | tensorflow/python/ops/math_ops.py | count_nonzero | minminsun/tensorflow | python | @tf_export(v1=['math.count_nonzero', 'count_nonzero'])
@deprecation.deprecated_args(None, 'keep_dims is deprecated, use keepdims instead', 'keep_dims')
@deprecation.deprecated_args(None, 'reduction_indices is deprecated, use axis instead', 'axis')
def count_nonzero(input_tensor, axis=None, keepdims=None, dtype=dtypes.int64, name=None, reduction_indices=None, keep_dims=None):
'Computes number of nonzero elements across dimensions of a tensor.\n\n Reduces `input_tensor` along the dimensions given in `axis`.\n Unless `keepdims` is true, the rank of the tensor is reduced by 1 for each\n entry in `axis`. If `keepdims` is true, the reduced dimensions\n are retained with length 1.\n\n If `axis` has no entries, all dimensions are reduced, and a\n tensor with a single element is returned.\n\n **NOTE** Floating point comparison to zero is done by exact floating point\n equality check. Small values are **not** rounded to zero for purposes of\n the nonzero check.\n\n For example:\n\n ```python\n x = tf.constant([[0, 1, 0], [1, 1, 0]])\n tf.count_nonzero(x) # 3\n tf.count_nonzero(x, 0) # [1, 2, 0]\n tf.count_nonzero(x, 1) # [1, 2]\n tf.count_nonzero(x, 1, keepdims=True) # [[1], [2]]\n tf.count_nonzero(x, [0, 1]) # 3\n ```\n\n **NOTE** Strings are compared against zero-length empty string ``. Any\n string with a size greater than zero is already considered as nonzero.\n\n For example:\n ```python\n x = tf.constant([, "a", " ", "b", ])\n tf.count_nonzero(x) # 3, with "a", " ", and "b" as nonzero strings.\n ```\n\n Args:\n input_tensor: The tensor to reduce. Should be of numeric type, `bool`,\n or `string`.\n axis: The dimensions to reduce. If `None` (the default),\n reduces all dimensions. Must be in the range\n `[-rank(input_tensor), rank(input_tensor))`.\n keepdims: If true, retains reduced dimensions with length 1.\n dtype: The output dtype; defaults to `tf.int64`.\n name: A name for the operation (optional).\n reduction_indices: The old (deprecated) name for axis.\n keep_dims: Deprecated alias for `keepdims`.\n\n Returns:\n The reduced tensor (number of nonzero values).\n '
keepdims = deprecation.deprecated_argument_lookup('keepdims', keepdims, 'keep_dims', keep_dims)
axis = deprecation.deprecated_argument_lookup('axis', axis, 'reduction_indices', reduction_indices)
return count_nonzero_v2(input_tensor, axis, keepdims, dtype, name) |
@tf_export('math.count_nonzero', v1=[])
def count_nonzero_v2(input, axis=None, keepdims=None, dtype=dtypes.int64, name=None):
'Computes number of nonzero elements across dimensions of a tensor.\n\n Reduces `input` along the dimensions given in `axis`.\n Unless `keepdims` is true, the rank of the tensor is reduced by 1 for each\n entry in `axis`. If `keepdims` is true, the reduced dimensions\n are retained with length 1.\n\n If `axis` has no entries, all dimensions are reduced, and a\n tensor with a single element is returned.\n\n **NOTE** Floating point comparison to zero is done by exact floating point\n equality check. Small values are **not** rounded to zero for purposes of\n the nonzero check.\n\n For example:\n\n ```python\n x = tf.constant([[0, 1, 0], [1, 1, 0]])\n tf.count_nonzero(x) # 3\n tf.count_nonzero(x, 0) # [1, 2, 0]\n tf.count_nonzero(x, 1) # [1, 2]\n tf.count_nonzero(x, 1, keepdims=True) # [[1], [2]]\n tf.count_nonzero(x, [0, 1]) # 3\n ```\n\n **NOTE** Strings are compared against zero-length empty string `""`. Any\n string with a size greater than zero is already considered as nonzero.\n\n For example:\n ```python\n x = tf.constant(["", "a", " ", "b", ""])\n tf.count_nonzero(x) # 3, with "a", " ", and "b" as nonzero strings.\n ```\n\n Args:\n input: The tensor to reduce. Should be of numeric type, `bool`,\n or `string`.\n axis: The dimensions to reduce. If `None` (the default),\n reduces all dimensions. Must be in the range\n `[-rank(input), rank(input))`.\n keepdims: If true, retains reduced dimensions with length 1.\n dtype: The output dtype; defaults to `tf.int64`.\n name: A name for the operation (optional).\n\n Returns:\n The reduced tensor (number of nonzero values).\n '
if (keepdims is None):
keepdims = False
with ops.name_scope(name, 'count_nonzero', [input]):
input = ops.convert_to_tensor(input, name='input')
zero = array_ops.zeros([], dtype=input.dtype)
return cast(reduce_sum(cast(gen_math_ops.not_equal(input, zero), dtypes.int64), axis=axis, keepdims=keepdims), dtype=dtype) | -7,720,529,422,064,440,000 | Computes number of nonzero elements across dimensions of a tensor.
Reduces `input` along the dimensions given in `axis`.
Unless `keepdims` is true, the rank of the tensor is reduced by 1 for each
entry in `axis`. If `keepdims` is true, the reduced dimensions
are retained with length 1.
If `axis` has no entries, all dimensions are reduced, and a
tensor with a single element is returned.
**NOTE** Floating point comparison to zero is done by exact floating point
equality check. Small values are **not** rounded to zero for purposes of
the nonzero check.
For example:
```python
x = tf.constant([[0, 1, 0], [1, 1, 0]])
tf.count_nonzero(x) # 3
tf.count_nonzero(x, 0) # [1, 2, 0]
tf.count_nonzero(x, 1) # [1, 2]
tf.count_nonzero(x, 1, keepdims=True) # [[1], [2]]
tf.count_nonzero(x, [0, 1]) # 3
```
**NOTE** Strings are compared against zero-length empty string `""`. Any
string with a size greater than zero is already considered as nonzero.
For example:
```python
x = tf.constant(["", "a", " ", "b", ""])
tf.count_nonzero(x) # 3, with "a", " ", and "b" as nonzero strings.
```
Args:
input: The tensor to reduce. Should be of numeric type, `bool`,
or `string`.
axis: The dimensions to reduce. If `None` (the default),
reduces all dimensions. Must be in the range
`[-rank(input), rank(input))`.
keepdims: If true, retains reduced dimensions with length 1.
dtype: The output dtype; defaults to `tf.int64`.
name: A name for the operation (optional).
Returns:
The reduced tensor (number of nonzero values). | tensorflow/python/ops/math_ops.py | count_nonzero_v2 | minminsun/tensorflow | python | @tf_export('math.count_nonzero', v1=[])
def count_nonzero_v2(input, axis=None, keepdims=None, dtype=dtypes.int64, name=None):
'Computes number of nonzero elements across dimensions of a tensor.\n\n Reduces `input` along the dimensions given in `axis`.\n Unless `keepdims` is true, the rank of the tensor is reduced by 1 for each\n entry in `axis`. If `keepdims` is true, the reduced dimensions\n are retained with length 1.\n\n If `axis` has no entries, all dimensions are reduced, and a\n tensor with a single element is returned.\n\n **NOTE** Floating point comparison to zero is done by exact floating point\n equality check. Small values are **not** rounded to zero for purposes of\n the nonzero check.\n\n For example:\n\n ```python\n x = tf.constant([[0, 1, 0], [1, 1, 0]])\n tf.count_nonzero(x) # 3\n tf.count_nonzero(x, 0) # [1, 2, 0]\n tf.count_nonzero(x, 1) # [1, 2]\n tf.count_nonzero(x, 1, keepdims=True) # [[1], [2]]\n tf.count_nonzero(x, [0, 1]) # 3\n ```\n\n **NOTE** Strings are compared against zero-length empty string ``. Any\n string with a size greater than zero is already considered as nonzero.\n\n For example:\n ```python\n x = tf.constant([, "a", " ", "b", ])\n tf.count_nonzero(x) # 3, with "a", " ", and "b" as nonzero strings.\n ```\n\n Args:\n input: The tensor to reduce. Should be of numeric type, `bool`,\n or `string`.\n axis: The dimensions to reduce. If `None` (the default),\n reduces all dimensions. Must be in the range\n `[-rank(input), rank(input))`.\n keepdims: If true, retains reduced dimensions with length 1.\n dtype: The output dtype; defaults to `tf.int64`.\n name: A name for the operation (optional).\n\n Returns:\n The reduced tensor (number of nonzero values).\n '
if (keepdims is None):
keepdims = False
with ops.name_scope(name, 'count_nonzero', [input]):
input = ops.convert_to_tensor(input, name='input')
zero = array_ops.zeros([], dtype=input.dtype)
return cast(reduce_sum(cast(gen_math_ops.not_equal(input, zero), dtypes.int64), axis=axis, keepdims=keepdims), dtype=dtype) |
@tf_export(v1=['math.reduce_mean', 'reduce_mean'])
def reduce_mean_v1(input_tensor, axis=None, keepdims=None, name=None, reduction_indices=None, keep_dims=None):
'Computes the mean of elements across dimensions of a tensor.\n\n Reduces `input_tensor` along the dimensions given in `axis`.\n Unless `keepdims` is true, the rank of the tensor is reduced by 1 for each\n entry in `axis`. If `keepdims` is true, the reduced dimensions\n are retained with length 1.\n\n If `axis` is None, all dimensions are reduced, and a\n tensor with a single element is returned.\n\n For example:\n\n ```python\n x = tf.constant([[1., 1.], [2., 2.]])\n tf.reduce_mean(x) # 1.5\n tf.reduce_mean(x, 0) # [1.5, 1.5]\n tf.reduce_mean(x, 1) # [1., 2.]\n ```\n\n Args:\n input_tensor: The tensor to reduce. Should have numeric type.\n axis: The dimensions to reduce. If `None` (the default),\n reduces all dimensions. Must be in the range\n `[-rank(input_tensor), rank(input_tensor))`.\n keepdims: If true, retains reduced dimensions with length 1.\n name: A name for the operation (optional).\n reduction_indices: The old (deprecated) name for axis.\n keep_dims: Deprecated alias for `keepdims`.\n\n Returns:\n The reduced tensor.\n\n @compatibility(numpy)\n Equivalent to np.mean\n\n Please note that `np.mean` has a `dtype` parameter that could be used to\n specify the output type. By default this is `dtype=float64`. On the other\n hand, `tf.reduce_mean` has an aggressive type inference from `input_tensor`,\n for example:\n\n ```python\n x = tf.constant([1, 0, 1, 0])\n tf.reduce_mean(x) # 0\n y = tf.constant([1., 0., 1., 0.])\n tf.reduce_mean(y) # 0.5\n ```\n\n @end_compatibility\n '
axis = deprecation.deprecated_argument_lookup('axis', axis, 'reduction_indices', reduction_indices)
keepdims = deprecation.deprecated_argument_lookup('keepdims', keepdims, 'keep_dims', keep_dims)
return reduce_mean(input_tensor, axis, keepdims, name) | -7,600,130,728,508,035,000 | Computes the mean of elements across dimensions of a tensor.
Reduces `input_tensor` along the dimensions given in `axis`.
Unless `keepdims` is true, the rank of the tensor is reduced by 1 for each
entry in `axis`. If `keepdims` is true, the reduced dimensions
are retained with length 1.
If `axis` is None, all dimensions are reduced, and a
tensor with a single element is returned.
For example:
```python
x = tf.constant([[1., 1.], [2., 2.]])
tf.reduce_mean(x) # 1.5
tf.reduce_mean(x, 0) # [1.5, 1.5]
tf.reduce_mean(x, 1) # [1., 2.]
```
Args:
input_tensor: The tensor to reduce. Should have numeric type.
axis: The dimensions to reduce. If `None` (the default),
reduces all dimensions. Must be in the range
`[-rank(input_tensor), rank(input_tensor))`.
keepdims: If true, retains reduced dimensions with length 1.
name: A name for the operation (optional).
reduction_indices: The old (deprecated) name for axis.
keep_dims: Deprecated alias for `keepdims`.
Returns:
The reduced tensor.
@compatibility(numpy)
Equivalent to np.mean
Please note that `np.mean` has a `dtype` parameter that could be used to
specify the output type. By default this is `dtype=float64`. On the other
hand, `tf.reduce_mean` has an aggressive type inference from `input_tensor`,
for example:
```python
x = tf.constant([1, 0, 1, 0])
tf.reduce_mean(x) # 0
y = tf.constant([1., 0., 1., 0.])
tf.reduce_mean(y) # 0.5
```
@end_compatibility | tensorflow/python/ops/math_ops.py | reduce_mean_v1 | minminsun/tensorflow | python | @tf_export(v1=['math.reduce_mean', 'reduce_mean'])
def reduce_mean_v1(input_tensor, axis=None, keepdims=None, name=None, reduction_indices=None, keep_dims=None):
'Computes the mean of elements across dimensions of a tensor.\n\n Reduces `input_tensor` along the dimensions given in `axis`.\n Unless `keepdims` is true, the rank of the tensor is reduced by 1 for each\n entry in `axis`. If `keepdims` is true, the reduced dimensions\n are retained with length 1.\n\n If `axis` is None, all dimensions are reduced, and a\n tensor with a single element is returned.\n\n For example:\n\n ```python\n x = tf.constant([[1., 1.], [2., 2.]])\n tf.reduce_mean(x) # 1.5\n tf.reduce_mean(x, 0) # [1.5, 1.5]\n tf.reduce_mean(x, 1) # [1., 2.]\n ```\n\n Args:\n input_tensor: The tensor to reduce. Should have numeric type.\n axis: The dimensions to reduce. If `None` (the default),\n reduces all dimensions. Must be in the range\n `[-rank(input_tensor), rank(input_tensor))`.\n keepdims: If true, retains reduced dimensions with length 1.\n name: A name for the operation (optional).\n reduction_indices: The old (deprecated) name for axis.\n keep_dims: Deprecated alias for `keepdims`.\n\n Returns:\n The reduced tensor.\n\n @compatibility(numpy)\n Equivalent to np.mean\n\n Please note that `np.mean` has a `dtype` parameter that could be used to\n specify the output type. By default this is `dtype=float64`. On the other\n hand, `tf.reduce_mean` has an aggressive type inference from `input_tensor`,\n for example:\n\n ```python\n x = tf.constant([1, 0, 1, 0])\n tf.reduce_mean(x) # 0\n y = tf.constant([1., 0., 1., 0.])\n tf.reduce_mean(y) # 0.5\n ```\n\n @end_compatibility\n '
axis = deprecation.deprecated_argument_lookup('axis', axis, 'reduction_indices', reduction_indices)
keepdims = deprecation.deprecated_argument_lookup('keepdims', keepdims, 'keep_dims', keep_dims)
return reduce_mean(input_tensor, axis, keepdims, name) |
@tf_export('math.reduce_mean', 'reduce_mean', v1=[])
@dispatch.add_dispatch_support
def reduce_mean(input_tensor, axis=None, keepdims=False, name=None):
'Computes the mean of elements across dimensions of a tensor.\n\n Reduces `input_tensor` along the dimensions given in `axis`.\n Unless `keepdims` is true, the rank of the tensor is reduced by 1 for each\n entry in `axis`. If `keepdims` is true, the reduced dimensions\n are retained with length 1.\n\n If `axis` is None, all dimensions are reduced, and a\n tensor with a single element is returned.\n\n For example:\n\n ```python\n x = tf.constant([[1., 1.], [2., 2.]])\n tf.reduce_mean(x) # 1.5\n tf.reduce_mean(x, 0) # [1.5, 1.5]\n tf.reduce_mean(x, 1) # [1., 2.]\n ```\n\n Args:\n input_tensor: The tensor to reduce. Should have numeric type.\n axis: The dimensions to reduce. If `None` (the default), reduces all\n dimensions. Must be in the range `[-rank(input_tensor),\n rank(input_tensor))`.\n keepdims: If true, retains reduced dimensions with length 1.\n name: A name for the operation (optional).\n\n Returns:\n The reduced tensor.\n\n @compatibility(numpy)\n Equivalent to np.mean\n\n Please note that `np.mean` has a `dtype` parameter that could be used to\n specify the output type. By default this is `dtype=float64`. On the other\n hand, `tf.reduce_mean` has an aggressive type inference from `input_tensor`,\n for example:\n\n ```python\n x = tf.constant([1, 0, 1, 0])\n tf.reduce_mean(x) # 0\n y = tf.constant([1., 0., 1., 0.])\n tf.reduce_mean(y) # 0.5\n ```\n\n @end_compatibility\n '
keepdims = (False if (keepdims is None) else keepdims)
return _may_reduce_to_scalar(keepdims, axis, gen_math_ops.mean(input_tensor, _ReductionDims(input_tensor, axis), keepdims, name=name)) | 2,426,798,984,264,452,600 | Computes the mean of elements across dimensions of a tensor.
Reduces `input_tensor` along the dimensions given in `axis`.
Unless `keepdims` is true, the rank of the tensor is reduced by 1 for each
entry in `axis`. If `keepdims` is true, the reduced dimensions
are retained with length 1.
If `axis` is None, all dimensions are reduced, and a
tensor with a single element is returned.
For example:
```python
x = tf.constant([[1., 1.], [2., 2.]])
tf.reduce_mean(x) # 1.5
tf.reduce_mean(x, 0) # [1.5, 1.5]
tf.reduce_mean(x, 1) # [1., 2.]
```
Args:
input_tensor: The tensor to reduce. Should have numeric type.
axis: The dimensions to reduce. If `None` (the default), reduces all
dimensions. Must be in the range `[-rank(input_tensor),
rank(input_tensor))`.
keepdims: If true, retains reduced dimensions with length 1.
name: A name for the operation (optional).
Returns:
The reduced tensor.
@compatibility(numpy)
Equivalent to np.mean
Please note that `np.mean` has a `dtype` parameter that could be used to
specify the output type. By default this is `dtype=float64`. On the other
hand, `tf.reduce_mean` has an aggressive type inference from `input_tensor`,
for example:
```python
x = tf.constant([1, 0, 1, 0])
tf.reduce_mean(x) # 0
y = tf.constant([1., 0., 1., 0.])
tf.reduce_mean(y) # 0.5
```
@end_compatibility | tensorflow/python/ops/math_ops.py | reduce_mean | minminsun/tensorflow | python | @tf_export('math.reduce_mean', 'reduce_mean', v1=[])
@dispatch.add_dispatch_support
def reduce_mean(input_tensor, axis=None, keepdims=False, name=None):
'Computes the mean of elements across dimensions of a tensor.\n\n Reduces `input_tensor` along the dimensions given in `axis`.\n Unless `keepdims` is true, the rank of the tensor is reduced by 1 for each\n entry in `axis`. If `keepdims` is true, the reduced dimensions\n are retained with length 1.\n\n If `axis` is None, all dimensions are reduced, and a\n tensor with a single element is returned.\n\n For example:\n\n ```python\n x = tf.constant([[1., 1.], [2., 2.]])\n tf.reduce_mean(x) # 1.5\n tf.reduce_mean(x, 0) # [1.5, 1.5]\n tf.reduce_mean(x, 1) # [1., 2.]\n ```\n\n Args:\n input_tensor: The tensor to reduce. Should have numeric type.\n axis: The dimensions to reduce. If `None` (the default), reduces all\n dimensions. Must be in the range `[-rank(input_tensor),\n rank(input_tensor))`.\n keepdims: If true, retains reduced dimensions with length 1.\n name: A name for the operation (optional).\n\n Returns:\n The reduced tensor.\n\n @compatibility(numpy)\n Equivalent to np.mean\n\n Please note that `np.mean` has a `dtype` parameter that could be used to\n specify the output type. By default this is `dtype=float64`. On the other\n hand, `tf.reduce_mean` has an aggressive type inference from `input_tensor`,\n for example:\n\n ```python\n x = tf.constant([1, 0, 1, 0])\n tf.reduce_mean(x) # 0\n y = tf.constant([1., 0., 1., 0.])\n tf.reduce_mean(y) # 0.5\n ```\n\n @end_compatibility\n '
keepdims = (False if (keepdims is None) else keepdims)
return _may_reduce_to_scalar(keepdims, axis, gen_math_ops.mean(input_tensor, _ReductionDims(input_tensor, axis), keepdims, name=name)) |
@tf_export('math.reduce_variance')
def reduce_variance(input_tensor, axis=None, keepdims=False, name=None):
'Computes the variance of elements across dimensions of a tensor.\n\n Reduces `input_tensor` along the dimensions given in `axis`.\n Unless `keepdims` is true, the rank of the tensor is reduced by 1 for each\n entry in `axis`. If `keepdims` is true, the reduced dimensions\n are retained with length 1.\n\n If `axis` is None, all dimensions are reduced, and a\n tensor with a single element is returned.\n\n For example:\n\n ```python\n x = tf.constant([[1., 2.], [3., 4.]])\n tf.reduce_variance(x) # 1.25\n tf.reduce_variance(x, 0) # [1., 1.]\n tf.reduce_variance(x, 1) # [0.25, 0.25]\n ```\n\n Args:\n input_tensor: The tensor to reduce. Should have numeric type.\n axis: The dimensions to reduce. If `None` (the default), reduces all\n dimensions. Must be in the range `[-rank(input_tensor),\n rank(input_tensor))`.\n keepdims: If true, retains reduced dimensions with length 1.\n name: A name scope for the associated operations (optional).\n\n Returns:\n The reduced tensor, of the same dtype as the input_tensor.\n\n @compatibility(numpy)\n Equivalent to np.var\n\n Please note that `np.var` has a `dtype` parameter that could be used to\n specify the output type. By default this is `dtype=float64`. On the other\n hand, `tf.reduce_variance` has an aggressive type inference from\n `input_tensor`,\n @end_compatibility\n '
name = (name if name else 'reduce_variance')
with ops.name_scope(name):
means = reduce_mean(input_tensor, axis=axis, keepdims=True)
squared_deviations = gen_math_ops.square((input_tensor - means))
return reduce_mean(squared_deviations, axis=axis, keepdims=keepdims) | 6,836,177,446,070,157,000 | Computes the variance of elements across dimensions of a tensor.
Reduces `input_tensor` along the dimensions given in `axis`.
Unless `keepdims` is true, the rank of the tensor is reduced by 1 for each
entry in `axis`. If `keepdims` is true, the reduced dimensions
are retained with length 1.
If `axis` is None, all dimensions are reduced, and a
tensor with a single element is returned.
For example:
```python
x = tf.constant([[1., 2.], [3., 4.]])
tf.reduce_variance(x) # 1.25
tf.reduce_variance(x, 0) # [1., 1.]
tf.reduce_variance(x, 1) # [0.25, 0.25]
```
Args:
input_tensor: The tensor to reduce. Should have numeric type.
axis: The dimensions to reduce. If `None` (the default), reduces all
dimensions. Must be in the range `[-rank(input_tensor),
rank(input_tensor))`.
keepdims: If true, retains reduced dimensions with length 1.
name: A name scope for the associated operations (optional).
Returns:
The reduced tensor, of the same dtype as the input_tensor.
@compatibility(numpy)
Equivalent to np.var
Please note that `np.var` has a `dtype` parameter that could be used to
specify the output type. By default this is `dtype=float64`. On the other
hand, `tf.reduce_variance` has an aggressive type inference from
`input_tensor`,
@end_compatibility | tensorflow/python/ops/math_ops.py | reduce_variance | minminsun/tensorflow | python | @tf_export('math.reduce_variance')
def reduce_variance(input_tensor, axis=None, keepdims=False, name=None):
'Computes the variance of elements across dimensions of a tensor.\n\n Reduces `input_tensor` along the dimensions given in `axis`.\n Unless `keepdims` is true, the rank of the tensor is reduced by 1 for each\n entry in `axis`. If `keepdims` is true, the reduced dimensions\n are retained with length 1.\n\n If `axis` is None, all dimensions are reduced, and a\n tensor with a single element is returned.\n\n For example:\n\n ```python\n x = tf.constant([[1., 2.], [3., 4.]])\n tf.reduce_variance(x) # 1.25\n tf.reduce_variance(x, 0) # [1., 1.]\n tf.reduce_variance(x, 1) # [0.25, 0.25]\n ```\n\n Args:\n input_tensor: The tensor to reduce. Should have numeric type.\n axis: The dimensions to reduce. If `None` (the default), reduces all\n dimensions. Must be in the range `[-rank(input_tensor),\n rank(input_tensor))`.\n keepdims: If true, retains reduced dimensions with length 1.\n name: A name scope for the associated operations (optional).\n\n Returns:\n The reduced tensor, of the same dtype as the input_tensor.\n\n @compatibility(numpy)\n Equivalent to np.var\n\n Please note that `np.var` has a `dtype` parameter that could be used to\n specify the output type. By default this is `dtype=float64`. On the other\n hand, `tf.reduce_variance` has an aggressive type inference from\n `input_tensor`,\n @end_compatibility\n '
name = (name if name else 'reduce_variance')
with ops.name_scope(name):
means = reduce_mean(input_tensor, axis=axis, keepdims=True)
squared_deviations = gen_math_ops.square((input_tensor - means))
return reduce_mean(squared_deviations, axis=axis, keepdims=keepdims) |
@tf_export('math.reduce_std')
def reduce_std(input_tensor, axis=None, keepdims=False, name=None):
'Computes the standard deviation of elements across dimensions of a tensor.\n\n Reduces `input_tensor` along the dimensions given in `axis`.\n Unless `keepdims` is true, the rank of the tensor is reduced by 1 for each\n entry in `axis`. If `keepdims` is true, the reduced dimensions\n are retained with length 1.\n\n If `axis` is None, all dimensions are reduced, and a\n tensor with a single element is returned.\n\n For example:\n\n ```python\n x = tf.constant([[1., 2.], [3., 4.]])\n tf.reduce_std(x) # 1.1180339887498949\n tf.reduce_std(x, 0) # [1., 1.]\n tf.reduce_std(x, 1) # [0.5, 0.5]\n ```\n\n Args:\n input_tensor: The tensor to reduce. Should have numeric type.\n axis: The dimensions to reduce. If `None` (the default), reduces all\n dimensions. Must be in the range `[-rank(input_tensor),\n rank(input_tensor))`.\n keepdims: If true, retains reduced dimensions with length 1.\n name: A name scope for the associated operations (optional).\n\n Returns:\n The reduced tensor, of the same dtype as the input_tensor.\n\n @compatibility(numpy)\n Equivalent to np.std\n\n Please note that `np.std` has a `dtype` parameter that could be used to\n specify the output type. By default this is `dtype=float64`. On the other\n hand, `tf.reduce_std` has an aggressive type inference from `input_tensor`,\n @end_compatibility\n '
name = (name if name else 'reduce_std')
with ops.name_scope(name):
variance = reduce_variance(input_tensor, axis=axis, keepdims=keepdims)
return gen_math_ops.sqrt(variance) | -6,180,980,226,246,193,000 | Computes the standard deviation of elements across dimensions of a tensor.
Reduces `input_tensor` along the dimensions given in `axis`.
Unless `keepdims` is true, the rank of the tensor is reduced by 1 for each
entry in `axis`. If `keepdims` is true, the reduced dimensions
are retained with length 1.
If `axis` is None, all dimensions are reduced, and a
tensor with a single element is returned.
For example:
```python
x = tf.constant([[1., 2.], [3., 4.]])
tf.reduce_std(x) # 1.1180339887498949
tf.reduce_std(x, 0) # [1., 1.]
tf.reduce_std(x, 1) # [0.5, 0.5]
```
Args:
input_tensor: The tensor to reduce. Should have numeric type.
axis: The dimensions to reduce. If `None` (the default), reduces all
dimensions. Must be in the range `[-rank(input_tensor),
rank(input_tensor))`.
keepdims: If true, retains reduced dimensions with length 1.
name: A name scope for the associated operations (optional).
Returns:
The reduced tensor, of the same dtype as the input_tensor.
@compatibility(numpy)
Equivalent to np.std
Please note that `np.std` has a `dtype` parameter that could be used to
specify the output type. By default this is `dtype=float64`. On the other
hand, `tf.reduce_std` has an aggressive type inference from `input_tensor`,
@end_compatibility | tensorflow/python/ops/math_ops.py | reduce_std | minminsun/tensorflow | python | @tf_export('math.reduce_std')
def reduce_std(input_tensor, axis=None, keepdims=False, name=None):
'Computes the standard deviation of elements across dimensions of a tensor.\n\n Reduces `input_tensor` along the dimensions given in `axis`.\n Unless `keepdims` is true, the rank of the tensor is reduced by 1 for each\n entry in `axis`. If `keepdims` is true, the reduced dimensions\n are retained with length 1.\n\n If `axis` is None, all dimensions are reduced, and a\n tensor with a single element is returned.\n\n For example:\n\n ```python\n x = tf.constant([[1., 2.], [3., 4.]])\n tf.reduce_std(x) # 1.1180339887498949\n tf.reduce_std(x, 0) # [1., 1.]\n tf.reduce_std(x, 1) # [0.5, 0.5]\n ```\n\n Args:\n input_tensor: The tensor to reduce. Should have numeric type.\n axis: The dimensions to reduce. If `None` (the default), reduces all\n dimensions. Must be in the range `[-rank(input_tensor),\n rank(input_tensor))`.\n keepdims: If true, retains reduced dimensions with length 1.\n name: A name scope for the associated operations (optional).\n\n Returns:\n The reduced tensor, of the same dtype as the input_tensor.\n\n @compatibility(numpy)\n Equivalent to np.std\n\n Please note that `np.std` has a `dtype` parameter that could be used to\n specify the output type. By default this is `dtype=float64`. On the other\n hand, `tf.reduce_std` has an aggressive type inference from `input_tensor`,\n @end_compatibility\n '
name = (name if name else 'reduce_std')
with ops.name_scope(name):
variance = reduce_variance(input_tensor, axis=axis, keepdims=keepdims)
return gen_math_ops.sqrt(variance) |
@tf_export('math.reduce_prod', 'reduce_prod', v1=[])
@dispatch.add_dispatch_support
def reduce_prod(input_tensor, axis=None, keepdims=False, name=None):
'Computes the product of elements across dimensions of a tensor.\n\n Reduces `input_tensor` along the dimensions given in `axis`.\n Unless `keepdims` is true, the rank of the tensor is reduced by 1 for each\n entry in `axis`. If `keepdims` is true, the reduced dimensions\n are retained with length 1.\n\n If `axis` is None, all dimensions are reduced, and a\n tensor with a single element is returned.\n\n Args:\n input_tensor: The tensor to reduce. Should have numeric type.\n axis: The dimensions to reduce. If `None` (the default),\n reduces all dimensions. Must be in the range\n `[-rank(input_tensor), rank(input_tensor))`.\n keepdims: If true, retains reduced dimensions with length 1.\n name: A name for the operation (optional).\n\n Returns:\n The reduced tensor.\n\n @compatibility(numpy)\n Equivalent to np.prod\n @end_compatibility\n '
keepdims = (False if (keepdims is None) else keepdims)
return _may_reduce_to_scalar(keepdims, axis, gen_math_ops.prod(input_tensor, _ReductionDims(input_tensor, axis), keepdims, name=name)) | -7,169,107,470,110,706,000 | Computes the product of elements across dimensions of a tensor.
Reduces `input_tensor` along the dimensions given in `axis`.
Unless `keepdims` is true, the rank of the tensor is reduced by 1 for each
entry in `axis`. If `keepdims` is true, the reduced dimensions
are retained with length 1.
If `axis` is None, all dimensions are reduced, and a
tensor with a single element is returned.
Args:
input_tensor: The tensor to reduce. Should have numeric type.
axis: The dimensions to reduce. If `None` (the default),
reduces all dimensions. Must be in the range
`[-rank(input_tensor), rank(input_tensor))`.
keepdims: If true, retains reduced dimensions with length 1.
name: A name for the operation (optional).
Returns:
The reduced tensor.
@compatibility(numpy)
Equivalent to np.prod
@end_compatibility | tensorflow/python/ops/math_ops.py | reduce_prod | minminsun/tensorflow | python | @tf_export('math.reduce_prod', 'reduce_prod', v1=[])
@dispatch.add_dispatch_support
def reduce_prod(input_tensor, axis=None, keepdims=False, name=None):
'Computes the product of elements across dimensions of a tensor.\n\n Reduces `input_tensor` along the dimensions given in `axis`.\n Unless `keepdims` is true, the rank of the tensor is reduced by 1 for each\n entry in `axis`. If `keepdims` is true, the reduced dimensions\n are retained with length 1.\n\n If `axis` is None, all dimensions are reduced, and a\n tensor with a single element is returned.\n\n Args:\n input_tensor: The tensor to reduce. Should have numeric type.\n axis: The dimensions to reduce. If `None` (the default),\n reduces all dimensions. Must be in the range\n `[-rank(input_tensor), rank(input_tensor))`.\n keepdims: If true, retains reduced dimensions with length 1.\n name: A name for the operation (optional).\n\n Returns:\n The reduced tensor.\n\n @compatibility(numpy)\n Equivalent to np.prod\n @end_compatibility\n '
keepdims = (False if (keepdims is None) else keepdims)
return _may_reduce_to_scalar(keepdims, axis, gen_math_ops.prod(input_tensor, _ReductionDims(input_tensor, axis), keepdims, name=name)) |
@tf_export(v1=['math.reduce_prod', 'reduce_prod'])
@deprecation.deprecated_args(None, 'keep_dims is deprecated, use keepdims instead', 'keep_dims')
def reduce_prod_v1(input_tensor, axis=None, keepdims=None, name=None, reduction_indices=None, keep_dims=None):
'Computes the product of elements across dimensions of a tensor.\n\n Reduces `input_tensor` along the dimensions given in `axis`.\n Unless `keepdims` is true, the rank of the tensor is reduced by 1 for each\n entry in `axis`. If `keepdims` is true, the reduced dimensions\n are retained with length 1.\n\n If `axis` is None, all dimensions are reduced, and a\n tensor with a single element is returned.\n\n Args:\n input_tensor: The tensor to reduce. Should have numeric type.\n axis: The dimensions to reduce. If `None` (the default), reduces all\n dimensions. Must be in the range `[-rank(input_tensor),\n rank(input_tensor))`.\n keepdims: If true, retains reduced dimensions with length 1.\n name: A name for the operation (optional).\n reduction_indices: The old (deprecated) name for axis.\n keep_dims: Deprecated alias for `keepdims`.\n\n Returns:\n The reduced tensor.\n\n @compatibility(numpy)\n Equivalent to np.prod\n @end_compatibility\n '
axis = deprecation.deprecated_argument_lookup('axis', axis, 'reduction_indices', reduction_indices)
keepdims = deprecation.deprecated_argument_lookup('keepdims', keepdims, 'keep_dims', keep_dims)
return reduce_prod(input_tensor, axis, keepdims, name) | -1,712,806,314,986,321,400 | Computes the product of elements across dimensions of a tensor.
Reduces `input_tensor` along the dimensions given in `axis`.
Unless `keepdims` is true, the rank of the tensor is reduced by 1 for each
entry in `axis`. If `keepdims` is true, the reduced dimensions
are retained with length 1.
If `axis` is None, all dimensions are reduced, and a
tensor with a single element is returned.
Args:
input_tensor: The tensor to reduce. Should have numeric type.
axis: The dimensions to reduce. If `None` (the default), reduces all
dimensions. Must be in the range `[-rank(input_tensor),
rank(input_tensor))`.
keepdims: If true, retains reduced dimensions with length 1.
name: A name for the operation (optional).
reduction_indices: The old (deprecated) name for axis.
keep_dims: Deprecated alias for `keepdims`.
Returns:
The reduced tensor.
@compatibility(numpy)
Equivalent to np.prod
@end_compatibility | tensorflow/python/ops/math_ops.py | reduce_prod_v1 | minminsun/tensorflow | python | @tf_export(v1=['math.reduce_prod', 'reduce_prod'])
@deprecation.deprecated_args(None, 'keep_dims is deprecated, use keepdims instead', 'keep_dims')
def reduce_prod_v1(input_tensor, axis=None, keepdims=None, name=None, reduction_indices=None, keep_dims=None):
'Computes the product of elements across dimensions of a tensor.\n\n Reduces `input_tensor` along the dimensions given in `axis`.\n Unless `keepdims` is true, the rank of the tensor is reduced by 1 for each\n entry in `axis`. If `keepdims` is true, the reduced dimensions\n are retained with length 1.\n\n If `axis` is None, all dimensions are reduced, and a\n tensor with a single element is returned.\n\n Args:\n input_tensor: The tensor to reduce. Should have numeric type.\n axis: The dimensions to reduce. If `None` (the default), reduces all\n dimensions. Must be in the range `[-rank(input_tensor),\n rank(input_tensor))`.\n keepdims: If true, retains reduced dimensions with length 1.\n name: A name for the operation (optional).\n reduction_indices: The old (deprecated) name for axis.\n keep_dims: Deprecated alias for `keepdims`.\n\n Returns:\n The reduced tensor.\n\n @compatibility(numpy)\n Equivalent to np.prod\n @end_compatibility\n '
axis = deprecation.deprecated_argument_lookup('axis', axis, 'reduction_indices', reduction_indices)
keepdims = deprecation.deprecated_argument_lookup('keepdims', keepdims, 'keep_dims', keep_dims)
return reduce_prod(input_tensor, axis, keepdims, name) |
@tf_export(v1=['math.reduce_min', 'reduce_min'])
@deprecation.deprecated_args(None, 'keep_dims is deprecated, use keepdims instead', 'keep_dims')
def reduce_min_v1(input_tensor, axis=None, keepdims=None, name=None, reduction_indices=None, keep_dims=None):
'Computes the minimum of elements across dimensions of a tensor.\n\n Reduces `input_tensor` along the dimensions given in `axis`.\n Unless `keepdims` is true, the rank of the tensor is reduced by 1 for each\n entry in `axis`. If `keepdims` is true, the reduced dimensions\n are retained with length 1.\n\n If `axis` is None, all dimensions are reduced, and a\n tensor with a single element is returned.\n\n Args:\n input_tensor: The tensor to reduce. Should have real numeric type.\n axis: The dimensions to reduce. If `None` (the default), reduces all\n dimensions. Must be in the range `[-rank(input_tensor),\n rank(input_tensor))`.\n keepdims: If true, retains reduced dimensions with length 1.\n name: A name for the operation (optional).\n reduction_indices: The old (deprecated) name for axis.\n keep_dims: Deprecated alias for `keepdims`.\n\n Returns:\n The reduced tensor.\n\n @compatibility(numpy)\n Equivalent to np.min\n @end_compatibility\n '
axis = deprecation.deprecated_argument_lookup('axis', axis, 'reduction_indices', reduction_indices)
keepdims = deprecation.deprecated_argument_lookup('keepdims', keepdims, 'keep_dims', keep_dims)
return reduce_min(input_tensor, axis, keepdims, name) | -684,596,964,939,524,000 | Computes the minimum of elements across dimensions of a tensor.
Reduces `input_tensor` along the dimensions given in `axis`.
Unless `keepdims` is true, the rank of the tensor is reduced by 1 for each
entry in `axis`. If `keepdims` is true, the reduced dimensions
are retained with length 1.
If `axis` is None, all dimensions are reduced, and a
tensor with a single element is returned.
Args:
input_tensor: The tensor to reduce. Should have real numeric type.
axis: The dimensions to reduce. If `None` (the default), reduces all
dimensions. Must be in the range `[-rank(input_tensor),
rank(input_tensor))`.
keepdims: If true, retains reduced dimensions with length 1.
name: A name for the operation (optional).
reduction_indices: The old (deprecated) name for axis.
keep_dims: Deprecated alias for `keepdims`.
Returns:
The reduced tensor.
@compatibility(numpy)
Equivalent to np.min
@end_compatibility | tensorflow/python/ops/math_ops.py | reduce_min_v1 | minminsun/tensorflow | python | @tf_export(v1=['math.reduce_min', 'reduce_min'])
@deprecation.deprecated_args(None, 'keep_dims is deprecated, use keepdims instead', 'keep_dims')
def reduce_min_v1(input_tensor, axis=None, keepdims=None, name=None, reduction_indices=None, keep_dims=None):
'Computes the minimum of elements across dimensions of a tensor.\n\n Reduces `input_tensor` along the dimensions given in `axis`.\n Unless `keepdims` is true, the rank of the tensor is reduced by 1 for each\n entry in `axis`. If `keepdims` is true, the reduced dimensions\n are retained with length 1.\n\n If `axis` is None, all dimensions are reduced, and a\n tensor with a single element is returned.\n\n Args:\n input_tensor: The tensor to reduce. Should have real numeric type.\n axis: The dimensions to reduce. If `None` (the default), reduces all\n dimensions. Must be in the range `[-rank(input_tensor),\n rank(input_tensor))`.\n keepdims: If true, retains reduced dimensions with length 1.\n name: A name for the operation (optional).\n reduction_indices: The old (deprecated) name for axis.\n keep_dims: Deprecated alias for `keepdims`.\n\n Returns:\n The reduced tensor.\n\n @compatibility(numpy)\n Equivalent to np.min\n @end_compatibility\n '
axis = deprecation.deprecated_argument_lookup('axis', axis, 'reduction_indices', reduction_indices)
keepdims = deprecation.deprecated_argument_lookup('keepdims', keepdims, 'keep_dims', keep_dims)
return reduce_min(input_tensor, axis, keepdims, name) |
@tf_export('math.reduce_min', 'reduce_min', v1=[])
@dispatch.add_dispatch_support
def reduce_min(input_tensor, axis=None, keepdims=False, name=None):
'Computes the minimum of elements across dimensions of a tensor.\n\n Reduces `input_tensor` along the dimensions given in `axis`.\n Unless `keepdims` is true, the rank of the tensor is reduced by 1 for each\n entry in `axis`. If `keepdims` is true, the reduced dimensions\n are retained with length 1.\n\n If `axis` is None, all dimensions are reduced, and a\n tensor with a single element is returned.\n\n Args:\n input_tensor: The tensor to reduce. Should have real numeric type.\n axis: The dimensions to reduce. If `None` (the default), reduces all\n dimensions. Must be in the range `[-rank(input_tensor),\n rank(input_tensor))`.\n keepdims: If true, retains reduced dimensions with length 1.\n name: A name for the operation (optional).\n\n Returns:\n The reduced tensor.\n\n @compatibility(numpy)\n Equivalent to np.min\n @end_compatibility\n '
keepdims = (False if (keepdims is None) else keepdims)
return _may_reduce_to_scalar(keepdims, axis, gen_math_ops._min(input_tensor, _ReductionDims(input_tensor, axis), keepdims, name=name)) | 5,341,900,889,916,194,000 | Computes the minimum of elements across dimensions of a tensor.
Reduces `input_tensor` along the dimensions given in `axis`.
Unless `keepdims` is true, the rank of the tensor is reduced by 1 for each
entry in `axis`. If `keepdims` is true, the reduced dimensions
are retained with length 1.
If `axis` is None, all dimensions are reduced, and a
tensor with a single element is returned.
Args:
input_tensor: The tensor to reduce. Should have real numeric type.
axis: The dimensions to reduce. If `None` (the default), reduces all
dimensions. Must be in the range `[-rank(input_tensor),
rank(input_tensor))`.
keepdims: If true, retains reduced dimensions with length 1.
name: A name for the operation (optional).
Returns:
The reduced tensor.
@compatibility(numpy)
Equivalent to np.min
@end_compatibility | tensorflow/python/ops/math_ops.py | reduce_min | minminsun/tensorflow | python | @tf_export('math.reduce_min', 'reduce_min', v1=[])
@dispatch.add_dispatch_support
def reduce_min(input_tensor, axis=None, keepdims=False, name=None):
'Computes the minimum of elements across dimensions of a tensor.\n\n Reduces `input_tensor` along the dimensions given in `axis`.\n Unless `keepdims` is true, the rank of the tensor is reduced by 1 for each\n entry in `axis`. If `keepdims` is true, the reduced dimensions\n are retained with length 1.\n\n If `axis` is None, all dimensions are reduced, and a\n tensor with a single element is returned.\n\n Args:\n input_tensor: The tensor to reduce. Should have real numeric type.\n axis: The dimensions to reduce. If `None` (the default), reduces all\n dimensions. Must be in the range `[-rank(input_tensor),\n rank(input_tensor))`.\n keepdims: If true, retains reduced dimensions with length 1.\n name: A name for the operation (optional).\n\n Returns:\n The reduced tensor.\n\n @compatibility(numpy)\n Equivalent to np.min\n @end_compatibility\n '
keepdims = (False if (keepdims is None) else keepdims)
return _may_reduce_to_scalar(keepdims, axis, gen_math_ops._min(input_tensor, _ReductionDims(input_tensor, axis), keepdims, name=name)) |
@tf_export(v1=['math.reduce_max', 'reduce_max'])
@deprecation.deprecated_args(None, 'keep_dims is deprecated, use keepdims instead', 'keep_dims')
def reduce_max_v1(input_tensor, axis=None, keepdims=None, name=None, reduction_indices=None, keep_dims=None):
'Computes the maximum of elements across dimensions of a tensor.\n\n Reduces `input_tensor` along the dimensions given in `axis`.\n Unless `keepdims` is true, the rank of the tensor is reduced by 1 for each\n entry in `axis`. If `keepdims` is true, the reduced dimensions\n are retained with length 1.\n\n If `axis` is None, all dimensions are reduced, and a\n tensor with a single element is returned.\n\n Args:\n input_tensor: The tensor to reduce. Should have real numeric type.\n axis: The dimensions to reduce. If `None` (the default),\n reduces all dimensions. Must be in the range\n `[-rank(input_tensor), rank(input_tensor))`.\n keepdims: If true, retains reduced dimensions with length 1.\n name: A name for the operation (optional).\n reduction_indices: The old (deprecated) name for axis.\n keep_dims: Deprecated alias for `keepdims`.\n\n Returns:\n The reduced tensor.\n\n @compatibility(numpy)\n Equivalent to np.max\n @end_compatibility\n '
axis = deprecation.deprecated_argument_lookup('axis', axis, 'reduction_indices', reduction_indices)
keepdims = deprecation.deprecated_argument_lookup('keepdims', keepdims, 'keep_dims', keep_dims)
return reduce_max(input_tensor, axis, keepdims, name) | -4,380,389,479,488,748,000 | Computes the maximum of elements across dimensions of a tensor.
Reduces `input_tensor` along the dimensions given in `axis`.
Unless `keepdims` is true, the rank of the tensor is reduced by 1 for each
entry in `axis`. If `keepdims` is true, the reduced dimensions
are retained with length 1.
If `axis` is None, all dimensions are reduced, and a
tensor with a single element is returned.
Args:
input_tensor: The tensor to reduce. Should have real numeric type.
axis: The dimensions to reduce. If `None` (the default),
reduces all dimensions. Must be in the range
`[-rank(input_tensor), rank(input_tensor))`.
keepdims: If true, retains reduced dimensions with length 1.
name: A name for the operation (optional).
reduction_indices: The old (deprecated) name for axis.
keep_dims: Deprecated alias for `keepdims`.
Returns:
The reduced tensor.
@compatibility(numpy)
Equivalent to np.max
@end_compatibility | tensorflow/python/ops/math_ops.py | reduce_max_v1 | minminsun/tensorflow | python | @tf_export(v1=['math.reduce_max', 'reduce_max'])
@deprecation.deprecated_args(None, 'keep_dims is deprecated, use keepdims instead', 'keep_dims')
def reduce_max_v1(input_tensor, axis=None, keepdims=None, name=None, reduction_indices=None, keep_dims=None):
'Computes the maximum of elements across dimensions of a tensor.\n\n Reduces `input_tensor` along the dimensions given in `axis`.\n Unless `keepdims` is true, the rank of the tensor is reduced by 1 for each\n entry in `axis`. If `keepdims` is true, the reduced dimensions\n are retained with length 1.\n\n If `axis` is None, all dimensions are reduced, and a\n tensor with a single element is returned.\n\n Args:\n input_tensor: The tensor to reduce. Should have real numeric type.\n axis: The dimensions to reduce. If `None` (the default),\n reduces all dimensions. Must be in the range\n `[-rank(input_tensor), rank(input_tensor))`.\n keepdims: If true, retains reduced dimensions with length 1.\n name: A name for the operation (optional).\n reduction_indices: The old (deprecated) name for axis.\n keep_dims: Deprecated alias for `keepdims`.\n\n Returns:\n The reduced tensor.\n\n @compatibility(numpy)\n Equivalent to np.max\n @end_compatibility\n '
axis = deprecation.deprecated_argument_lookup('axis', axis, 'reduction_indices', reduction_indices)
keepdims = deprecation.deprecated_argument_lookup('keepdims', keepdims, 'keep_dims', keep_dims)
return reduce_max(input_tensor, axis, keepdims, name) |
@tf_export('math.reduce_max', 'reduce_max', v1=[])
@dispatch.add_dispatch_support
def reduce_max(input_tensor, axis=None, keepdims=False, name=None):
'Computes the maximum of elements across dimensions of a tensor.\n\n Reduces `input_tensor` along the dimensions given in `axis`.\n Unless `keepdims` is true, the rank of the tensor is reduced by 1 for each\n entry in `axis`. If `keepdims` is true, the reduced dimensions\n are retained with length 1.\n\n If `axis` is None, all dimensions are reduced, and a\n tensor with a single element is returned.\n\n Args:\n input_tensor: The tensor to reduce. Should have real numeric type.\n axis: The dimensions to reduce. If `None` (the default), reduces all\n dimensions. Must be in the range `[-rank(input_tensor),\n rank(input_tensor))`.\n keepdims: If true, retains reduced dimensions with length 1.\n name: A name for the operation (optional).\n\n Returns:\n The reduced tensor.\n\n @compatibility(numpy)\n Equivalent to np.max\n @end_compatibility\n '
keepdims = (False if (keepdims is None) else keepdims)
return _may_reduce_to_scalar(keepdims, axis, gen_math_ops._max(input_tensor, _ReductionDims(input_tensor, axis), keepdims, name=name)) | -1,403,142,209,296,636,400 | Computes the maximum of elements across dimensions of a tensor.
Reduces `input_tensor` along the dimensions given in `axis`.
Unless `keepdims` is true, the rank of the tensor is reduced by 1 for each
entry in `axis`. If `keepdims` is true, the reduced dimensions
are retained with length 1.
If `axis` is None, all dimensions are reduced, and a
tensor with a single element is returned.
Args:
input_tensor: The tensor to reduce. Should have real numeric type.
axis: The dimensions to reduce. If `None` (the default), reduces all
dimensions. Must be in the range `[-rank(input_tensor),
rank(input_tensor))`.
keepdims: If true, retains reduced dimensions with length 1.
name: A name for the operation (optional).
Returns:
The reduced tensor.
@compatibility(numpy)
Equivalent to np.max
@end_compatibility | tensorflow/python/ops/math_ops.py | reduce_max | minminsun/tensorflow | python | @tf_export('math.reduce_max', 'reduce_max', v1=[])
@dispatch.add_dispatch_support
def reduce_max(input_tensor, axis=None, keepdims=False, name=None):
'Computes the maximum of elements across dimensions of a tensor.\n\n Reduces `input_tensor` along the dimensions given in `axis`.\n Unless `keepdims` is true, the rank of the tensor is reduced by 1 for each\n entry in `axis`. If `keepdims` is true, the reduced dimensions\n are retained with length 1.\n\n If `axis` is None, all dimensions are reduced, and a\n tensor with a single element is returned.\n\n Args:\n input_tensor: The tensor to reduce. Should have real numeric type.\n axis: The dimensions to reduce. If `None` (the default), reduces all\n dimensions. Must be in the range `[-rank(input_tensor),\n rank(input_tensor))`.\n keepdims: If true, retains reduced dimensions with length 1.\n name: A name for the operation (optional).\n\n Returns:\n The reduced tensor.\n\n @compatibility(numpy)\n Equivalent to np.max\n @end_compatibility\n '
keepdims = (False if (keepdims is None) else keepdims)
return _may_reduce_to_scalar(keepdims, axis, gen_math_ops._max(input_tensor, _ReductionDims(input_tensor, axis), keepdims, name=name)) |
@tf_export(v1=['math.reduce_all', 'reduce_all'])
@deprecation.deprecated_args(None, 'keep_dims is deprecated, use keepdims instead', 'keep_dims')
def reduce_all_v1(input_tensor, axis=None, keepdims=None, name=None, reduction_indices=None, keep_dims=None):
'Computes the "logical and" of elements across dimensions of a tensor.\n\n Reduces `input_tensor` along the dimensions given in `axis`.\n Unless `keepdims` is true, the rank of the tensor is reduced by 1 for each\n entry in `axis`. If `keepdims` is true, the reduced dimensions\n are retained with length 1.\n\n If `axis` is None, all dimensions are reduced, and a\n tensor with a single element is returned.\n\n For example:\n\n ```python\n x = tf.constant([[True, True], [False, False]])\n tf.reduce_all(x) # False\n tf.reduce_all(x, 0) # [False, False]\n tf.reduce_all(x, 1) # [True, False]\n ```\n\n Args:\n input_tensor: The boolean tensor to reduce.\n axis: The dimensions to reduce. If `None` (the default), reduces all\n dimensions. Must be in the range `[-rank(input_tensor),\n rank(input_tensor))`.\n keepdims: If true, retains reduced dimensions with length 1.\n name: A name for the operation (optional).\n reduction_indices: The old (deprecated) name for axis.\n keep_dims: Deprecated alias for `keepdims`.\n\n Returns:\n The reduced tensor.\n\n @compatibility(numpy)\n Equivalent to np.all\n @end_compatibility\n '
axis = deprecation.deprecated_argument_lookup('axis', axis, 'reduction_indices', reduction_indices)
keepdims = deprecation.deprecated_argument_lookup('keepdims', keepdims, 'keep_dims', keep_dims)
return reduce_all(input_tensor, axis, keepdims, name) | -326,992,824,029,111,400 | Computes the "logical and" of elements across dimensions of a tensor.
Reduces `input_tensor` along the dimensions given in `axis`.
Unless `keepdims` is true, the rank of the tensor is reduced by 1 for each
entry in `axis`. If `keepdims` is true, the reduced dimensions
are retained with length 1.
If `axis` is None, all dimensions are reduced, and a
tensor with a single element is returned.
For example:
```python
x = tf.constant([[True, True], [False, False]])
tf.reduce_all(x) # False
tf.reduce_all(x, 0) # [False, False]
tf.reduce_all(x, 1) # [True, False]
```
Args:
input_tensor: The boolean tensor to reduce.
axis: The dimensions to reduce. If `None` (the default), reduces all
dimensions. Must be in the range `[-rank(input_tensor),
rank(input_tensor))`.
keepdims: If true, retains reduced dimensions with length 1.
name: A name for the operation (optional).
reduction_indices: The old (deprecated) name for axis.
keep_dims: Deprecated alias for `keepdims`.
Returns:
The reduced tensor.
@compatibility(numpy)
Equivalent to np.all
@end_compatibility | tensorflow/python/ops/math_ops.py | reduce_all_v1 | minminsun/tensorflow | python | @tf_export(v1=['math.reduce_all', 'reduce_all'])
@deprecation.deprecated_args(None, 'keep_dims is deprecated, use keepdims instead', 'keep_dims')
def reduce_all_v1(input_tensor, axis=None, keepdims=None, name=None, reduction_indices=None, keep_dims=None):
'Computes the "logical and" of elements across dimensions of a tensor.\n\n Reduces `input_tensor` along the dimensions given in `axis`.\n Unless `keepdims` is true, the rank of the tensor is reduced by 1 for each\n entry in `axis`. If `keepdims` is true, the reduced dimensions\n are retained with length 1.\n\n If `axis` is None, all dimensions are reduced, and a\n tensor with a single element is returned.\n\n For example:\n\n ```python\n x = tf.constant([[True, True], [False, False]])\n tf.reduce_all(x) # False\n tf.reduce_all(x, 0) # [False, False]\n tf.reduce_all(x, 1) # [True, False]\n ```\n\n Args:\n input_tensor: The boolean tensor to reduce.\n axis: The dimensions to reduce. If `None` (the default), reduces all\n dimensions. Must be in the range `[-rank(input_tensor),\n rank(input_tensor))`.\n keepdims: If true, retains reduced dimensions with length 1.\n name: A name for the operation (optional).\n reduction_indices: The old (deprecated) name for axis.\n keep_dims: Deprecated alias for `keepdims`.\n\n Returns:\n The reduced tensor.\n\n @compatibility(numpy)\n Equivalent to np.all\n @end_compatibility\n '
axis = deprecation.deprecated_argument_lookup('axis', axis, 'reduction_indices', reduction_indices)
keepdims = deprecation.deprecated_argument_lookup('keepdims', keepdims, 'keep_dims', keep_dims)
return reduce_all(input_tensor, axis, keepdims, name) |
@tf_export('reduce_all', 'math.reduce_all', v1=[])
@dispatch.add_dispatch_support
def reduce_all(input_tensor, axis=None, keepdims=False, name=None):
'Computes the "logical and" of elements across dimensions of a tensor.\n\n Reduces `input_tensor` along the dimensions given in `axis`.\n Unless `keepdims` is true, the rank of the tensor is reduced by 1 for each\n entry in `axis`. If `keepdims` is true, the reduced dimensions\n are retained with length 1.\n\n If `axis` is None, all dimensions are reduced, and a\n tensor with a single element is returned.\n\n For example:\n\n ```python\n x = tf.constant([[True, True], [False, False]])\n tf.reduce_all(x) # False\n tf.reduce_all(x, 0) # [False, False]\n tf.reduce_all(x, 1) # [True, False]\n ```\n\n Args:\n input_tensor: The boolean tensor to reduce.\n axis: The dimensions to reduce. If `None` (the default), reduces all\n dimensions. Must be in the range `[-rank(input_tensor),\n rank(input_tensor))`.\n keepdims: If true, retains reduced dimensions with length 1.\n name: A name for the operation (optional).\n\n Returns:\n The reduced tensor.\n\n @compatibility(numpy)\n Equivalent to np.all\n @end_compatibility\n '
keepdims = (False if (keepdims is None) else keepdims)
return _may_reduce_to_scalar(keepdims, axis, gen_math_ops._all(input_tensor, _ReductionDims(input_tensor, axis), keepdims, name=name)) | -1,228,370,869,425,369,600 | Computes the "logical and" of elements across dimensions of a tensor.
Reduces `input_tensor` along the dimensions given in `axis`.
Unless `keepdims` is true, the rank of the tensor is reduced by 1 for each
entry in `axis`. If `keepdims` is true, the reduced dimensions
are retained with length 1.
If `axis` is None, all dimensions are reduced, and a
tensor with a single element is returned.
For example:
```python
x = tf.constant([[True, True], [False, False]])
tf.reduce_all(x) # False
tf.reduce_all(x, 0) # [False, False]
tf.reduce_all(x, 1) # [True, False]
```
Args:
input_tensor: The boolean tensor to reduce.
axis: The dimensions to reduce. If `None` (the default), reduces all
dimensions. Must be in the range `[-rank(input_tensor),
rank(input_tensor))`.
keepdims: If true, retains reduced dimensions with length 1.
name: A name for the operation (optional).
Returns:
The reduced tensor.
@compatibility(numpy)
Equivalent to np.all
@end_compatibility | tensorflow/python/ops/math_ops.py | reduce_all | minminsun/tensorflow | python | @tf_export('reduce_all', 'math.reduce_all', v1=[])
@dispatch.add_dispatch_support
def reduce_all(input_tensor, axis=None, keepdims=False, name=None):
'Computes the "logical and" of elements across dimensions of a tensor.\n\n Reduces `input_tensor` along the dimensions given in `axis`.\n Unless `keepdims` is true, the rank of the tensor is reduced by 1 for each\n entry in `axis`. If `keepdims` is true, the reduced dimensions\n are retained with length 1.\n\n If `axis` is None, all dimensions are reduced, and a\n tensor with a single element is returned.\n\n For example:\n\n ```python\n x = tf.constant([[True, True], [False, False]])\n tf.reduce_all(x) # False\n tf.reduce_all(x, 0) # [False, False]\n tf.reduce_all(x, 1) # [True, False]\n ```\n\n Args:\n input_tensor: The boolean tensor to reduce.\n axis: The dimensions to reduce. If `None` (the default), reduces all\n dimensions. Must be in the range `[-rank(input_tensor),\n rank(input_tensor))`.\n keepdims: If true, retains reduced dimensions with length 1.\n name: A name for the operation (optional).\n\n Returns:\n The reduced tensor.\n\n @compatibility(numpy)\n Equivalent to np.all\n @end_compatibility\n '
keepdims = (False if (keepdims is None) else keepdims)
return _may_reduce_to_scalar(keepdims, axis, gen_math_ops._all(input_tensor, _ReductionDims(input_tensor, axis), keepdims, name=name)) |
@tf_export(v1=['math.reduce_any', 'reduce_any'])
@deprecation.deprecated_args(None, 'keep_dims is deprecated, use keepdims instead', 'keep_dims')
def reduce_any_v1(input_tensor, axis=None, keepdims=None, name=None, reduction_indices=None, keep_dims=None):
'Computes the "logical or" of elements across dimensions of a tensor.\n\n Reduces `input_tensor` along the dimensions given in `axis`.\n Unless `keepdims` is true, the rank of the tensor is reduced by 1 for each\n entry in `axis`. If `keepdims` is true, the reduced dimensions\n are retained with length 1.\n\n If `axis` is None, all dimensions are reduced, and a\n tensor with a single element is returned.\n\n For example:\n\n ```python\n x = tf.constant([[True, True], [False, False]])\n tf.reduce_any(x) # True\n tf.reduce_any(x, 0) # [True, True]\n tf.reduce_any(x, 1) # [True, False]\n ```\n\n Args:\n input_tensor: The boolean tensor to reduce.\n axis: The dimensions to reduce. If `None` (the default), reduces all\n dimensions. Must be in the range `[-rank(input_tensor),\n rank(input_tensor))`.\n keepdims: If true, retains reduced dimensions with length 1.\n name: A name for the operation (optional).\n reduction_indices: The old (deprecated) name for axis.\n keep_dims: Deprecated alias for `keepdims`.\n\n Returns:\n The reduced tensor.\n\n @compatibility(numpy)\n Equivalent to np.any\n @end_compatibility\n '
axis = deprecation.deprecated_argument_lookup('axis', axis, 'reduction_indices', reduction_indices)
keepdims = deprecation.deprecated_argument_lookup('keepdims', keepdims, 'keep_dims', keep_dims)
return reduce_any(input_tensor, axis, keepdims, name) | 4,959,863,152,156,496,000 | Computes the "logical or" of elements across dimensions of a tensor.
Reduces `input_tensor` along the dimensions given in `axis`.
Unless `keepdims` is true, the rank of the tensor is reduced by 1 for each
entry in `axis`. If `keepdims` is true, the reduced dimensions
are retained with length 1.
If `axis` is None, all dimensions are reduced, and a
tensor with a single element is returned.
For example:
```python
x = tf.constant([[True, True], [False, False]])
tf.reduce_any(x) # True
tf.reduce_any(x, 0) # [True, True]
tf.reduce_any(x, 1) # [True, False]
```
Args:
input_tensor: The boolean tensor to reduce.
axis: The dimensions to reduce. If `None` (the default), reduces all
dimensions. Must be in the range `[-rank(input_tensor),
rank(input_tensor))`.
keepdims: If true, retains reduced dimensions with length 1.
name: A name for the operation (optional).
reduction_indices: The old (deprecated) name for axis.
keep_dims: Deprecated alias for `keepdims`.
Returns:
The reduced tensor.
@compatibility(numpy)
Equivalent to np.any
@end_compatibility | tensorflow/python/ops/math_ops.py | reduce_any_v1 | minminsun/tensorflow | python | @tf_export(v1=['math.reduce_any', 'reduce_any'])
@deprecation.deprecated_args(None, 'keep_dims is deprecated, use keepdims instead', 'keep_dims')
def reduce_any_v1(input_tensor, axis=None, keepdims=None, name=None, reduction_indices=None, keep_dims=None):
'Computes the "logical or" of elements across dimensions of a tensor.\n\n Reduces `input_tensor` along the dimensions given in `axis`.\n Unless `keepdims` is true, the rank of the tensor is reduced by 1 for each\n entry in `axis`. If `keepdims` is true, the reduced dimensions\n are retained with length 1.\n\n If `axis` is None, all dimensions are reduced, and a\n tensor with a single element is returned.\n\n For example:\n\n ```python\n x = tf.constant([[True, True], [False, False]])\n tf.reduce_any(x) # True\n tf.reduce_any(x, 0) # [True, True]\n tf.reduce_any(x, 1) # [True, False]\n ```\n\n Args:\n input_tensor: The boolean tensor to reduce.\n axis: The dimensions to reduce. If `None` (the default), reduces all\n dimensions. Must be in the range `[-rank(input_tensor),\n rank(input_tensor))`.\n keepdims: If true, retains reduced dimensions with length 1.\n name: A name for the operation (optional).\n reduction_indices: The old (deprecated) name for axis.\n keep_dims: Deprecated alias for `keepdims`.\n\n Returns:\n The reduced tensor.\n\n @compatibility(numpy)\n Equivalent to np.any\n @end_compatibility\n '
axis = deprecation.deprecated_argument_lookup('axis', axis, 'reduction_indices', reduction_indices)
keepdims = deprecation.deprecated_argument_lookup('keepdims', keepdims, 'keep_dims', keep_dims)
return reduce_any(input_tensor, axis, keepdims, name) |
@tf_export('math.reduce_any', 'reduce_any', v1=[])
@dispatch.add_dispatch_support
def reduce_any(input_tensor, axis=None, keepdims=False, name=None):
'Computes the "logical or" of elements across dimensions of a tensor.\n\n Reduces `input_tensor` along the dimensions given in `axis`.\n Unless `keepdims` is true, the rank of the tensor is reduced by 1 for each\n entry in `axis`. If `keepdims` is true, the reduced dimensions\n are retained with length 1.\n\n If `axis` is None, all dimensions are reduced, and a\n tensor with a single element is returned.\n\n For example:\n\n ```python\n x = tf.constant([[True, True], [False, False]])\n tf.reduce_any(x) # True\n tf.reduce_any(x, 0) # [True, True]\n tf.reduce_any(x, 1) # [True, False]\n ```\n\n Args:\n input_tensor: The boolean tensor to reduce.\n axis: The dimensions to reduce. If `None` (the default), reduces all\n dimensions. Must be in the range `[-rank(input_tensor),\n rank(input_tensor))`.\n keepdims: If true, retains reduced dimensions with length 1.\n name: A name for the operation (optional).\n\n Returns:\n The reduced tensor.\n\n @compatibility(numpy)\n Equivalent to np.any\n @end_compatibility\n '
keepdims = (False if (keepdims is None) else keepdims)
return _may_reduce_to_scalar(keepdims, axis, gen_math_ops._any(input_tensor, _ReductionDims(input_tensor, axis), keepdims, name=name)) | 4,303,524,323,399,926,000 | Computes the "logical or" of elements across dimensions of a tensor.
Reduces `input_tensor` along the dimensions given in `axis`.
Unless `keepdims` is true, the rank of the tensor is reduced by 1 for each
entry in `axis`. If `keepdims` is true, the reduced dimensions
are retained with length 1.
If `axis` is None, all dimensions are reduced, and a
tensor with a single element is returned.
For example:
```python
x = tf.constant([[True, True], [False, False]])
tf.reduce_any(x) # True
tf.reduce_any(x, 0) # [True, True]
tf.reduce_any(x, 1) # [True, False]
```
Args:
input_tensor: The boolean tensor to reduce.
axis: The dimensions to reduce. If `None` (the default), reduces all
dimensions. Must be in the range `[-rank(input_tensor),
rank(input_tensor))`.
keepdims: If true, retains reduced dimensions with length 1.
name: A name for the operation (optional).
Returns:
The reduced tensor.
@compatibility(numpy)
Equivalent to np.any
@end_compatibility | tensorflow/python/ops/math_ops.py | reduce_any | minminsun/tensorflow | python | @tf_export('math.reduce_any', 'reduce_any', v1=[])
@dispatch.add_dispatch_support
def reduce_any(input_tensor, axis=None, keepdims=False, name=None):
'Computes the "logical or" of elements across dimensions of a tensor.\n\n Reduces `input_tensor` along the dimensions given in `axis`.\n Unless `keepdims` is true, the rank of the tensor is reduced by 1 for each\n entry in `axis`. If `keepdims` is true, the reduced dimensions\n are retained with length 1.\n\n If `axis` is None, all dimensions are reduced, and a\n tensor with a single element is returned.\n\n For example:\n\n ```python\n x = tf.constant([[True, True], [False, False]])\n tf.reduce_any(x) # True\n tf.reduce_any(x, 0) # [True, True]\n tf.reduce_any(x, 1) # [True, False]\n ```\n\n Args:\n input_tensor: The boolean tensor to reduce.\n axis: The dimensions to reduce. If `None` (the default), reduces all\n dimensions. Must be in the range `[-rank(input_tensor),\n rank(input_tensor))`.\n keepdims: If true, retains reduced dimensions with length 1.\n name: A name for the operation (optional).\n\n Returns:\n The reduced tensor.\n\n @compatibility(numpy)\n Equivalent to np.any\n @end_compatibility\n '
keepdims = (False if (keepdims is None) else keepdims)
return _may_reduce_to_scalar(keepdims, axis, gen_math_ops._any(input_tensor, _ReductionDims(input_tensor, axis), keepdims, name=name)) |
@tf_export(v1=['math.reduce_logsumexp', 'reduce_logsumexp'])
@deprecation.deprecated_args(None, 'keep_dims is deprecated, use keepdims instead', 'keep_dims')
def reduce_logsumexp_v1(input_tensor, axis=None, keepdims=None, name=None, reduction_indices=None, keep_dims=None):
'Computes log(sum(exp(elements across dimensions of a tensor))).\n\n Reduces `input_tensor` along the dimensions given in `axis`.\n Unless `keepdims` is true, the rank of the tensor is reduced by 1 for each\n entry in `axis`. If `keepdims` is true, the reduced dimensions\n are retained with length 1.\n\n If `axis` has no entries, all dimensions are reduced, and a\n tensor with a single element is returned.\n\n This function is more numerically stable than log(sum(exp(input))). It avoids\n overflows caused by taking the exp of large inputs and underflows caused by\n taking the log of small inputs.\n\n For example:\n\n ```python\n x = tf.constant([[0., 0., 0.], [0., 0., 0.]])\n tf.reduce_logsumexp(x) # log(6)\n tf.reduce_logsumexp(x, 0) # [log(2), log(2), log(2)]\n tf.reduce_logsumexp(x, 1) # [log(3), log(3)]\n tf.reduce_logsumexp(x, 1, keepdims=True) # [[log(3)], [log(3)]]\n tf.reduce_logsumexp(x, [0, 1]) # log(6)\n ```\n\n Args:\n input_tensor: The tensor to reduce. Should have numeric type.\n axis: The dimensions to reduce. If `None` (the default), reduces all\n dimensions. Must be in the range `[-rank(input_tensor),\n rank(input_tensor))`.\n keepdims: If true, retains reduced dimensions with length 1.\n name: A name for the operation (optional).\n reduction_indices: The old (deprecated) name for axis.\n keep_dims: Deprecated alias for `keepdims`.\n\n Returns:\n The reduced tensor.\n '
axis = deprecation.deprecated_argument_lookup('axis', axis, 'reduction_indices', reduction_indices)
keepdims = deprecation.deprecated_argument_lookup('keepdims', keepdims, 'keep_dims', keep_dims)
return reduce_logsumexp(input_tensor, axis, keepdims, name) | 3,363,810,572,624,813,000 | Computes log(sum(exp(elements across dimensions of a tensor))).
Reduces `input_tensor` along the dimensions given in `axis`.
Unless `keepdims` is true, the rank of the tensor is reduced by 1 for each
entry in `axis`. If `keepdims` is true, the reduced dimensions
are retained with length 1.
If `axis` has no entries, all dimensions are reduced, and a
tensor with a single element is returned.
This function is more numerically stable than log(sum(exp(input))). It avoids
overflows caused by taking the exp of large inputs and underflows caused by
taking the log of small inputs.
For example:
```python
x = tf.constant([[0., 0., 0.], [0., 0., 0.]])
tf.reduce_logsumexp(x) # log(6)
tf.reduce_logsumexp(x, 0) # [log(2), log(2), log(2)]
tf.reduce_logsumexp(x, 1) # [log(3), log(3)]
tf.reduce_logsumexp(x, 1, keepdims=True) # [[log(3)], [log(3)]]
tf.reduce_logsumexp(x, [0, 1]) # log(6)
```
Args:
input_tensor: The tensor to reduce. Should have numeric type.
axis: The dimensions to reduce. If `None` (the default), reduces all
dimensions. Must be in the range `[-rank(input_tensor),
rank(input_tensor))`.
keepdims: If true, retains reduced dimensions with length 1.
name: A name for the operation (optional).
reduction_indices: The old (deprecated) name for axis.
keep_dims: Deprecated alias for `keepdims`.
Returns:
The reduced tensor. | tensorflow/python/ops/math_ops.py | reduce_logsumexp_v1 | minminsun/tensorflow | python | @tf_export(v1=['math.reduce_logsumexp', 'reduce_logsumexp'])
@deprecation.deprecated_args(None, 'keep_dims is deprecated, use keepdims instead', 'keep_dims')
def reduce_logsumexp_v1(input_tensor, axis=None, keepdims=None, name=None, reduction_indices=None, keep_dims=None):
'Computes log(sum(exp(elements across dimensions of a tensor))).\n\n Reduces `input_tensor` along the dimensions given in `axis`.\n Unless `keepdims` is true, the rank of the tensor is reduced by 1 for each\n entry in `axis`. If `keepdims` is true, the reduced dimensions\n are retained with length 1.\n\n If `axis` has no entries, all dimensions are reduced, and a\n tensor with a single element is returned.\n\n This function is more numerically stable than log(sum(exp(input))). It avoids\n overflows caused by taking the exp of large inputs and underflows caused by\n taking the log of small inputs.\n\n For example:\n\n ```python\n x = tf.constant([[0., 0., 0.], [0., 0., 0.]])\n tf.reduce_logsumexp(x) # log(6)\n tf.reduce_logsumexp(x, 0) # [log(2), log(2), log(2)]\n tf.reduce_logsumexp(x, 1) # [log(3), log(3)]\n tf.reduce_logsumexp(x, 1, keepdims=True) # [[log(3)], [log(3)]]\n tf.reduce_logsumexp(x, [0, 1]) # log(6)\n ```\n\n Args:\n input_tensor: The tensor to reduce. Should have numeric type.\n axis: The dimensions to reduce. If `None` (the default), reduces all\n dimensions. Must be in the range `[-rank(input_tensor),\n rank(input_tensor))`.\n keepdims: If true, retains reduced dimensions with length 1.\n name: A name for the operation (optional).\n reduction_indices: The old (deprecated) name for axis.\n keep_dims: Deprecated alias for `keepdims`.\n\n Returns:\n The reduced tensor.\n '
axis = deprecation.deprecated_argument_lookup('axis', axis, 'reduction_indices', reduction_indices)
keepdims = deprecation.deprecated_argument_lookup('keepdims', keepdims, 'keep_dims', keep_dims)
return reduce_logsumexp(input_tensor, axis, keepdims, name) |
@tf_export('math.reduce_logsumexp', 'reduce_logsumexp', v1=[])
def reduce_logsumexp(input_tensor, axis=None, keepdims=False, name=None):
'Computes log(sum(exp(elements across dimensions of a tensor))).\n\n Reduces `input_tensor` along the dimensions given in `axis`.\n Unless `keepdims` is true, the rank of the tensor is reduced by 1 for each\n entry in `axis`. If `keepdims` is true, the reduced dimensions\n are retained with length 1.\n\n If `axis` has no entries, all dimensions are reduced, and a\n tensor with a single element is returned.\n\n This function is more numerically stable than log(sum(exp(input))). It avoids\n overflows caused by taking the exp of large inputs and underflows caused by\n taking the log of small inputs.\n\n For example:\n\n ```python\n x = tf.constant([[0., 0., 0.], [0., 0., 0.]])\n tf.reduce_logsumexp(x) # log(6)\n tf.reduce_logsumexp(x, 0) # [log(2), log(2), log(2)]\n tf.reduce_logsumexp(x, 1) # [log(3), log(3)]\n tf.reduce_logsumexp(x, 1, keepdims=True) # [[log(3)], [log(3)]]\n tf.reduce_logsumexp(x, [0, 1]) # log(6)\n ```\n\n Args:\n input_tensor: The tensor to reduce. Should have numeric type.\n axis: The dimensions to reduce. If `None` (the default), reduces all\n dimensions. Must be in the range `[-rank(input_tensor),\n rank(input_tensor))`.\n keepdims: If true, retains reduced dimensions with length 1.\n name: A name for the operation (optional).\n\n Returns:\n The reduced tensor.\n '
keepdims = (False if (keepdims is None) else keepdims)
input_tensor = ops.convert_to_tensor(input_tensor)
with ops.name_scope(name, 'ReduceLogSumExp', [input_tensor]) as name:
raw_max = reduce_max(input_tensor, axis=axis, keepdims=True)
my_max = array_ops.stop_gradient(array_ops.where(gen_math_ops.is_finite(raw_max), raw_max, array_ops.zeros_like(raw_max)))
result = gen_math_ops.log(reduce_sum(gen_math_ops.exp(gen_math_ops.sub(input_tensor, my_max)), axis, keepdims=keepdims))
if (not keepdims):
my_max = array_ops.reshape(my_max, array_ops.shape(result))
result = gen_math_ops.add(result, my_max)
return _may_reduce_to_scalar(keepdims, axis, result) | -5,735,506,923,689,613,000 | Computes log(sum(exp(elements across dimensions of a tensor))).
Reduces `input_tensor` along the dimensions given in `axis`.
Unless `keepdims` is true, the rank of the tensor is reduced by 1 for each
entry in `axis`. If `keepdims` is true, the reduced dimensions
are retained with length 1.
If `axis` has no entries, all dimensions are reduced, and a
tensor with a single element is returned.
This function is more numerically stable than log(sum(exp(input))). It avoids
overflows caused by taking the exp of large inputs and underflows caused by
taking the log of small inputs.
For example:
```python
x = tf.constant([[0., 0., 0.], [0., 0., 0.]])
tf.reduce_logsumexp(x) # log(6)
tf.reduce_logsumexp(x, 0) # [log(2), log(2), log(2)]
tf.reduce_logsumexp(x, 1) # [log(3), log(3)]
tf.reduce_logsumexp(x, 1, keepdims=True) # [[log(3)], [log(3)]]
tf.reduce_logsumexp(x, [0, 1]) # log(6)
```
Args:
input_tensor: The tensor to reduce. Should have numeric type.
axis: The dimensions to reduce. If `None` (the default), reduces all
dimensions. Must be in the range `[-rank(input_tensor),
rank(input_tensor))`.
keepdims: If true, retains reduced dimensions with length 1.
name: A name for the operation (optional).
Returns:
The reduced tensor. | tensorflow/python/ops/math_ops.py | reduce_logsumexp | minminsun/tensorflow | python | @tf_export('math.reduce_logsumexp', 'reduce_logsumexp', v1=[])
def reduce_logsumexp(input_tensor, axis=None, keepdims=False, name=None):
'Computes log(sum(exp(elements across dimensions of a tensor))).\n\n Reduces `input_tensor` along the dimensions given in `axis`.\n Unless `keepdims` is true, the rank of the tensor is reduced by 1 for each\n entry in `axis`. If `keepdims` is true, the reduced dimensions\n are retained with length 1.\n\n If `axis` has no entries, all dimensions are reduced, and a\n tensor with a single element is returned.\n\n This function is more numerically stable than log(sum(exp(input))). It avoids\n overflows caused by taking the exp of large inputs and underflows caused by\n taking the log of small inputs.\n\n For example:\n\n ```python\n x = tf.constant([[0., 0., 0.], [0., 0., 0.]])\n tf.reduce_logsumexp(x) # log(6)\n tf.reduce_logsumexp(x, 0) # [log(2), log(2), log(2)]\n tf.reduce_logsumexp(x, 1) # [log(3), log(3)]\n tf.reduce_logsumexp(x, 1, keepdims=True) # [[log(3)], [log(3)]]\n tf.reduce_logsumexp(x, [0, 1]) # log(6)\n ```\n\n Args:\n input_tensor: The tensor to reduce. Should have numeric type.\n axis: The dimensions to reduce. If `None` (the default), reduces all\n dimensions. Must be in the range `[-rank(input_tensor),\n rank(input_tensor))`.\n keepdims: If true, retains reduced dimensions with length 1.\n name: A name for the operation (optional).\n\n Returns:\n The reduced tensor.\n '
keepdims = (False if (keepdims is None) else keepdims)
input_tensor = ops.convert_to_tensor(input_tensor)
with ops.name_scope(name, 'ReduceLogSumExp', [input_tensor]) as name:
raw_max = reduce_max(input_tensor, axis=axis, keepdims=True)
my_max = array_ops.stop_gradient(array_ops.where(gen_math_ops.is_finite(raw_max), raw_max, array_ops.zeros_like(raw_max)))
result = gen_math_ops.log(reduce_sum(gen_math_ops.exp(gen_math_ops.sub(input_tensor, my_max)), axis, keepdims=keepdims))
if (not keepdims):
my_max = array_ops.reshape(my_max, array_ops.shape(result))
result = gen_math_ops.add(result, my_max)
return _may_reduce_to_scalar(keepdims, axis, result) |
@tf_export('linalg.trace', v1=['linalg.trace', 'trace'])
@deprecation.deprecated_endpoints('trace')
def trace(x, name=None):
'Compute the trace of a tensor `x`.\n\n `trace(x)` returns the sum along the main diagonal of each inner-most matrix\n in x. If x is of rank `k` with shape `[I, J, K, ..., L, M, N]`, then output\n is a tensor of rank `k-2` with dimensions `[I, J, K, ..., L]` where\n\n `output[i, j, k, ..., l] = trace(x[i, j, i, ..., l, :, :])`\n\n For example:\n\n ```python\n x = tf.constant([[1, 2], [3, 4]])\n tf.linalg.trace(x) # 5\n\n x = tf.constant([[1, 2, 3],\n [4, 5, 6],\n [7, 8, 9]])\n tf.linalg.trace(x) # 15\n\n x = tf.constant([[[1, 2, 3],\n [4, 5, 6],\n [7, 8, 9]],\n [[-1, -2, -3],\n [-4, -5, -6],\n [-7, -8, -9]]])\n tf.linalg.trace(x) # [15, -15]\n ```\n\n Args:\n x: tensor.\n name: A name for the operation (optional).\n\n Returns:\n The trace of input tensor.\n '
with ops.name_scope(name, 'Trace', [x]) as name:
x = ops.convert_to_tensor(x, name='x')
return reduce_sum(array_ops.matrix_diag_part(x), [(- 1)], name=name) | -3,322,411,102,757,272,000 | Compute the trace of a tensor `x`.
`trace(x)` returns the sum along the main diagonal of each inner-most matrix
in x. If x is of rank `k` with shape `[I, J, K, ..., L, M, N]`, then output
is a tensor of rank `k-2` with dimensions `[I, J, K, ..., L]` where
`output[i, j, k, ..., l] = trace(x[i, j, i, ..., l, :, :])`
For example:
```python
x = tf.constant([[1, 2], [3, 4]])
tf.linalg.trace(x) # 5
x = tf.constant([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
tf.linalg.trace(x) # 15
x = tf.constant([[[1, 2, 3],
[4, 5, 6],
[7, 8, 9]],
[[-1, -2, -3],
[-4, -5, -6],
[-7, -8, -9]]])
tf.linalg.trace(x) # [15, -15]
```
Args:
x: tensor.
name: A name for the operation (optional).
Returns:
The trace of input tensor. | tensorflow/python/ops/math_ops.py | trace | minminsun/tensorflow | python | @tf_export('linalg.trace', v1=['linalg.trace', 'trace'])
@deprecation.deprecated_endpoints('trace')
def trace(x, name=None):
'Compute the trace of a tensor `x`.\n\n `trace(x)` returns the sum along the main diagonal of each inner-most matrix\n in x. If x is of rank `k` with shape `[I, J, K, ..., L, M, N]`, then output\n is a tensor of rank `k-2` with dimensions `[I, J, K, ..., L]` where\n\n `output[i, j, k, ..., l] = trace(x[i, j, i, ..., l, :, :])`\n\n For example:\n\n ```python\n x = tf.constant([[1, 2], [3, 4]])\n tf.linalg.trace(x) # 5\n\n x = tf.constant([[1, 2, 3],\n [4, 5, 6],\n [7, 8, 9]])\n tf.linalg.trace(x) # 15\n\n x = tf.constant([[[1, 2, 3],\n [4, 5, 6],\n [7, 8, 9]],\n [[-1, -2, -3],\n [-4, -5, -6],\n [-7, -8, -9]]])\n tf.linalg.trace(x) # [15, -15]\n ```\n\n Args:\n x: tensor.\n name: A name for the operation (optional).\n\n Returns:\n The trace of input tensor.\n '
with ops.name_scope(name, 'Trace', [x]) as name:
x = ops.convert_to_tensor(x, name='x')
return reduce_sum(array_ops.matrix_diag_part(x), [(- 1)], name=name) |
@tf_export('linalg.matmul', 'matmul')
def matmul(a, b, transpose_a=False, transpose_b=False, adjoint_a=False, adjoint_b=False, a_is_sparse=False, b_is_sparse=False, name=None):
'Multiplies matrix `a` by matrix `b`, producing `a` * `b`.\n\n The inputs must, following any transpositions, be tensors of rank >= 2\n where the inner 2 dimensions specify valid matrix multiplication arguments,\n and any further outer dimensions match.\n\n Both matrices must be of the same type. The supported types are:\n `float16`, `float32`, `float64`, `int32`, `complex64`, `complex128`.\n\n Either matrix can be transposed or adjointed (conjugated and transposed) on\n the fly by setting one of the corresponding flag to `True`. These are `False`\n by default.\n\n If one or both of the matrices contain a lot of zeros, a more efficient\n multiplication algorithm can be used by setting the corresponding\n `a_is_sparse` or `b_is_sparse` flag to `True`. These are `False` by default.\n This optimization is only available for plain matrices (rank-2 tensors) with\n datatypes `bfloat16` or `float32`.\n\n For example:\n\n ```python\n # 2-D tensor `a`\n # [[1, 2, 3],\n # [4, 5, 6]]\n a = tf.constant([1, 2, 3, 4, 5, 6], shape=[2, 3])\n\n # 2-D tensor `b`\n # [[ 7, 8],\n # [ 9, 10],\n # [11, 12]]\n b = tf.constant([7, 8, 9, 10, 11, 12], shape=[3, 2])\n\n # `a` * `b`\n # [[ 58, 64],\n # [139, 154]]\n c = tf.matmul(a, b)\n\n\n # 3-D tensor `a`\n # [[[ 1, 2, 3],\n # [ 4, 5, 6]],\n # [[ 7, 8, 9],\n # [10, 11, 12]]]\n a = tf.constant(np.arange(1, 13, dtype=np.int32),\n shape=[2, 2, 3])\n\n # 3-D tensor `b`\n # [[[13, 14],\n # [15, 16],\n # [17, 18]],\n # [[19, 20],\n # [21, 22],\n # [23, 24]]]\n b = tf.constant(np.arange(13, 25, dtype=np.int32),\n shape=[2, 3, 2])\n\n # `a` * `b`\n # [[[ 94, 100],\n # [229, 244]],\n # [[508, 532],\n # [697, 730]]]\n c = tf.matmul(a, b)\n\n # Since python >= 3.5 the @ operator is supported (see PEP 465).\n # In TensorFlow, it simply calls the `tf.matmul()` function, so the\n # following lines are equivalent:\n d = a @ b @ [[10.], [11.]]\n d = tf.matmul(tf.matmul(a, b), [[10.], [11.]])\n ```\n\n Args:\n a: `Tensor` of type `float16`, `float32`, `float64`, `int32`, `complex64`,\n `complex128` and rank > 1.\n b: `Tensor` with same type and rank as `a`.\n transpose_a: If `True`, `a` is transposed before multiplication.\n transpose_b: If `True`, `b` is transposed before multiplication.\n adjoint_a: If `True`, `a` is conjugated and transposed before\n multiplication.\n adjoint_b: If `True`, `b` is conjugated and transposed before\n multiplication.\n a_is_sparse: If `True`, `a` is treated as a sparse matrix.\n b_is_sparse: If `True`, `b` is treated as a sparse matrix.\n name: Name for the operation (optional).\n\n Returns:\n A `Tensor` of the same type as `a` and `b` where each inner-most matrix is\n the product of the corresponding matrices in `a` and `b`, e.g. if all\n transpose or adjoint attributes are `False`:\n\n `output`[..., i, j] = sum_k (`a`[..., i, k] * `b`[..., k, j]),\n for all indices i, j.\n\n Note: This is matrix product, not element-wise product.\n\n\n Raises:\n ValueError: If transpose_a and adjoint_a, or transpose_b and adjoint_b\n are both set to True.\n '
with ops.name_scope(name, 'MatMul', [a, b]) as name:
if (transpose_a and adjoint_a):
raise ValueError('Only one of transpose_a and adjoint_a can be True.')
if (transpose_b and adjoint_b):
raise ValueError('Only one of transpose_b and adjoint_b can be True.')
if context.executing_eagerly():
if (not isinstance(a, (ops.EagerTensor, _resource_variable_type))):
a = ops.convert_to_tensor(a, name='a')
if (not isinstance(b, (ops.EagerTensor, _resource_variable_type))):
b = ops.convert_to_tensor(b, name='b')
else:
a = ops.convert_to_tensor(a, name='a')
b = ops.convert_to_tensor(b, name='b')
a_shape = a._shape_tuple()
b_shape = b._shape_tuple()
if (((not a_is_sparse) and (not b_is_sparse)) and (((a_shape is None) or (len(a_shape) > 2)) and ((b_shape is None) or (len(b_shape) > 2)))):
if transpose_a:
a = conj(a)
adjoint_a = True
if transpose_b:
b = conj(b)
adjoint_b = True
return gen_math_ops.batch_mat_mul(a, b, adj_x=adjoint_a, adj_y=adjoint_b, name=name)
if adjoint_a:
a = conj(a)
transpose_a = True
if adjoint_b:
b = conj(b)
transpose_b = True
use_sparse_matmul = False
if (a_is_sparse or b_is_sparse):
sparse_matmul_types = [dtypes.bfloat16, dtypes.float32]
use_sparse_matmul = ((a.dtype in sparse_matmul_types) and (b.dtype in sparse_matmul_types))
if (((a.dtype == dtypes.bfloat16) or (b.dtype == dtypes.bfloat16)) and (a.dtype != b.dtype)):
use_sparse_matmul = True
if use_sparse_matmul:
ret = sparse_matmul(a, b, transpose_a=transpose_a, transpose_b=transpose_b, a_is_sparse=a_is_sparse, b_is_sparse=b_is_sparse, name=name)
if ((a.dtype == dtypes.bfloat16) and (b.dtype == dtypes.bfloat16)):
ret = cast(ret, dtypes.bfloat16)
return ret
else:
return gen_math_ops.mat_mul(a, b, transpose_a=transpose_a, transpose_b=transpose_b, name=name) | -7,635,559,913,485,626,000 | Multiplies matrix `a` by matrix `b`, producing `a` * `b`.
The inputs must, following any transpositions, be tensors of rank >= 2
where the inner 2 dimensions specify valid matrix multiplication arguments,
and any further outer dimensions match.
Both matrices must be of the same type. The supported types are:
`float16`, `float32`, `float64`, `int32`, `complex64`, `complex128`.
Either matrix can be transposed or adjointed (conjugated and transposed) on
the fly by setting one of the corresponding flag to `True`. These are `False`
by default.
If one or both of the matrices contain a lot of zeros, a more efficient
multiplication algorithm can be used by setting the corresponding
`a_is_sparse` or `b_is_sparse` flag to `True`. These are `False` by default.
This optimization is only available for plain matrices (rank-2 tensors) with
datatypes `bfloat16` or `float32`.
For example:
```python
# 2-D tensor `a`
# [[1, 2, 3],
# [4, 5, 6]]
a = tf.constant([1, 2, 3, 4, 5, 6], shape=[2, 3])
# 2-D tensor `b`
# [[ 7, 8],
# [ 9, 10],
# [11, 12]]
b = tf.constant([7, 8, 9, 10, 11, 12], shape=[3, 2])
# `a` * `b`
# [[ 58, 64],
# [139, 154]]
c = tf.matmul(a, b)
# 3-D tensor `a`
# [[[ 1, 2, 3],
# [ 4, 5, 6]],
# [[ 7, 8, 9],
# [10, 11, 12]]]
a = tf.constant(np.arange(1, 13, dtype=np.int32),
shape=[2, 2, 3])
# 3-D tensor `b`
# [[[13, 14],
# [15, 16],
# [17, 18]],
# [[19, 20],
# [21, 22],
# [23, 24]]]
b = tf.constant(np.arange(13, 25, dtype=np.int32),
shape=[2, 3, 2])
# `a` * `b`
# [[[ 94, 100],
# [229, 244]],
# [[508, 532],
# [697, 730]]]
c = tf.matmul(a, b)
# Since python >= 3.5 the @ operator is supported (see PEP 465).
# In TensorFlow, it simply calls the `tf.matmul()` function, so the
# following lines are equivalent:
d = a @ b @ [[10.], [11.]]
d = tf.matmul(tf.matmul(a, b), [[10.], [11.]])
```
Args:
a: `Tensor` of type `float16`, `float32`, `float64`, `int32`, `complex64`,
`complex128` and rank > 1.
b: `Tensor` with same type and rank as `a`.
transpose_a: If `True`, `a` is transposed before multiplication.
transpose_b: If `True`, `b` is transposed before multiplication.
adjoint_a: If `True`, `a` is conjugated and transposed before
multiplication.
adjoint_b: If `True`, `b` is conjugated and transposed before
multiplication.
a_is_sparse: If `True`, `a` is treated as a sparse matrix.
b_is_sparse: If `True`, `b` is treated as a sparse matrix.
name: Name for the operation (optional).
Returns:
A `Tensor` of the same type as `a` and `b` where each inner-most matrix is
the product of the corresponding matrices in `a` and `b`, e.g. if all
transpose or adjoint attributes are `False`:
`output`[..., i, j] = sum_k (`a`[..., i, k] * `b`[..., k, j]),
for all indices i, j.
Note: This is matrix product, not element-wise product.
Raises:
ValueError: If transpose_a and adjoint_a, or transpose_b and adjoint_b
are both set to True. | tensorflow/python/ops/math_ops.py | matmul | minminsun/tensorflow | python | @tf_export('linalg.matmul', 'matmul')
def matmul(a, b, transpose_a=False, transpose_b=False, adjoint_a=False, adjoint_b=False, a_is_sparse=False, b_is_sparse=False, name=None):
'Multiplies matrix `a` by matrix `b`, producing `a` * `b`.\n\n The inputs must, following any transpositions, be tensors of rank >= 2\n where the inner 2 dimensions specify valid matrix multiplication arguments,\n and any further outer dimensions match.\n\n Both matrices must be of the same type. The supported types are:\n `float16`, `float32`, `float64`, `int32`, `complex64`, `complex128`.\n\n Either matrix can be transposed or adjointed (conjugated and transposed) on\n the fly by setting one of the corresponding flag to `True`. These are `False`\n by default.\n\n If one or both of the matrices contain a lot of zeros, a more efficient\n multiplication algorithm can be used by setting the corresponding\n `a_is_sparse` or `b_is_sparse` flag to `True`. These are `False` by default.\n This optimization is only available for plain matrices (rank-2 tensors) with\n datatypes `bfloat16` or `float32`.\n\n For example:\n\n ```python\n # 2-D tensor `a`\n # [[1, 2, 3],\n # [4, 5, 6]]\n a = tf.constant([1, 2, 3, 4, 5, 6], shape=[2, 3])\n\n # 2-D tensor `b`\n # [[ 7, 8],\n # [ 9, 10],\n # [11, 12]]\n b = tf.constant([7, 8, 9, 10, 11, 12], shape=[3, 2])\n\n # `a` * `b`\n # [[ 58, 64],\n # [139, 154]]\n c = tf.matmul(a, b)\n\n\n # 3-D tensor `a`\n # [[[ 1, 2, 3],\n # [ 4, 5, 6]],\n # [[ 7, 8, 9],\n # [10, 11, 12]]]\n a = tf.constant(np.arange(1, 13, dtype=np.int32),\n shape=[2, 2, 3])\n\n # 3-D tensor `b`\n # [[[13, 14],\n # [15, 16],\n # [17, 18]],\n # [[19, 20],\n # [21, 22],\n # [23, 24]]]\n b = tf.constant(np.arange(13, 25, dtype=np.int32),\n shape=[2, 3, 2])\n\n # `a` * `b`\n # [[[ 94, 100],\n # [229, 244]],\n # [[508, 532],\n # [697, 730]]]\n c = tf.matmul(a, b)\n\n # Since python >= 3.5 the @ operator is supported (see PEP 465).\n # In TensorFlow, it simply calls the `tf.matmul()` function, so the\n # following lines are equivalent:\n d = a @ b @ [[10.], [11.]]\n d = tf.matmul(tf.matmul(a, b), [[10.], [11.]])\n ```\n\n Args:\n a: `Tensor` of type `float16`, `float32`, `float64`, `int32`, `complex64`,\n `complex128` and rank > 1.\n b: `Tensor` with same type and rank as `a`.\n transpose_a: If `True`, `a` is transposed before multiplication.\n transpose_b: If `True`, `b` is transposed before multiplication.\n adjoint_a: If `True`, `a` is conjugated and transposed before\n multiplication.\n adjoint_b: If `True`, `b` is conjugated and transposed before\n multiplication.\n a_is_sparse: If `True`, `a` is treated as a sparse matrix.\n b_is_sparse: If `True`, `b` is treated as a sparse matrix.\n name: Name for the operation (optional).\n\n Returns:\n A `Tensor` of the same type as `a` and `b` where each inner-most matrix is\n the product of the corresponding matrices in `a` and `b`, e.g. if all\n transpose or adjoint attributes are `False`:\n\n `output`[..., i, j] = sum_k (`a`[..., i, k] * `b`[..., k, j]),\n for all indices i, j.\n\n Note: This is matrix product, not element-wise product.\n\n\n Raises:\n ValueError: If transpose_a and adjoint_a, or transpose_b and adjoint_b\n are both set to True.\n '
with ops.name_scope(name, 'MatMul', [a, b]) as name:
if (transpose_a and adjoint_a):
raise ValueError('Only one of transpose_a and adjoint_a can be True.')
if (transpose_b and adjoint_b):
raise ValueError('Only one of transpose_b and adjoint_b can be True.')
if context.executing_eagerly():
if (not isinstance(a, (ops.EagerTensor, _resource_variable_type))):
a = ops.convert_to_tensor(a, name='a')
if (not isinstance(b, (ops.EagerTensor, _resource_variable_type))):
b = ops.convert_to_tensor(b, name='b')
else:
a = ops.convert_to_tensor(a, name='a')
b = ops.convert_to_tensor(b, name='b')
a_shape = a._shape_tuple()
b_shape = b._shape_tuple()
if (((not a_is_sparse) and (not b_is_sparse)) and (((a_shape is None) or (len(a_shape) > 2)) and ((b_shape is None) or (len(b_shape) > 2)))):
if transpose_a:
a = conj(a)
adjoint_a = True
if transpose_b:
b = conj(b)
adjoint_b = True
return gen_math_ops.batch_mat_mul(a, b, adj_x=adjoint_a, adj_y=adjoint_b, name=name)
if adjoint_a:
a = conj(a)
transpose_a = True
if adjoint_b:
b = conj(b)
transpose_b = True
use_sparse_matmul = False
if (a_is_sparse or b_is_sparse):
sparse_matmul_types = [dtypes.bfloat16, dtypes.float32]
use_sparse_matmul = ((a.dtype in sparse_matmul_types) and (b.dtype in sparse_matmul_types))
if (((a.dtype == dtypes.bfloat16) or (b.dtype == dtypes.bfloat16)) and (a.dtype != b.dtype)):
use_sparse_matmul = True
if use_sparse_matmul:
ret = sparse_matmul(a, b, transpose_a=transpose_a, transpose_b=transpose_b, a_is_sparse=a_is_sparse, b_is_sparse=b_is_sparse, name=name)
if ((a.dtype == dtypes.bfloat16) and (b.dtype == dtypes.bfloat16)):
ret = cast(ret, dtypes.bfloat16)
return ret
else:
return gen_math_ops.mat_mul(a, b, transpose_a=transpose_a, transpose_b=transpose_b, name=name) |
@tf_export('linalg.matvec')
def matvec(a, b, transpose_a=False, adjoint_a=False, a_is_sparse=False, b_is_sparse=False, name=None):
'Multiplies matrix `a` by vector `b`, producing `a` * `b`.\n\n The matrix `a` must, following any transpositions, be a tensor of rank >= 2,\n and we must have `shape(b) = shape(a)[:-2] + [shape(a)[-1]]`.\n\n Both `a` and `b` must be of the same type. The supported types are:\n `float16`, `float32`, `float64`, `int32`, `complex64`, `complex128`.\n\n Matrix `a` can be transposed or adjointed (conjugated and transposed) on\n the fly by setting one of the corresponding flag to `True`. These are `False`\n by default.\n\n If one or both of the inputs contain a lot of zeros, a more efficient\n multiplication algorithm can be used by setting the corresponding\n `a_is_sparse` or `b_is_sparse` flag to `True`. These are `False` by default.\n This optimization is only available for plain matrices/vectors (rank-2/1\n tensors) with datatypes `bfloat16` or `float32`.\n\n For example:\n\n ```python\n # 2-D tensor `a`\n # [[1, 2, 3],\n # [4, 5, 6]]\n a = tf.constant([1, 2, 3, 4, 5, 6], shape=[2, 3])\n\n # 1-D tensor `b`\n # [7, 9, 11]\n b = tf.constant([7, 9, 11], shape=[3])\n\n # `a` * `b`\n # [ 58, 64]\n c = tf.matvec(a, b)\n\n\n # 3-D tensor `a`\n # [[[ 1, 2, 3],\n # [ 4, 5, 6]],\n # [[ 7, 8, 9],\n # [10, 11, 12]]]\n a = tf.constant(np.arange(1, 13, dtype=np.int32),\n shape=[2, 2, 3])\n\n # 2-D tensor `b`\n # [[13, 14, 15],\n # [16, 17, 18]]\n b = tf.constant(np.arange(13, 19, dtype=np.int32),\n shape=[2, 3])\n\n # `a` * `b`\n # [[ 86, 212],\n # [410, 563]]\n c = tf.matvec(a, b)\n ```\n\n Args:\n a: `Tensor` of type `float16`, `float32`, `float64`, `int32`, `complex64`,\n `complex128` and rank > 1.\n b: `Tensor` with same type and rank = `rank(a) - 1`.\n transpose_a: If `True`, `a` is transposed before multiplication.\n adjoint_a: If `True`, `a` is conjugated and transposed before\n multiplication.\n a_is_sparse: If `True`, `a` is treated as a sparse matrix.\n b_is_sparse: If `True`, `b` is treated as a sparse matrix.\n name: Name for the operation (optional).\n\n Returns:\n A `Tensor` of the same type as `a` and `b` where each inner-most vector is\n the product of the corresponding matrices in `a` and vectors in `b`, e.g. if\n all transpose or adjoint attributes are `False`:\n\n `output`[..., i] = sum_k (`a`[..., i, k] * `b`[..., k]), for all indices i.\n\n Note: This is matrix-vector product, not element-wise product.\n\n\n Raises:\n ValueError: If transpose_a and adjoint_a are both set to True.\n '
with ops.name_scope(name, 'MatVec', [a, b]) as name:
output = matmul(a, array_ops.expand_dims(b, axis=(- 1)), transpose_a=transpose_a, adjoint_a=adjoint_a, a_is_sparse=a_is_sparse, b_is_sparse=b_is_sparse)
return array_ops.squeeze(output, axis=(- 1)) | -1,994,279,374,956,680,400 | Multiplies matrix `a` by vector `b`, producing `a` * `b`.
The matrix `a` must, following any transpositions, be a tensor of rank >= 2,
and we must have `shape(b) = shape(a)[:-2] + [shape(a)[-1]]`.
Both `a` and `b` must be of the same type. The supported types are:
`float16`, `float32`, `float64`, `int32`, `complex64`, `complex128`.
Matrix `a` can be transposed or adjointed (conjugated and transposed) on
the fly by setting one of the corresponding flag to `True`. These are `False`
by default.
If one or both of the inputs contain a lot of zeros, a more efficient
multiplication algorithm can be used by setting the corresponding
`a_is_sparse` or `b_is_sparse` flag to `True`. These are `False` by default.
This optimization is only available for plain matrices/vectors (rank-2/1
tensors) with datatypes `bfloat16` or `float32`.
For example:
```python
# 2-D tensor `a`
# [[1, 2, 3],
# [4, 5, 6]]
a = tf.constant([1, 2, 3, 4, 5, 6], shape=[2, 3])
# 1-D tensor `b`
# [7, 9, 11]
b = tf.constant([7, 9, 11], shape=[3])
# `a` * `b`
# [ 58, 64]
c = tf.matvec(a, b)
# 3-D tensor `a`
# [[[ 1, 2, 3],
# [ 4, 5, 6]],
# [[ 7, 8, 9],
# [10, 11, 12]]]
a = tf.constant(np.arange(1, 13, dtype=np.int32),
shape=[2, 2, 3])
# 2-D tensor `b`
# [[13, 14, 15],
# [16, 17, 18]]
b = tf.constant(np.arange(13, 19, dtype=np.int32),
shape=[2, 3])
# `a` * `b`
# [[ 86, 212],
# [410, 563]]
c = tf.matvec(a, b)
```
Args:
a: `Tensor` of type `float16`, `float32`, `float64`, `int32`, `complex64`,
`complex128` and rank > 1.
b: `Tensor` with same type and rank = `rank(a) - 1`.
transpose_a: If `True`, `a` is transposed before multiplication.
adjoint_a: If `True`, `a` is conjugated and transposed before
multiplication.
a_is_sparse: If `True`, `a` is treated as a sparse matrix.
b_is_sparse: If `True`, `b` is treated as a sparse matrix.
name: Name for the operation (optional).
Returns:
A `Tensor` of the same type as `a` and `b` where each inner-most vector is
the product of the corresponding matrices in `a` and vectors in `b`, e.g. if
all transpose or adjoint attributes are `False`:
`output`[..., i] = sum_k (`a`[..., i, k] * `b`[..., k]), for all indices i.
Note: This is matrix-vector product, not element-wise product.
Raises:
ValueError: If transpose_a and adjoint_a are both set to True. | tensorflow/python/ops/math_ops.py | matvec | minminsun/tensorflow | python | @tf_export('linalg.matvec')
def matvec(a, b, transpose_a=False, adjoint_a=False, a_is_sparse=False, b_is_sparse=False, name=None):
'Multiplies matrix `a` by vector `b`, producing `a` * `b`.\n\n The matrix `a` must, following any transpositions, be a tensor of rank >= 2,\n and we must have `shape(b) = shape(a)[:-2] + [shape(a)[-1]]`.\n\n Both `a` and `b` must be of the same type. The supported types are:\n `float16`, `float32`, `float64`, `int32`, `complex64`, `complex128`.\n\n Matrix `a` can be transposed or adjointed (conjugated and transposed) on\n the fly by setting one of the corresponding flag to `True`. These are `False`\n by default.\n\n If one or both of the inputs contain a lot of zeros, a more efficient\n multiplication algorithm can be used by setting the corresponding\n `a_is_sparse` or `b_is_sparse` flag to `True`. These are `False` by default.\n This optimization is only available for plain matrices/vectors (rank-2/1\n tensors) with datatypes `bfloat16` or `float32`.\n\n For example:\n\n ```python\n # 2-D tensor `a`\n # [[1, 2, 3],\n # [4, 5, 6]]\n a = tf.constant([1, 2, 3, 4, 5, 6], shape=[2, 3])\n\n # 1-D tensor `b`\n # [7, 9, 11]\n b = tf.constant([7, 9, 11], shape=[3])\n\n # `a` * `b`\n # [ 58, 64]\n c = tf.matvec(a, b)\n\n\n # 3-D tensor `a`\n # [[[ 1, 2, 3],\n # [ 4, 5, 6]],\n # [[ 7, 8, 9],\n # [10, 11, 12]]]\n a = tf.constant(np.arange(1, 13, dtype=np.int32),\n shape=[2, 2, 3])\n\n # 2-D tensor `b`\n # [[13, 14, 15],\n # [16, 17, 18]]\n b = tf.constant(np.arange(13, 19, dtype=np.int32),\n shape=[2, 3])\n\n # `a` * `b`\n # [[ 86, 212],\n # [410, 563]]\n c = tf.matvec(a, b)\n ```\n\n Args:\n a: `Tensor` of type `float16`, `float32`, `float64`, `int32`, `complex64`,\n `complex128` and rank > 1.\n b: `Tensor` with same type and rank = `rank(a) - 1`.\n transpose_a: If `True`, `a` is transposed before multiplication.\n adjoint_a: If `True`, `a` is conjugated and transposed before\n multiplication.\n a_is_sparse: If `True`, `a` is treated as a sparse matrix.\n b_is_sparse: If `True`, `b` is treated as a sparse matrix.\n name: Name for the operation (optional).\n\n Returns:\n A `Tensor` of the same type as `a` and `b` where each inner-most vector is\n the product of the corresponding matrices in `a` and vectors in `b`, e.g. if\n all transpose or adjoint attributes are `False`:\n\n `output`[..., i] = sum_k (`a`[..., i, k] * `b`[..., k]), for all indices i.\n\n Note: This is matrix-vector product, not element-wise product.\n\n\n Raises:\n ValueError: If transpose_a and adjoint_a are both set to True.\n '
with ops.name_scope(name, 'MatVec', [a, b]) as name:
output = matmul(a, array_ops.expand_dims(b, axis=(- 1)), transpose_a=transpose_a, adjoint_a=adjoint_a, a_is_sparse=a_is_sparse, b_is_sparse=b_is_sparse)
return array_ops.squeeze(output, axis=(- 1)) |
@ops.RegisterStatistics('MatMul', 'flops')
def _calc_mat_mul_flops(graph, node):
'Calculates the compute resources needed for MatMul.'
transpose_a = node.attr['transpose_a'].b
a_shape = graph_util.tensor_shape_from_node_def_name(graph, node.input[0])
a_shape.assert_is_fully_defined()
if transpose_a:
k = int(a_shape[0])
else:
k = int(a_shape[1])
output_shape = graph_util.tensor_shape_from_node_def_name(graph, node.name)
output_shape.assert_is_fully_defined()
output_count = np.prod(output_shape.as_list())
return ops.OpStats('flops', ((k * output_count) * 2)) | 4,539,289,546,934,779,400 | Calculates the compute resources needed for MatMul. | tensorflow/python/ops/math_ops.py | _calc_mat_mul_flops | minminsun/tensorflow | python | @ops.RegisterStatistics('MatMul', 'flops')
def _calc_mat_mul_flops(graph, node):
transpose_a = node.attr['transpose_a'].b
a_shape = graph_util.tensor_shape_from_node_def_name(graph, node.input[0])
a_shape.assert_is_fully_defined()
if transpose_a:
k = int(a_shape[0])
else:
k = int(a_shape[1])
output_shape = graph_util.tensor_shape_from_node_def_name(graph, node.name)
output_shape.assert_is_fully_defined()
output_count = np.prod(output_shape.as_list())
return ops.OpStats('flops', ((k * output_count) * 2)) |
def _as_indexed_slices(x, optimize=True):
"Convert 'x' to IndexedSlices.\n\n Convert a dense Tensor to a block-sparse IndexedSlices.\n\n Args:\n x: Either a Tensor object, or an IndexedSlices object.\n optimize: if true, attempt to optimize the conversion of 'x'.\n\n Returns:\n An IndexedSlices object.\n\n Raises:\n TypeError: If 'x' is not a Tensor or an IndexedSlices object.\n "
if (not isinstance(x, (ops.Tensor, ops.IndexedSlices))):
raise TypeError(('Not a Tensor or IndexedSlices: %s' % type(x)))
if isinstance(x, ops.IndexedSlices):
return x
x_shape = array_ops.shape_internal(x, optimize=optimize)
return ops.IndexedSlices(x, range(0, x_shape[0]), x_shape) | 5,001,471,169,256,508,000 | Convert 'x' to IndexedSlices.
Convert a dense Tensor to a block-sparse IndexedSlices.
Args:
x: Either a Tensor object, or an IndexedSlices object.
optimize: if true, attempt to optimize the conversion of 'x'.
Returns:
An IndexedSlices object.
Raises:
TypeError: If 'x' is not a Tensor or an IndexedSlices object. | tensorflow/python/ops/math_ops.py | _as_indexed_slices | minminsun/tensorflow | python | def _as_indexed_slices(x, optimize=True):
"Convert 'x' to IndexedSlices.\n\n Convert a dense Tensor to a block-sparse IndexedSlices.\n\n Args:\n x: Either a Tensor object, or an IndexedSlices object.\n optimize: if true, attempt to optimize the conversion of 'x'.\n\n Returns:\n An IndexedSlices object.\n\n Raises:\n TypeError: If 'x' is not a Tensor or an IndexedSlices object.\n "
if (not isinstance(x, (ops.Tensor, ops.IndexedSlices))):
raise TypeError(('Not a Tensor or IndexedSlices: %s' % type(x)))
if isinstance(x, ops.IndexedSlices):
return x
x_shape = array_ops.shape_internal(x, optimize=optimize)
return ops.IndexedSlices(x, range(0, x_shape[0]), x_shape) |
def _as_indexed_slices_list(inputs, optimize=True):
"Convert all elements of 'inputs' to IndexedSlices.\n\n Additionally, homogenize the types of all the indices to\n either int32 or int64.\n\n Args:\n inputs: List containing either Tensor or IndexedSlices objects.\n optimize: if true, attempt to optimize the conversion of each input.\n\n Returns:\n A list of IndexedSlices objects.\n\n Raises:\n TypeError: If 'inputs' is not a list or a tuple.\n "
if (not isinstance(inputs, (list, tuple))):
raise TypeError(('Expected a list or tuple, not a %s' % type(inputs)))
outputs = [_as_indexed_slices(i, optimize=optimize) for i in inputs]
with_int32_index = [o.indices for o in outputs if (o.indices.dtype == dtypes.int32)]
if ((not with_int32_index) or (len(with_int32_index) == len(outputs))):
return outputs
casted_outputs = []
for o in outputs:
if (o.indices.dtype == dtypes.int32):
casted_outputs.append(ops.IndexedSlices(o.values, cast(o.indices, dtypes.int64), o.dense_shape))
else:
casted_outputs.append(o)
return casted_outputs | -6,402,197,960,556,010,000 | Convert all elements of 'inputs' to IndexedSlices.
Additionally, homogenize the types of all the indices to
either int32 or int64.
Args:
inputs: List containing either Tensor or IndexedSlices objects.
optimize: if true, attempt to optimize the conversion of each input.
Returns:
A list of IndexedSlices objects.
Raises:
TypeError: If 'inputs' is not a list or a tuple. | tensorflow/python/ops/math_ops.py | _as_indexed_slices_list | minminsun/tensorflow | python | def _as_indexed_slices_list(inputs, optimize=True):
"Convert all elements of 'inputs' to IndexedSlices.\n\n Additionally, homogenize the types of all the indices to\n either int32 or int64.\n\n Args:\n inputs: List containing either Tensor or IndexedSlices objects.\n optimize: if true, attempt to optimize the conversion of each input.\n\n Returns:\n A list of IndexedSlices objects.\n\n Raises:\n TypeError: If 'inputs' is not a list or a tuple.\n "
if (not isinstance(inputs, (list, tuple))):
raise TypeError(('Expected a list or tuple, not a %s' % type(inputs)))
outputs = [_as_indexed_slices(i, optimize=optimize) for i in inputs]
with_int32_index = [o.indices for o in outputs if (o.indices.dtype == dtypes.int32)]
if ((not with_int32_index) or (len(with_int32_index) == len(outputs))):
return outputs
casted_outputs = []
for o in outputs:
if (o.indices.dtype == dtypes.int32):
casted_outputs.append(ops.IndexedSlices(o.values, cast(o.indices, dtypes.int64), o.dense_shape))
else:
casted_outputs.append(o)
return casted_outputs |
@tf_export('math.add_n', 'add_n')
@dispatch.add_dispatch_support
def add_n(inputs, name=None):
"Adds all input tensors element-wise.\n\n Converts `IndexedSlices` objects into dense tensors prior to adding.\n\n Args:\n inputs: A list of `Tensor` or `IndexedSlices` objects, each with same shape\n and type.\n name: A name for the operation (optional).\n\n Returns:\n A `Tensor` of same shape and type as the elements of `inputs`.\n\n Raises:\n ValueError: If `inputs` don't all have same shape and dtype or the shape\n cannot be inferred.\n "
if ((not inputs) or (not isinstance(inputs, (list, tuple)))):
raise ValueError('inputs must be a list of at least one Tensor/IndexedSlices with the same dtype and shape')
inputs = ops.convert_n_to_tensor_or_indexed_slices(inputs)
if (not all((isinstance(x, (ops.Tensor, ops.IndexedSlices)) for x in inputs))):
raise ValueError('inputs must be a list of at least one Tensor/IndexedSlices with the same dtype and shape')
if (len(inputs) == 1):
if isinstance(inputs[0], ops.IndexedSlices):
values = ops.convert_to_tensor(inputs[0])
else:
values = inputs[0]
if name:
return array_ops.identity(values, name=name)
return values
return gen_math_ops.add_n(inputs, name=name) | 7,431,452,468,637,580,000 | Adds all input tensors element-wise.
Converts `IndexedSlices` objects into dense tensors prior to adding.
Args:
inputs: A list of `Tensor` or `IndexedSlices` objects, each with same shape
and type.
name: A name for the operation (optional).
Returns:
A `Tensor` of same shape and type as the elements of `inputs`.
Raises:
ValueError: If `inputs` don't all have same shape and dtype or the shape
cannot be inferred. | tensorflow/python/ops/math_ops.py | add_n | minminsun/tensorflow | python | @tf_export('math.add_n', 'add_n')
@dispatch.add_dispatch_support
def add_n(inputs, name=None):
"Adds all input tensors element-wise.\n\n Converts `IndexedSlices` objects into dense tensors prior to adding.\n\n Args:\n inputs: A list of `Tensor` or `IndexedSlices` objects, each with same shape\n and type.\n name: A name for the operation (optional).\n\n Returns:\n A `Tensor` of same shape and type as the elements of `inputs`.\n\n Raises:\n ValueError: If `inputs` don't all have same shape and dtype or the shape\n cannot be inferred.\n "
if ((not inputs) or (not isinstance(inputs, (list, tuple)))):
raise ValueError('inputs must be a list of at least one Tensor/IndexedSlices with the same dtype and shape')
inputs = ops.convert_n_to_tensor_or_indexed_slices(inputs)
if (not all((isinstance(x, (ops.Tensor, ops.IndexedSlices)) for x in inputs))):
raise ValueError('inputs must be a list of at least one Tensor/IndexedSlices with the same dtype and shape')
if (len(inputs) == 1):
if isinstance(inputs[0], ops.IndexedSlices):
values = ops.convert_to_tensor(inputs[0])
else:
values = inputs[0]
if name:
return array_ops.identity(values, name=name)
return values
return gen_math_ops.add_n(inputs, name=name) |
@tf_export('math.accumulate_n', v1=['math.accumulate_n', 'accumulate_n'])
@deprecation.deprecated_endpoints('accumulate_n')
def accumulate_n(inputs, shape=None, tensor_dtype=None, name=None):
"Returns the element-wise sum of a list of tensors.\n\n Optionally, pass `shape` and `tensor_dtype` for shape and type checking,\n otherwise, these are inferred.\n\n `tf.math.accumulate_n` performs the same operation as `tf.add_n`, but does not\n wait for all of its inputs to be ready before beginning to sum. This can\n save memory if inputs are ready at different times, since minimum temporary\n storage is proportional to the output size rather than the inputs size.\n\n `accumulate_n` is differentiable (but wasn't previous to TensorFlow 1.7).\n\n For example:\n\n ```python\n a = tf.constant([[1, 2], [3, 4]])\n b = tf.constant([[5, 0], [0, 6]])\n tf.math.accumulate_n([a, b, a]) # [[7, 4], [6, 14]]\n\n # Explicitly pass shape and type\n tf.math.accumulate_n([a, b, a], shape=[2, 2], tensor_dtype=tf.int32)\n # [[7, 4],\n # [6, 14]]\n ```\n\n Args:\n inputs: A list of `Tensor` objects, each with same shape and type.\n shape: Shape of elements of `inputs`.\n tensor_dtype: The type of `inputs`.\n name: A name for the operation (optional).\n\n Returns:\n A `Tensor` of same shape and type as the elements of `inputs`.\n\n Raises:\n ValueError: If `inputs` don't all have same shape and dtype or the shape\n cannot be inferred.\n "
def _input_error():
return ValueError('inputs must be a list of at least one Tensor with the same dtype and shape')
if ((not inputs) or (not isinstance(inputs, (list, tuple)))):
raise _input_error()
inputs = ops.convert_n_to_tensor_or_indexed_slices(inputs)
if (not all((isinstance(x, ops.Tensor) for x in inputs))):
raise _input_error()
if (not all(((x.dtype == inputs[0].dtype) for x in inputs))):
raise _input_error()
if (shape is not None):
shape = tensor_shape.as_shape(shape)
else:
shape = tensor_shape.unknown_shape()
for input_tensor in inputs:
if isinstance(input_tensor, ops.Tensor):
shape = shape.merge_with(input_tensor.get_shape())
if ((tensor_dtype is not None) and (tensor_dtype != inputs[0].dtype)):
raise TypeError('tensor_dtype is {}, but input is of type {}'.format(tensor_dtype, inputs[0].dtype))
if ((len(inputs) == 1) and (name is None)):
return inputs[0]
elif ((len(inputs) == 1) and (name is not None)):
return array_ops.identity(inputs[0], name=name)
elif context.executing_eagerly():
return add_n(inputs, name=name)
else:
return gen_math_ops.accumulate_nv2(inputs, name=name, shape=shape) | 3,628,942,482,496,208,400 | Returns the element-wise sum of a list of tensors.
Optionally, pass `shape` and `tensor_dtype` for shape and type checking,
otherwise, these are inferred.
`tf.math.accumulate_n` performs the same operation as `tf.add_n`, but does not
wait for all of its inputs to be ready before beginning to sum. This can
save memory if inputs are ready at different times, since minimum temporary
storage is proportional to the output size rather than the inputs size.
`accumulate_n` is differentiable (but wasn't previous to TensorFlow 1.7).
For example:
```python
a = tf.constant([[1, 2], [3, 4]])
b = tf.constant([[5, 0], [0, 6]])
tf.math.accumulate_n([a, b, a]) # [[7, 4], [6, 14]]
# Explicitly pass shape and type
tf.math.accumulate_n([a, b, a], shape=[2, 2], tensor_dtype=tf.int32)
# [[7, 4],
# [6, 14]]
```
Args:
inputs: A list of `Tensor` objects, each with same shape and type.
shape: Shape of elements of `inputs`.
tensor_dtype: The type of `inputs`.
name: A name for the operation (optional).
Returns:
A `Tensor` of same shape and type as the elements of `inputs`.
Raises:
ValueError: If `inputs` don't all have same shape and dtype or the shape
cannot be inferred. | tensorflow/python/ops/math_ops.py | accumulate_n | minminsun/tensorflow | python | @tf_export('math.accumulate_n', v1=['math.accumulate_n', 'accumulate_n'])
@deprecation.deprecated_endpoints('accumulate_n')
def accumulate_n(inputs, shape=None, tensor_dtype=None, name=None):
"Returns the element-wise sum of a list of tensors.\n\n Optionally, pass `shape` and `tensor_dtype` for shape and type checking,\n otherwise, these are inferred.\n\n `tf.math.accumulate_n` performs the same operation as `tf.add_n`, but does not\n wait for all of its inputs to be ready before beginning to sum. This can\n save memory if inputs are ready at different times, since minimum temporary\n storage is proportional to the output size rather than the inputs size.\n\n `accumulate_n` is differentiable (but wasn't previous to TensorFlow 1.7).\n\n For example:\n\n ```python\n a = tf.constant([[1, 2], [3, 4]])\n b = tf.constant([[5, 0], [0, 6]])\n tf.math.accumulate_n([a, b, a]) # [[7, 4], [6, 14]]\n\n # Explicitly pass shape and type\n tf.math.accumulate_n([a, b, a], shape=[2, 2], tensor_dtype=tf.int32)\n # [[7, 4],\n # [6, 14]]\n ```\n\n Args:\n inputs: A list of `Tensor` objects, each with same shape and type.\n shape: Shape of elements of `inputs`.\n tensor_dtype: The type of `inputs`.\n name: A name for the operation (optional).\n\n Returns:\n A `Tensor` of same shape and type as the elements of `inputs`.\n\n Raises:\n ValueError: If `inputs` don't all have same shape and dtype or the shape\n cannot be inferred.\n "
def _input_error():
return ValueError('inputs must be a list of at least one Tensor with the same dtype and shape')
if ((not inputs) or (not isinstance(inputs, (list, tuple)))):
raise _input_error()
inputs = ops.convert_n_to_tensor_or_indexed_slices(inputs)
if (not all((isinstance(x, ops.Tensor) for x in inputs))):
raise _input_error()
if (not all(((x.dtype == inputs[0].dtype) for x in inputs))):
raise _input_error()
if (shape is not None):
shape = tensor_shape.as_shape(shape)
else:
shape = tensor_shape.unknown_shape()
for input_tensor in inputs:
if isinstance(input_tensor, ops.Tensor):
shape = shape.merge_with(input_tensor.get_shape())
if ((tensor_dtype is not None) and (tensor_dtype != inputs[0].dtype)):
raise TypeError('tensor_dtype is {}, but input is of type {}'.format(tensor_dtype, inputs[0].dtype))
if ((len(inputs) == 1) and (name is None)):
return inputs[0]
elif ((len(inputs) == 1) and (name is not None)):
return array_ops.identity(inputs[0], name=name)
elif context.executing_eagerly():
return add_n(inputs, name=name)
else:
return gen_math_ops.accumulate_nv2(inputs, name=name, shape=shape) |
@ops.RegisterGradient('AccumulateNV2')
def _accumulate_n_grad(op, grad):
'Same as gradient for AddN. Copies the gradient to all inputs.'
return ([grad] * len(op.inputs)) | -6,715,794,146,925,564,000 | Same as gradient for AddN. Copies the gradient to all inputs. | tensorflow/python/ops/math_ops.py | _accumulate_n_grad | minminsun/tensorflow | python | @ops.RegisterGradient('AccumulateNV2')
def _accumulate_n_grad(op, grad):
return ([grad] * len(op.inputs)) |
@tf_export('math.sigmoid', 'nn.sigmoid', 'sigmoid')
def sigmoid(x, name=None):
'Computes sigmoid of `x` element-wise.\n\n Specifically, `y = 1 / (1 + exp(-x))`.\n\n Args:\n x: A Tensor with type `float16`, `float32`, `float64`, `complex64`,\n or `complex128`.\n name: A name for the operation (optional).\n\n Returns:\n A Tensor with the same type as `x`.\n\n @compatibility(scipy)\n Equivalent to scipy.special.expit\n @end_compatibility\n '
with ops.name_scope(name, 'Sigmoid', [x]) as name:
x = ops.convert_to_tensor(x, name='x')
return gen_math_ops.sigmoid(x, name=name) | -5,913,921,996,781,770,000 | Computes sigmoid of `x` element-wise.
Specifically, `y = 1 / (1 + exp(-x))`.
Args:
x: A Tensor with type `float16`, `float32`, `float64`, `complex64`,
or `complex128`.
name: A name for the operation (optional).
Returns:
A Tensor with the same type as `x`.
@compatibility(scipy)
Equivalent to scipy.special.expit
@end_compatibility | tensorflow/python/ops/math_ops.py | sigmoid | minminsun/tensorflow | python | @tf_export('math.sigmoid', 'nn.sigmoid', 'sigmoid')
def sigmoid(x, name=None):
'Computes sigmoid of `x` element-wise.\n\n Specifically, `y = 1 / (1 + exp(-x))`.\n\n Args:\n x: A Tensor with type `float16`, `float32`, `float64`, `complex64`,\n or `complex128`.\n name: A name for the operation (optional).\n\n Returns:\n A Tensor with the same type as `x`.\n\n @compatibility(scipy)\n Equivalent to scipy.special.expit\n @end_compatibility\n '
with ops.name_scope(name, 'Sigmoid', [x]) as name:
x = ops.convert_to_tensor(x, name='x')
return gen_math_ops.sigmoid(x, name=name) |
@tf_export('math.log_sigmoid', v1=['math.log_sigmoid', 'log_sigmoid'])
@dispatch.add_dispatch_support
@deprecation.deprecated_endpoints('log_sigmoid')
def log_sigmoid(x, name=None):
'Computes log sigmoid of `x` element-wise.\n\n Specifically, `y = log(1 / (1 + exp(-x)))`. For numerical stability,\n we use `y = -tf.nn.softplus(-x)`.\n\n Args:\n x: A Tensor with type `float32` or `float64`.\n name: A name for the operation (optional).\n\n Returns:\n A Tensor with the same type as `x`.\n '
with ops.name_scope(name, 'LogSigmoid', [x]) as name:
x = ops.convert_to_tensor(x, name='x')
return gen_math_ops.neg(gen_nn_ops.softplus((- x)), name=name) | 2,684,433,138,987,555,000 | Computes log sigmoid of `x` element-wise.
Specifically, `y = log(1 / (1 + exp(-x)))`. For numerical stability,
we use `y = -tf.nn.softplus(-x)`.
Args:
x: A Tensor with type `float32` or `float64`.
name: A name for the operation (optional).
Returns:
A Tensor with the same type as `x`. | tensorflow/python/ops/math_ops.py | log_sigmoid | minminsun/tensorflow | python | @tf_export('math.log_sigmoid', v1=['math.log_sigmoid', 'log_sigmoid'])
@dispatch.add_dispatch_support
@deprecation.deprecated_endpoints('log_sigmoid')
def log_sigmoid(x, name=None):
'Computes log sigmoid of `x` element-wise.\n\n Specifically, `y = log(1 / (1 + exp(-x)))`. For numerical stability,\n we use `y = -tf.nn.softplus(-x)`.\n\n Args:\n x: A Tensor with type `float32` or `float64`.\n name: A name for the operation (optional).\n\n Returns:\n A Tensor with the same type as `x`.\n '
with ops.name_scope(name, 'LogSigmoid', [x]) as name:
x = ops.convert_to_tensor(x, name='x')
return gen_math_ops.neg(gen_nn_ops.softplus((- x)), name=name) |
@tf_export('math.bincount', v1=[])
def bincount(arr, weights=None, minlength=None, maxlength=None, dtype=dtypes.int32, name=None):
'Counts the number of occurrences of each value in an integer array.\n\n If `minlength` and `maxlength` are not given, returns a vector with length\n `tf.reduce_max(arr) + 1` if `arr` is non-empty, and length 0 otherwise.\n If `weights` are non-None, then index `i` of the output stores the sum of the\n value in `weights` at each index where the corresponding value in `arr` is\n `i`.\n\n Args:\n arr: An int32 tensor of non-negative values.\n weights: If non-None, must be the same shape as arr. For each value in\n `arr`, the bin will be incremented by the corresponding weight instead of\n 1.\n minlength: If given, ensures the output has length at least `minlength`,\n padding with zeros at the end if necessary.\n maxlength: If given, skips values in `arr` that are equal or greater than\n `maxlength`, ensuring that the output has length at most `maxlength`.\n dtype: If `weights` is None, determines the type of the output bins.\n name: A name scope for the associated operations (optional).\n\n Returns:\n A vector with the same dtype as `weights` or the given `dtype`. The bin\n values.\n '
name = ('bincount' if (name is None) else name)
with ops.name_scope(name):
arr = ops.convert_to_tensor(arr, name='arr', dtype=dtypes.int32)
array_is_nonempty = (reduce_prod(array_ops.shape(arr)) > 0)
output_size = (cast(array_is_nonempty, dtypes.int32) * (reduce_max(arr) + 1))
if (minlength is not None):
minlength = ops.convert_to_tensor(minlength, name='minlength', dtype=dtypes.int32)
output_size = gen_math_ops.maximum(minlength, output_size)
if (maxlength is not None):
maxlength = ops.convert_to_tensor(maxlength, name='maxlength', dtype=dtypes.int32)
output_size = gen_math_ops.minimum(maxlength, output_size)
if (weights is not None):
weights = ops.convert_to_tensor(weights, name='weights')
return gen_math_ops.unsorted_segment_sum(weights, arr, output_size)
weights = constant_op.constant([], dtype)
return gen_math_ops.bincount(arr, output_size, weights) | 2,066,914,436,022,351,400 | Counts the number of occurrences of each value in an integer array.
If `minlength` and `maxlength` are not given, returns a vector with length
`tf.reduce_max(arr) + 1` if `arr` is non-empty, and length 0 otherwise.
If `weights` are non-None, then index `i` of the output stores the sum of the
value in `weights` at each index where the corresponding value in `arr` is
`i`.
Args:
arr: An int32 tensor of non-negative values.
weights: If non-None, must be the same shape as arr. For each value in
`arr`, the bin will be incremented by the corresponding weight instead of
1.
minlength: If given, ensures the output has length at least `minlength`,
padding with zeros at the end if necessary.
maxlength: If given, skips values in `arr` that are equal or greater than
`maxlength`, ensuring that the output has length at most `maxlength`.
dtype: If `weights` is None, determines the type of the output bins.
name: A name scope for the associated operations (optional).
Returns:
A vector with the same dtype as `weights` or the given `dtype`. The bin
values. | tensorflow/python/ops/math_ops.py | bincount | minminsun/tensorflow | python | @tf_export('math.bincount', v1=[])
def bincount(arr, weights=None, minlength=None, maxlength=None, dtype=dtypes.int32, name=None):
'Counts the number of occurrences of each value in an integer array.\n\n If `minlength` and `maxlength` are not given, returns a vector with length\n `tf.reduce_max(arr) + 1` if `arr` is non-empty, and length 0 otherwise.\n If `weights` are non-None, then index `i` of the output stores the sum of the\n value in `weights` at each index where the corresponding value in `arr` is\n `i`.\n\n Args:\n arr: An int32 tensor of non-negative values.\n weights: If non-None, must be the same shape as arr. For each value in\n `arr`, the bin will be incremented by the corresponding weight instead of\n 1.\n minlength: If given, ensures the output has length at least `minlength`,\n padding with zeros at the end if necessary.\n maxlength: If given, skips values in `arr` that are equal or greater than\n `maxlength`, ensuring that the output has length at most `maxlength`.\n dtype: If `weights` is None, determines the type of the output bins.\n name: A name scope for the associated operations (optional).\n\n Returns:\n A vector with the same dtype as `weights` or the given `dtype`. The bin\n values.\n '
name = ('bincount' if (name is None) else name)
with ops.name_scope(name):
arr = ops.convert_to_tensor(arr, name='arr', dtype=dtypes.int32)
array_is_nonempty = (reduce_prod(array_ops.shape(arr)) > 0)
output_size = (cast(array_is_nonempty, dtypes.int32) * (reduce_max(arr) + 1))
if (minlength is not None):
minlength = ops.convert_to_tensor(minlength, name='minlength', dtype=dtypes.int32)
output_size = gen_math_ops.maximum(minlength, output_size)
if (maxlength is not None):
maxlength = ops.convert_to_tensor(maxlength, name='maxlength', dtype=dtypes.int32)
output_size = gen_math_ops.minimum(maxlength, output_size)
if (weights is not None):
weights = ops.convert_to_tensor(weights, name='weights')
return gen_math_ops.unsorted_segment_sum(weights, arr, output_size)
weights = constant_op.constant([], dtype)
return gen_math_ops.bincount(arr, output_size, weights) |
@tf_export(v1=['math.bincount', 'bincount'])
@deprecation.deprecated_endpoints('bincount')
def bincount_v1(arr, weights=None, minlength=None, maxlength=None, dtype=dtypes.int32):
'Counts the number of occurrences of each value in an integer array.\n\n If `minlength` and `maxlength` are not given, returns a vector with length\n `tf.reduce_max(arr) + 1` if `arr` is non-empty, and length 0 otherwise.\n If `weights` are non-None, then index `i` of the output stores the sum of the\n value in `weights` at each index where the corresponding value in `arr` is\n `i`.\n\n Args:\n arr: An int32 tensor of non-negative values.\n weights: If non-None, must be the same shape as arr. For each value in\n `arr`, the bin will be incremented by the corresponding weight instead of\n 1.\n minlength: If given, ensures the output has length at least `minlength`,\n padding with zeros at the end if necessary.\n maxlength: If given, skips values in `arr` that are equal or greater than\n `maxlength`, ensuring that the output has length at most `maxlength`.\n dtype: If `weights` is None, determines the type of the output bins.\n\n Returns:\n A vector with the same dtype as `weights` or the given `dtype`. The bin\n values.\n '
return bincount(arr, weights, minlength, maxlength, dtype) | 1,028,371,735,247,038,600 | Counts the number of occurrences of each value in an integer array.
If `minlength` and `maxlength` are not given, returns a vector with length
`tf.reduce_max(arr) + 1` if `arr` is non-empty, and length 0 otherwise.
If `weights` are non-None, then index `i` of the output stores the sum of the
value in `weights` at each index where the corresponding value in `arr` is
`i`.
Args:
arr: An int32 tensor of non-negative values.
weights: If non-None, must be the same shape as arr. For each value in
`arr`, the bin will be incremented by the corresponding weight instead of
1.
minlength: If given, ensures the output has length at least `minlength`,
padding with zeros at the end if necessary.
maxlength: If given, skips values in `arr` that are equal or greater than
`maxlength`, ensuring that the output has length at most `maxlength`.
dtype: If `weights` is None, determines the type of the output bins.
Returns:
A vector with the same dtype as `weights` or the given `dtype`. The bin
values. | tensorflow/python/ops/math_ops.py | bincount_v1 | minminsun/tensorflow | python | @tf_export(v1=['math.bincount', 'bincount'])
@deprecation.deprecated_endpoints('bincount')
def bincount_v1(arr, weights=None, minlength=None, maxlength=None, dtype=dtypes.int32):
'Counts the number of occurrences of each value in an integer array.\n\n If `minlength` and `maxlength` are not given, returns a vector with length\n `tf.reduce_max(arr) + 1` if `arr` is non-empty, and length 0 otherwise.\n If `weights` are non-None, then index `i` of the output stores the sum of the\n value in `weights` at each index where the corresponding value in `arr` is\n `i`.\n\n Args:\n arr: An int32 tensor of non-negative values.\n weights: If non-None, must be the same shape as arr. For each value in\n `arr`, the bin will be incremented by the corresponding weight instead of\n 1.\n minlength: If given, ensures the output has length at least `minlength`,\n padding with zeros at the end if necessary.\n maxlength: If given, skips values in `arr` that are equal or greater than\n `maxlength`, ensuring that the output has length at most `maxlength`.\n dtype: If `weights` is None, determines the type of the output bins.\n\n Returns:\n A vector with the same dtype as `weights` or the given `dtype`. The bin\n values.\n '
return bincount(arr, weights, minlength, maxlength, dtype) |
@tf_export('math.cumsum', 'cumsum')
def cumsum(x, axis=0, exclusive=False, reverse=False, name=None):
'Compute the cumulative sum of the tensor `x` along `axis`.\n\n By default, this op performs an inclusive cumsum, which means that the first\n element of the input is identical to the first element of the output:\n\n ```python\n tf.cumsum([a, b, c]) # [a, a + b, a + b + c]\n ```\n\n By setting the `exclusive` kwarg to `True`, an exclusive cumsum is performed\n instead:\n\n ```python\n tf.cumsum([a, b, c], exclusive=True) # [0, a, a + b]\n ```\n\n By setting the `reverse` kwarg to `True`, the cumsum is performed in the\n opposite direction:\n\n ```python\n tf.cumsum([a, b, c], reverse=True) # [a + b + c, b + c, c]\n ```\n\n This is more efficient than using separate `tf.reverse` ops.\n\n The `reverse` and `exclusive` kwargs can also be combined:\n\n ```python\n tf.cumsum([a, b, c], exclusive=True, reverse=True) # [b + c, c, 0]\n ```\n\n Args:\n x: A `Tensor`. Must be one of the following types: `float32`, `float64`,\n `int64`, `int32`, `uint8`, `uint16`, `int16`, `int8`, `complex64`,\n `complex128`, `qint8`, `quint8`, `qint32`, `half`.\n axis: A `Tensor` of type `int32` (default: 0). Must be in the range\n `[-rank(x), rank(x))`.\n exclusive: If `True`, perform exclusive cumsum.\n reverse: A `bool` (default: False).\n name: A name for the operation (optional).\n\n Returns:\n A `Tensor`. Has the same type as `x`.\n '
with ops.name_scope(name, 'Cumsum', [x]) as name:
x = ops.convert_to_tensor(x, name='x')
return gen_math_ops.cumsum(x, axis, exclusive=exclusive, reverse=reverse, name=name) | -5,548,327,466,838,296,000 | Compute the cumulative sum of the tensor `x` along `axis`.
By default, this op performs an inclusive cumsum, which means that the first
element of the input is identical to the first element of the output:
```python
tf.cumsum([a, b, c]) # [a, a + b, a + b + c]
```
By setting the `exclusive` kwarg to `True`, an exclusive cumsum is performed
instead:
```python
tf.cumsum([a, b, c], exclusive=True) # [0, a, a + b]
```
By setting the `reverse` kwarg to `True`, the cumsum is performed in the
opposite direction:
```python
tf.cumsum([a, b, c], reverse=True) # [a + b + c, b + c, c]
```
This is more efficient than using separate `tf.reverse` ops.
The `reverse` and `exclusive` kwargs can also be combined:
```python
tf.cumsum([a, b, c], exclusive=True, reverse=True) # [b + c, c, 0]
```
Args:
x: A `Tensor`. Must be one of the following types: `float32`, `float64`,
`int64`, `int32`, `uint8`, `uint16`, `int16`, `int8`, `complex64`,
`complex128`, `qint8`, `quint8`, `qint32`, `half`.
axis: A `Tensor` of type `int32` (default: 0). Must be in the range
`[-rank(x), rank(x))`.
exclusive: If `True`, perform exclusive cumsum.
reverse: A `bool` (default: False).
name: A name for the operation (optional).
Returns:
A `Tensor`. Has the same type as `x`. | tensorflow/python/ops/math_ops.py | cumsum | minminsun/tensorflow | python | @tf_export('math.cumsum', 'cumsum')
def cumsum(x, axis=0, exclusive=False, reverse=False, name=None):
'Compute the cumulative sum of the tensor `x` along `axis`.\n\n By default, this op performs an inclusive cumsum, which means that the first\n element of the input is identical to the first element of the output:\n\n ```python\n tf.cumsum([a, b, c]) # [a, a + b, a + b + c]\n ```\n\n By setting the `exclusive` kwarg to `True`, an exclusive cumsum is performed\n instead:\n\n ```python\n tf.cumsum([a, b, c], exclusive=True) # [0, a, a + b]\n ```\n\n By setting the `reverse` kwarg to `True`, the cumsum is performed in the\n opposite direction:\n\n ```python\n tf.cumsum([a, b, c], reverse=True) # [a + b + c, b + c, c]\n ```\n\n This is more efficient than using separate `tf.reverse` ops.\n\n The `reverse` and `exclusive` kwargs can also be combined:\n\n ```python\n tf.cumsum([a, b, c], exclusive=True, reverse=True) # [b + c, c, 0]\n ```\n\n Args:\n x: A `Tensor`. Must be one of the following types: `float32`, `float64`,\n `int64`, `int32`, `uint8`, `uint16`, `int16`, `int8`, `complex64`,\n `complex128`, `qint8`, `quint8`, `qint32`, `half`.\n axis: A `Tensor` of type `int32` (default: 0). Must be in the range\n `[-rank(x), rank(x))`.\n exclusive: If `True`, perform exclusive cumsum.\n reverse: A `bool` (default: False).\n name: A name for the operation (optional).\n\n Returns:\n A `Tensor`. Has the same type as `x`.\n '
with ops.name_scope(name, 'Cumsum', [x]) as name:
x = ops.convert_to_tensor(x, name='x')
return gen_math_ops.cumsum(x, axis, exclusive=exclusive, reverse=reverse, name=name) |
@tf_export('math.cumprod', v1=['math.cumprod', 'cumprod'])
@deprecation.deprecated_endpoints('cumprod')
def cumprod(x, axis=0, exclusive=False, reverse=False, name=None):
'Compute the cumulative product of the tensor `x` along `axis`.\n\n By default, this op performs an inclusive cumprod, which means that the\n first element of the input is identical to the first element of the output:\n\n ```python\n tf.math.cumprod([a, b, c]) # [a, a * b, a * b * c]\n ```\n\n By setting the `exclusive` kwarg to `True`, an exclusive cumprod is\n performed\n instead:\n\n ```python\n tf.math.cumprod([a, b, c], exclusive=True) # [1, a, a * b]\n ```\n\n By setting the `reverse` kwarg to `True`, the cumprod is performed in the\n opposite direction:\n\n ```python\n tf.math.cumprod([a, b, c], reverse=True) # [a * b * c, b * c, c]\n ```\n\n This is more efficient than using separate `tf.reverse` ops.\n The `reverse` and `exclusive` kwargs can also be combined:\n\n ```python\n tf.math.cumprod([a, b, c], exclusive=True, reverse=True) # [b * c, c, 1]\n ```\n\n Args:\n x: A `Tensor`. Must be one of the following types: `float32`, `float64`,\n `int64`, `int32`, `uint8`, `uint16`, `int16`, `int8`, `complex64`,\n `complex128`, `qint8`, `quint8`, `qint32`, `half`.\n axis: A `Tensor` of type `int32` (default: 0). Must be in the range\n `[-rank(x), rank(x))`.\n exclusive: If `True`, perform exclusive cumprod.\n reverse: A `bool` (default: False).\n name: A name for the operation (optional).\n\n Returns:\n A `Tensor`. Has the same type as `x`.\n '
with ops.name_scope(name, 'Cumprod', [x]) as name:
x = ops.convert_to_tensor(x, name='x')
return gen_math_ops.cumprod(x, axis, exclusive=exclusive, reverse=reverse, name=name) | -7,603,428,310,472,397,000 | Compute the cumulative product of the tensor `x` along `axis`.
By default, this op performs an inclusive cumprod, which means that the
first element of the input is identical to the first element of the output:
```python
tf.math.cumprod([a, b, c]) # [a, a * b, a * b * c]
```
By setting the `exclusive` kwarg to `True`, an exclusive cumprod is
performed
instead:
```python
tf.math.cumprod([a, b, c], exclusive=True) # [1, a, a * b]
```
By setting the `reverse` kwarg to `True`, the cumprod is performed in the
opposite direction:
```python
tf.math.cumprod([a, b, c], reverse=True) # [a * b * c, b * c, c]
```
This is more efficient than using separate `tf.reverse` ops.
The `reverse` and `exclusive` kwargs can also be combined:
```python
tf.math.cumprod([a, b, c], exclusive=True, reverse=True) # [b * c, c, 1]
```
Args:
x: A `Tensor`. Must be one of the following types: `float32`, `float64`,
`int64`, `int32`, `uint8`, `uint16`, `int16`, `int8`, `complex64`,
`complex128`, `qint8`, `quint8`, `qint32`, `half`.
axis: A `Tensor` of type `int32` (default: 0). Must be in the range
`[-rank(x), rank(x))`.
exclusive: If `True`, perform exclusive cumprod.
reverse: A `bool` (default: False).
name: A name for the operation (optional).
Returns:
A `Tensor`. Has the same type as `x`. | tensorflow/python/ops/math_ops.py | cumprod | minminsun/tensorflow | python | @tf_export('math.cumprod', v1=['math.cumprod', 'cumprod'])
@deprecation.deprecated_endpoints('cumprod')
def cumprod(x, axis=0, exclusive=False, reverse=False, name=None):
'Compute the cumulative product of the tensor `x` along `axis`.\n\n By default, this op performs an inclusive cumprod, which means that the\n first element of the input is identical to the first element of the output:\n\n ```python\n tf.math.cumprod([a, b, c]) # [a, a * b, a * b * c]\n ```\n\n By setting the `exclusive` kwarg to `True`, an exclusive cumprod is\n performed\n instead:\n\n ```python\n tf.math.cumprod([a, b, c], exclusive=True) # [1, a, a * b]\n ```\n\n By setting the `reverse` kwarg to `True`, the cumprod is performed in the\n opposite direction:\n\n ```python\n tf.math.cumprod([a, b, c], reverse=True) # [a * b * c, b * c, c]\n ```\n\n This is more efficient than using separate `tf.reverse` ops.\n The `reverse` and `exclusive` kwargs can also be combined:\n\n ```python\n tf.math.cumprod([a, b, c], exclusive=True, reverse=True) # [b * c, c, 1]\n ```\n\n Args:\n x: A `Tensor`. Must be one of the following types: `float32`, `float64`,\n `int64`, `int32`, `uint8`, `uint16`, `int16`, `int8`, `complex64`,\n `complex128`, `qint8`, `quint8`, `qint32`, `half`.\n axis: A `Tensor` of type `int32` (default: 0). Must be in the range\n `[-rank(x), rank(x))`.\n exclusive: If `True`, perform exclusive cumprod.\n reverse: A `bool` (default: False).\n name: A name for the operation (optional).\n\n Returns:\n A `Tensor`. Has the same type as `x`.\n '
with ops.name_scope(name, 'Cumprod', [x]) as name:
x = ops.convert_to_tensor(x, name='x')
return gen_math_ops.cumprod(x, axis, exclusive=exclusive, reverse=reverse, name=name) |
@tf_export('math.conj', v1=['math.conj', 'conj'])
@dispatch.add_dispatch_support
@deprecation.deprecated_endpoints('conj')
def conj(x, name=None):
"Returns the complex conjugate of a complex number.\n\n Given a tensor `input` of complex numbers, this operation returns a tensor of\n complex numbers that are the complex conjugate of each element in `input`. The\n complex numbers in `input` must be of the form \\\\(a + bj\\\\), where *a* is the\n real part and *b* is the imaginary part.\n\n The complex conjugate returned by this operation is of the form \\\\(a - bj\\\\).\n\n For example:\n\n # tensor 'input' is [-2.25 + 4.75j, 3.25 + 5.75j]\n tf.math.conj(input) ==> [-2.25 - 4.75j, 3.25 - 5.75j]\n\n If `x` is real, it is returned unchanged.\n\n Args:\n x: `Tensor` to conjugate. Must have numeric or variant type.\n name: A name for the operation (optional).\n\n Returns:\n A `Tensor` that is the conjugate of `x` (with the same type).\n\n Raises:\n TypeError: If `x` is not a numeric tensor.\n "
if isinstance(x, ops.Tensor):
dt = x.dtype
if (dt.is_floating or dt.is_integer):
return x
with ops.name_scope(name, 'Conj', [x]) as name:
x = ops.convert_to_tensor(x, name='x')
if (x.dtype.is_complex or (x.dtype == dtypes.variant)):
return gen_math_ops.conj(x, name=name)
elif (x.dtype.is_floating or x.dtype.is_integer):
return x
else:
raise TypeError(('Expected numeric or variant tensor, got dtype %r' % x.dtype)) | 2,591,929,951,766,534,700 | Returns the complex conjugate of a complex number.
Given a tensor `input` of complex numbers, this operation returns a tensor of
complex numbers that are the complex conjugate of each element in `input`. The
complex numbers in `input` must be of the form \\(a + bj\\), where *a* is the
real part and *b* is the imaginary part.
The complex conjugate returned by this operation is of the form \\(a - bj\\).
For example:
# tensor 'input' is [-2.25 + 4.75j, 3.25 + 5.75j]
tf.math.conj(input) ==> [-2.25 - 4.75j, 3.25 - 5.75j]
If `x` is real, it is returned unchanged.
Args:
x: `Tensor` to conjugate. Must have numeric or variant type.
name: A name for the operation (optional).
Returns:
A `Tensor` that is the conjugate of `x` (with the same type).
Raises:
TypeError: If `x` is not a numeric tensor. | tensorflow/python/ops/math_ops.py | conj | minminsun/tensorflow | python | @tf_export('math.conj', v1=['math.conj', 'conj'])
@dispatch.add_dispatch_support
@deprecation.deprecated_endpoints('conj')
def conj(x, name=None):
"Returns the complex conjugate of a complex number.\n\n Given a tensor `input` of complex numbers, this operation returns a tensor of\n complex numbers that are the complex conjugate of each element in `input`. The\n complex numbers in `input` must be of the form \\\\(a + bj\\\\), where *a* is the\n real part and *b* is the imaginary part.\n\n The complex conjugate returned by this operation is of the form \\\\(a - bj\\\\).\n\n For example:\n\n # tensor 'input' is [-2.25 + 4.75j, 3.25 + 5.75j]\n tf.math.conj(input) ==> [-2.25 - 4.75j, 3.25 - 5.75j]\n\n If `x` is real, it is returned unchanged.\n\n Args:\n x: `Tensor` to conjugate. Must have numeric or variant type.\n name: A name for the operation (optional).\n\n Returns:\n A `Tensor` that is the conjugate of `x` (with the same type).\n\n Raises:\n TypeError: If `x` is not a numeric tensor.\n "
if isinstance(x, ops.Tensor):
dt = x.dtype
if (dt.is_floating or dt.is_integer):
return x
with ops.name_scope(name, 'Conj', [x]) as name:
x = ops.convert_to_tensor(x, name='x')
if (x.dtype.is_complex or (x.dtype == dtypes.variant)):
return gen_math_ops.conj(x, name=name)
elif (x.dtype.is_floating or x.dtype.is_integer):
return x
else:
raise TypeError(('Expected numeric or variant tensor, got dtype %r' % x.dtype)) |
def _BroadcastShape(op):
'Common shape function for binary operators that broadcast their inputs.'
return [common_shapes.broadcast_shape(op.inputs[0].get_shape(), op.inputs[1].get_shape())] | 7,801,190,168,870,443,000 | Common shape function for binary operators that broadcast their inputs. | tensorflow/python/ops/math_ops.py | _BroadcastShape | minminsun/tensorflow | python | def _BroadcastShape(op):
return [common_shapes.broadcast_shape(op.inputs[0].get_shape(), op.inputs[1].get_shape())] |
def reduced_shape(input_shape, axes):
'Helper function for reduction ops.\n\n Args:\n input_shape: 1-D Tensor, the shape of the Tensor being reduced.\n axes: 1-D Tensor, the reduction axes.\n Returns:\n A 1-D Tensor, the output shape as if keepdims were set to True.\n '
if context.executing_eagerly():
input_shape = input_shape.numpy()
axes = axes.numpy()
input_shape[axes] = 1
return input_shape
input_shape = cast(input_shape, dtypes.int32)
axes = cast(axes, dtypes.int32)
input_rank = array_ops.size(input_shape)
axes = ((axes + input_rank) % input_rank)
axes_shape = array_ops.shape(axes)
return gen_data_flow_ops.dynamic_stitch([range(input_rank), axes], [input_shape, array_ops.fill(axes_shape, 1)]) | -6,701,013,897,436,533,000 | Helper function for reduction ops.
Args:
input_shape: 1-D Tensor, the shape of the Tensor being reduced.
axes: 1-D Tensor, the reduction axes.
Returns:
A 1-D Tensor, the output shape as if keepdims were set to True. | tensorflow/python/ops/math_ops.py | reduced_shape | minminsun/tensorflow | python | def reduced_shape(input_shape, axes):
'Helper function for reduction ops.\n\n Args:\n input_shape: 1-D Tensor, the shape of the Tensor being reduced.\n axes: 1-D Tensor, the reduction axes.\n Returns:\n A 1-D Tensor, the output shape as if keepdims were set to True.\n '
if context.executing_eagerly():
input_shape = input_shape.numpy()
axes = axes.numpy()
input_shape[axes] = 1
return input_shape
input_shape = cast(input_shape, dtypes.int32)
axes = cast(axes, dtypes.int32)
input_rank = array_ops.size(input_shape)
axes = ((axes + input_rank) % input_rank)
axes_shape = array_ops.shape(axes)
return gen_data_flow_ops.dynamic_stitch([range(input_rank), axes], [input_shape, array_ops.fill(axes_shape, 1)]) |
def _unsorted_segment_N(data, segment_ids, num_segments):
' Helper function for unsorted_segment_mean/_sqrtN. Computes the number\n of segment entries with 0-entries set to 1 to allow division by N.\n '
segment_ids_shape = array_ops.shape_internal(segment_ids)
ones_tensor = array_ops.ones(segment_ids_shape, dtype=data.dtype)
N = gen_math_ops.unsorted_segment_sum(ones_tensor, segment_ids, num_segments)
ndims_output = (data.shape.ndims - segment_ids.shape.ndims)
broadcast_shape = ([num_segments] + ([1] * ndims_output))
N = array_ops.reshape(N, broadcast_shape)
return gen_math_ops.maximum(N, 1) | 1,557,372,864,016,889,000 | Helper function for unsorted_segment_mean/_sqrtN. Computes the number
of segment entries with 0-entries set to 1 to allow division by N. | tensorflow/python/ops/math_ops.py | _unsorted_segment_N | minminsun/tensorflow | python | def _unsorted_segment_N(data, segment_ids, num_segments):
' Helper function for unsorted_segment_mean/_sqrtN. Computes the number\n of segment entries with 0-entries set to 1 to allow division by N.\n '
segment_ids_shape = array_ops.shape_internal(segment_ids)
ones_tensor = array_ops.ones(segment_ids_shape, dtype=data.dtype)
N = gen_math_ops.unsorted_segment_sum(ones_tensor, segment_ids, num_segments)
ndims_output = (data.shape.ndims - segment_ids.shape.ndims)
broadcast_shape = ([num_segments] + ([1] * ndims_output))
N = array_ops.reshape(N, broadcast_shape)
return gen_math_ops.maximum(N, 1) |
@tf_export('math.unsorted_segment_mean', v1=['math.unsorted_segment_mean', 'unsorted_segment_mean'])
@deprecation.deprecated_endpoints('unsorted_segment_mean')
@dispatch.add_dispatch_support
def unsorted_segment_mean(data, segment_ids, num_segments, name=None):
'Computes the mean along segments of a tensor.\n\n Read [the section on\n segmentation](https://tensorflow.org/api_guides/python/math_ops#segmentation)\n for an explanation of segments.\n\n This operator is similar to the unsorted segment sum operator found\n [here](../../../api_docs/python/math_ops.md#UnsortedSegmentSum).\n Instead of computing the sum over segments, it computes the mean of all\n entries belonging to a segment such that:\n\n \\\\(output_i = 1/N_i \\sum_{j...} data[j...]\\\\) where the sum is over tuples\n `j...` such that `segment_ids[j...] == i` with \\\\N_i\\\\ being the number of\n occurrences of id \\\\i\\\\.\n\n If there is no entry for a given segment ID `i`, it outputs 0.\n\n If the given segment ID `i` is negative, the value is dropped and will not\n be added to the sum of the segment.\n\n Args:\n data: A `Tensor` with floating point or complex dtype.\n segment_ids: An integer tensor whose shape is a prefix of `data.shape`.\n num_segments: An integer scalar `Tensor`. The number of distinct\n segment IDs.\n name: A name for the operation (optional).\n\n Returns:\n A `Tensor`. Has same shape as data, except for the first `segment_ids.rank`\n dimensions, which are replaced with a single dimension which has size\n `num_segments`.\n '
with ops.name_scope(name, 'UnsortedSegmentMean'):
data = ops.convert_to_tensor(data)
segment_ids = ops.convert_to_tensor(segment_ids)
N = _unsorted_segment_N(data, segment_ids, num_segments)
summed = gen_math_ops.unsorted_segment_sum(data, segment_ids, num_segments)
return (summed / N) | 3,424,219,195,254,692,000 | Computes the mean along segments of a tensor.
Read [the section on
segmentation](https://tensorflow.org/api_guides/python/math_ops#segmentation)
for an explanation of segments.
This operator is similar to the unsorted segment sum operator found
[here](../../../api_docs/python/math_ops.md#UnsortedSegmentSum).
Instead of computing the sum over segments, it computes the mean of all
entries belonging to a segment such that:
\\(output_i = 1/N_i \sum_{j...} data[j...]\\) where the sum is over tuples
`j...` such that `segment_ids[j...] == i` with \\N_i\\ being the number of
occurrences of id \\i\\.
If there is no entry for a given segment ID `i`, it outputs 0.
If the given segment ID `i` is negative, the value is dropped and will not
be added to the sum of the segment.
Args:
data: A `Tensor` with floating point or complex dtype.
segment_ids: An integer tensor whose shape is a prefix of `data.shape`.
num_segments: An integer scalar `Tensor`. The number of distinct
segment IDs.
name: A name for the operation (optional).
Returns:
A `Tensor`. Has same shape as data, except for the first `segment_ids.rank`
dimensions, which are replaced with a single dimension which has size
`num_segments`. | tensorflow/python/ops/math_ops.py | unsorted_segment_mean | minminsun/tensorflow | python | @tf_export('math.unsorted_segment_mean', v1=['math.unsorted_segment_mean', 'unsorted_segment_mean'])
@deprecation.deprecated_endpoints('unsorted_segment_mean')
@dispatch.add_dispatch_support
def unsorted_segment_mean(data, segment_ids, num_segments, name=None):
'Computes the mean along segments of a tensor.\n\n Read [the section on\n segmentation](https://tensorflow.org/api_guides/python/math_ops#segmentation)\n for an explanation of segments.\n\n This operator is similar to the unsorted segment sum operator found\n [here](../../../api_docs/python/math_ops.md#UnsortedSegmentSum).\n Instead of computing the sum over segments, it computes the mean of all\n entries belonging to a segment such that:\n\n \\\\(output_i = 1/N_i \\sum_{j...} data[j...]\\\\) where the sum is over tuples\n `j...` such that `segment_ids[j...] == i` with \\\\N_i\\\\ being the number of\n occurrences of id \\\\i\\\\.\n\n If there is no entry for a given segment ID `i`, it outputs 0.\n\n If the given segment ID `i` is negative, the value is dropped and will not\n be added to the sum of the segment.\n\n Args:\n data: A `Tensor` with floating point or complex dtype.\n segment_ids: An integer tensor whose shape is a prefix of `data.shape`.\n num_segments: An integer scalar `Tensor`. The number of distinct\n segment IDs.\n name: A name for the operation (optional).\n\n Returns:\n A `Tensor`. Has same shape as data, except for the first `segment_ids.rank`\n dimensions, which are replaced with a single dimension which has size\n `num_segments`.\n '
with ops.name_scope(name, 'UnsortedSegmentMean'):
data = ops.convert_to_tensor(data)
segment_ids = ops.convert_to_tensor(segment_ids)
N = _unsorted_segment_N(data, segment_ids, num_segments)
summed = gen_math_ops.unsorted_segment_sum(data, segment_ids, num_segments)
return (summed / N) |
@tf_export('math.unsorted_segment_sqrt_n', v1=['math.unsorted_segment_sqrt_n', 'unsorted_segment_sqrt_n'])
@deprecation.deprecated_endpoints('unsorted_segment_sqrt_n')
@dispatch.add_dispatch_support
def unsorted_segment_sqrt_n(data, segment_ids, num_segments, name=None):
'Computes the sum along segments of a tensor divided by the sqrt(N).\n\n Read [the section on\n segmentation](https://tensorflow.org/api_guides/python/math_ops#segmentation)\n for an explanation of segments.\n\n This operator is similar to the unsorted segment sum operator found\n [here](../../../api_docs/python/math_ops.md#UnsortedSegmentSum).\n Additionally to computing the sum over segments, it divides the results by\n sqrt(N).\n\n \\\\(output_i = 1/sqrt(N_i) \\sum_{j...} data[j...]\\\\) where the sum is over\n tuples `j...` such that `segment_ids[j...] == i` with \\\\N_i\\\\ being the\n number of occurrences of id \\\\i\\\\.\n\n If there is no entry for a given segment ID `i`, it outputs 0.\n\n Note that this op only supports floating point and complex dtypes,\n due to tf.sqrt only supporting these types.\n\n If the given segment ID `i` is negative, the value is dropped and will not\n be added to the sum of the segment.\n\n Args:\n data: A `Tensor` with floating point or complex dtype.\n segment_ids: An integer tensor whose shape is a prefix of `data.shape`.\n num_segments: An integer scalar `Tensor`. The number of distinct\n segment IDs.\n name: A name for the operation (optional).\n\n Returns:\n A `Tensor`. Has same shape as data, except for the first `segment_ids.rank`\n dimensions, which are replaced with a single dimension which has size\n `num_segments`.\n '
with ops.name_scope(name, 'UnsortedSegmentSqrtN'):
data = ops.convert_to_tensor(data)
segment_ids = ops.convert_to_tensor(segment_ids)
N = _unsorted_segment_N(data, segment_ids, num_segments)
summed = gen_math_ops.unsorted_segment_sum(data, segment_ids, num_segments)
return (summed / gen_math_ops.sqrt(N)) | -8,094,678,367,791,078,000 | Computes the sum along segments of a tensor divided by the sqrt(N).
Read [the section on
segmentation](https://tensorflow.org/api_guides/python/math_ops#segmentation)
for an explanation of segments.
This operator is similar to the unsorted segment sum operator found
[here](../../../api_docs/python/math_ops.md#UnsortedSegmentSum).
Additionally to computing the sum over segments, it divides the results by
sqrt(N).
\\(output_i = 1/sqrt(N_i) \sum_{j...} data[j...]\\) where the sum is over
tuples `j...` such that `segment_ids[j...] == i` with \\N_i\\ being the
number of occurrences of id \\i\\.
If there is no entry for a given segment ID `i`, it outputs 0.
Note that this op only supports floating point and complex dtypes,
due to tf.sqrt only supporting these types.
If the given segment ID `i` is negative, the value is dropped and will not
be added to the sum of the segment.
Args:
data: A `Tensor` with floating point or complex dtype.
segment_ids: An integer tensor whose shape is a prefix of `data.shape`.
num_segments: An integer scalar `Tensor`. The number of distinct
segment IDs.
name: A name for the operation (optional).
Returns:
A `Tensor`. Has same shape as data, except for the first `segment_ids.rank`
dimensions, which are replaced with a single dimension which has size
`num_segments`. | tensorflow/python/ops/math_ops.py | unsorted_segment_sqrt_n | minminsun/tensorflow | python | @tf_export('math.unsorted_segment_sqrt_n', v1=['math.unsorted_segment_sqrt_n', 'unsorted_segment_sqrt_n'])
@deprecation.deprecated_endpoints('unsorted_segment_sqrt_n')
@dispatch.add_dispatch_support
def unsorted_segment_sqrt_n(data, segment_ids, num_segments, name=None):
'Computes the sum along segments of a tensor divided by the sqrt(N).\n\n Read [the section on\n segmentation](https://tensorflow.org/api_guides/python/math_ops#segmentation)\n for an explanation of segments.\n\n This operator is similar to the unsorted segment sum operator found\n [here](../../../api_docs/python/math_ops.md#UnsortedSegmentSum).\n Additionally to computing the sum over segments, it divides the results by\n sqrt(N).\n\n \\\\(output_i = 1/sqrt(N_i) \\sum_{j...} data[j...]\\\\) where the sum is over\n tuples `j...` such that `segment_ids[j...] == i` with \\\\N_i\\\\ being the\n number of occurrences of id \\\\i\\\\.\n\n If there is no entry for a given segment ID `i`, it outputs 0.\n\n Note that this op only supports floating point and complex dtypes,\n due to tf.sqrt only supporting these types.\n\n If the given segment ID `i` is negative, the value is dropped and will not\n be added to the sum of the segment.\n\n Args:\n data: A `Tensor` with floating point or complex dtype.\n segment_ids: An integer tensor whose shape is a prefix of `data.shape`.\n num_segments: An integer scalar `Tensor`. The number of distinct\n segment IDs.\n name: A name for the operation (optional).\n\n Returns:\n A `Tensor`. Has same shape as data, except for the first `segment_ids.rank`\n dimensions, which are replaced with a single dimension which has size\n `num_segments`.\n '
with ops.name_scope(name, 'UnsortedSegmentSqrtN'):
data = ops.convert_to_tensor(data)
segment_ids = ops.convert_to_tensor(segment_ids)
N = _unsorted_segment_N(data, segment_ids, num_segments)
summed = gen_math_ops.unsorted_segment_sum(data, segment_ids, num_segments)
return (summed / gen_math_ops.sqrt(N)) |
@tf_export(v1=['sparse.segment_sum', 'sparse_segment_sum'])
@deprecation.deprecated_endpoints('sparse_segment_sum')
def sparse_segment_sum(data, indices, segment_ids, name=None, num_segments=None):
"Computes the sum along sparse segments of a tensor.\n\n Read [the section on\n segmentation](https://tensorflow.org/api_guides/python/math_ops#Segmentation)\n for an explanation of segments.\n\n Like `SegmentSum`, but `segment_ids` can have rank less than `data`'s first\n dimension, selecting a subset of dimension 0, specified by `indices`.\n `segment_ids` is allowed to have missing ids, in which case the output will\n be zeros at those indices. In those cases `num_segments` is used to determine\n the size of the output.\n\n For example:\n\n ```python\n c = tf.constant([[1,2,3,4], [-1,-2,-3,-4], [5,6,7,8]])\n\n # Select two rows, one segment.\n tf.sparse.segment_sum(c, tf.constant([0, 1]), tf.constant([0, 0]))\n # => [[0 0 0 0]]\n\n # Select two rows, two segment.\n tf.sparse.segment_sum(c, tf.constant([0, 1]), tf.constant([0, 1]))\n # => [[ 1 2 3 4]\n # [-1 -2 -3 -4]]\n\n # With missing segment ids.\n tf.sparse.segment_sum(c, tf.constant([0, 1]), tf.constant([0, 2]),\n num_segments=4)\n # => [[ 1 2 3 4]\n # [ 0 0 0 0]\n # [-1 -2 -3 -4]\n # [ 0 0 0 0]]\n\n # Select all rows, two segments.\n tf.sparse.segment_sum(c, tf.constant([0, 1, 2]), tf.constant([0, 0, 1]))\n # => [[0 0 0 0]\n # [5 6 7 8]]\n\n # Which is equivalent to:\n tf.segment_sum(c, tf.constant([0, 0, 1]))\n ```\n\n Args:\n data: A `Tensor` with data that will be assembled in the output.\n indices: A 1-D `Tensor` with indices into `data`. Has same rank as\n `segment_ids`.\n segment_ids: A 1-D `Tensor` with indices into the output `Tensor`.\n Values should be sorted and can be repeated.\n name: A name for the operation (optional).\n num_segments: An optional int32 scalar. Indicates the size of the output\n `Tensor`.\n\n Returns:\n A `tensor` of the shape as data, except for dimension 0 which\n has size `k`, the number of segments specified via `num_segments` or\n inferred for the last element in `segments_ids`.\n "
if (num_segments is not None):
return gen_math_ops.sparse_segment_sum_with_num_segments(data=data, indices=indices, segment_ids=segment_ids, num_segments=num_segments, name=name)
else:
return gen_math_ops.sparse_segment_sum(data=data, indices=indices, segment_ids=segment_ids, name=name) | -8,370,364,508,005,443,000 | Computes the sum along sparse segments of a tensor.
Read [the section on
segmentation](https://tensorflow.org/api_guides/python/math_ops#Segmentation)
for an explanation of segments.
Like `SegmentSum`, but `segment_ids` can have rank less than `data`'s first
dimension, selecting a subset of dimension 0, specified by `indices`.
`segment_ids` is allowed to have missing ids, in which case the output will
be zeros at those indices. In those cases `num_segments` is used to determine
the size of the output.
For example:
```python
c = tf.constant([[1,2,3,4], [-1,-2,-3,-4], [5,6,7,8]])
# Select two rows, one segment.
tf.sparse.segment_sum(c, tf.constant([0, 1]), tf.constant([0, 0]))
# => [[0 0 0 0]]
# Select two rows, two segment.
tf.sparse.segment_sum(c, tf.constant([0, 1]), tf.constant([0, 1]))
# => [[ 1 2 3 4]
# [-1 -2 -3 -4]]
# With missing segment ids.
tf.sparse.segment_sum(c, tf.constant([0, 1]), tf.constant([0, 2]),
num_segments=4)
# => [[ 1 2 3 4]
# [ 0 0 0 0]
# [-1 -2 -3 -4]
# [ 0 0 0 0]]
# Select all rows, two segments.
tf.sparse.segment_sum(c, tf.constant([0, 1, 2]), tf.constant([0, 0, 1]))
# => [[0 0 0 0]
# [5 6 7 8]]
# Which is equivalent to:
tf.segment_sum(c, tf.constant([0, 0, 1]))
```
Args:
data: A `Tensor` with data that will be assembled in the output.
indices: A 1-D `Tensor` with indices into `data`. Has same rank as
`segment_ids`.
segment_ids: A 1-D `Tensor` with indices into the output `Tensor`.
Values should be sorted and can be repeated.
name: A name for the operation (optional).
num_segments: An optional int32 scalar. Indicates the size of the output
`Tensor`.
Returns:
A `tensor` of the shape as data, except for dimension 0 which
has size `k`, the number of segments specified via `num_segments` or
inferred for the last element in `segments_ids`. | tensorflow/python/ops/math_ops.py | sparse_segment_sum | minminsun/tensorflow | python | @tf_export(v1=['sparse.segment_sum', 'sparse_segment_sum'])
@deprecation.deprecated_endpoints('sparse_segment_sum')
def sparse_segment_sum(data, indices, segment_ids, name=None, num_segments=None):
"Computes the sum along sparse segments of a tensor.\n\n Read [the section on\n segmentation](https://tensorflow.org/api_guides/python/math_ops#Segmentation)\n for an explanation of segments.\n\n Like `SegmentSum`, but `segment_ids` can have rank less than `data`'s first\n dimension, selecting a subset of dimension 0, specified by `indices`.\n `segment_ids` is allowed to have missing ids, in which case the output will\n be zeros at those indices. In those cases `num_segments` is used to determine\n the size of the output.\n\n For example:\n\n ```python\n c = tf.constant([[1,2,3,4], [-1,-2,-3,-4], [5,6,7,8]])\n\n # Select two rows, one segment.\n tf.sparse.segment_sum(c, tf.constant([0, 1]), tf.constant([0, 0]))\n # => [[0 0 0 0]]\n\n # Select two rows, two segment.\n tf.sparse.segment_sum(c, tf.constant([0, 1]), tf.constant([0, 1]))\n # => [[ 1 2 3 4]\n # [-1 -2 -3 -4]]\n\n # With missing segment ids.\n tf.sparse.segment_sum(c, tf.constant([0, 1]), tf.constant([0, 2]),\n num_segments=4)\n # => [[ 1 2 3 4]\n # [ 0 0 0 0]\n # [-1 -2 -3 -4]\n # [ 0 0 0 0]]\n\n # Select all rows, two segments.\n tf.sparse.segment_sum(c, tf.constant([0, 1, 2]), tf.constant([0, 0, 1]))\n # => [[0 0 0 0]\n # [5 6 7 8]]\n\n # Which is equivalent to:\n tf.segment_sum(c, tf.constant([0, 0, 1]))\n ```\n\n Args:\n data: A `Tensor` with data that will be assembled in the output.\n indices: A 1-D `Tensor` with indices into `data`. Has same rank as\n `segment_ids`.\n segment_ids: A 1-D `Tensor` with indices into the output `Tensor`.\n Values should be sorted and can be repeated.\n name: A name for the operation (optional).\n num_segments: An optional int32 scalar. Indicates the size of the output\n `Tensor`.\n\n Returns:\n A `tensor` of the shape as data, except for dimension 0 which\n has size `k`, the number of segments specified via `num_segments` or\n inferred for the last element in `segments_ids`.\n "
if (num_segments is not None):
return gen_math_ops.sparse_segment_sum_with_num_segments(data=data, indices=indices, segment_ids=segment_ids, num_segments=num_segments, name=name)
else:
return gen_math_ops.sparse_segment_sum(data=data, indices=indices, segment_ids=segment_ids, name=name) |
@tf_export(v1=['sparse.segment_mean', 'sparse_segment_mean'])
@deprecation.deprecated_endpoints('sparse_segment_mean')
def sparse_segment_mean(data, indices, segment_ids, name=None, num_segments=None):
"Computes the mean along sparse segments of a tensor.\n\n Read [the section on\n segmentation](https://tensorflow.org/api_guides/python/math_ops#Segmentation)\n for an explanation of segments.\n\n Like `SegmentMean`, but `segment_ids` can have rank less than `data`'s first\n dimension, selecting a subset of dimension 0, specified by `indices`.\n `segment_ids` is allowed to have missing ids, in which case the output will\n be zeros at those indices. In those cases `num_segments` is used to determine\n the size of the output.\n\n Args:\n data: A `Tensor` with data that will be assembled in the output.\n indices: A 1-D `Tensor` with indices into `data`. Has same rank as\n `segment_ids`.\n segment_ids: A 1-D `Tensor` with indices into the output `Tensor`.\n Values should be sorted and can be repeated.\n name: A name for the operation (optional).\n num_segments: An optional int32 scalar. Indicates the size of the output\n `Tensor`.\n\n Returns:\n A `tensor` of the shape as data, except for dimension 0 which\n has size `k`, the number of segments specified via `num_segments` or\n inferred for the last element in `segments_ids`.\n "
if (num_segments is not None):
return gen_math_ops.sparse_segment_mean_with_num_segments(data=data, indices=indices, segment_ids=segment_ids, num_segments=num_segments, name=name)
else:
return gen_math_ops.sparse_segment_mean(data=data, indices=indices, segment_ids=segment_ids, name=name) | 6,740,956,599,249,067,000 | Computes the mean along sparse segments of a tensor.
Read [the section on
segmentation](https://tensorflow.org/api_guides/python/math_ops#Segmentation)
for an explanation of segments.
Like `SegmentMean`, but `segment_ids` can have rank less than `data`'s first
dimension, selecting a subset of dimension 0, specified by `indices`.
`segment_ids` is allowed to have missing ids, in which case the output will
be zeros at those indices. In those cases `num_segments` is used to determine
the size of the output.
Args:
data: A `Tensor` with data that will be assembled in the output.
indices: A 1-D `Tensor` with indices into `data`. Has same rank as
`segment_ids`.
segment_ids: A 1-D `Tensor` with indices into the output `Tensor`.
Values should be sorted and can be repeated.
name: A name for the operation (optional).
num_segments: An optional int32 scalar. Indicates the size of the output
`Tensor`.
Returns:
A `tensor` of the shape as data, except for dimension 0 which
has size `k`, the number of segments specified via `num_segments` or
inferred for the last element in `segments_ids`. | tensorflow/python/ops/math_ops.py | sparse_segment_mean | minminsun/tensorflow | python | @tf_export(v1=['sparse.segment_mean', 'sparse_segment_mean'])
@deprecation.deprecated_endpoints('sparse_segment_mean')
def sparse_segment_mean(data, indices, segment_ids, name=None, num_segments=None):
"Computes the mean along sparse segments of a tensor.\n\n Read [the section on\n segmentation](https://tensorflow.org/api_guides/python/math_ops#Segmentation)\n for an explanation of segments.\n\n Like `SegmentMean`, but `segment_ids` can have rank less than `data`'s first\n dimension, selecting a subset of dimension 0, specified by `indices`.\n `segment_ids` is allowed to have missing ids, in which case the output will\n be zeros at those indices. In those cases `num_segments` is used to determine\n the size of the output.\n\n Args:\n data: A `Tensor` with data that will be assembled in the output.\n indices: A 1-D `Tensor` with indices into `data`. Has same rank as\n `segment_ids`.\n segment_ids: A 1-D `Tensor` with indices into the output `Tensor`.\n Values should be sorted and can be repeated.\n name: A name for the operation (optional).\n num_segments: An optional int32 scalar. Indicates the size of the output\n `Tensor`.\n\n Returns:\n A `tensor` of the shape as data, except for dimension 0 which\n has size `k`, the number of segments specified via `num_segments` or\n inferred for the last element in `segments_ids`.\n "
if (num_segments is not None):
return gen_math_ops.sparse_segment_mean_with_num_segments(data=data, indices=indices, segment_ids=segment_ids, num_segments=num_segments, name=name)
else:
return gen_math_ops.sparse_segment_mean(data=data, indices=indices, segment_ids=segment_ids, name=name) |
@tf_export('sparse.segment_mean', v1=[])
def sparse_segment_mean_v2(data, indices, segment_ids, num_segments=None, name=None):
"Computes the mean along sparse segments of a tensor.\n\n Read [the section on\n segmentation](https://tensorflow.org/api_guides/python/math_ops#Segmentation)\n for an explanation of segments.\n\n Like `SegmentMean`, but `segment_ids` can have rank less than `data`'s first\n dimension, selecting a subset of dimension 0, specified by `indices`.\n `segment_ids` is allowed to have missing ids, in which case the output will\n be zeros at those indices. In those cases `num_segments` is used to determine\n the size of the output.\n\n Args:\n data: A `Tensor` with data that will be assembled in the output.\n indices: A 1-D `Tensor` with indices into `data`. Has same rank as\n `segment_ids`.\n segment_ids: A 1-D `Tensor` with indices into the output `Tensor`. Values\n should be sorted and can be repeated.\n num_segments: An optional int32 scalar. Indicates the size of the output\n `Tensor`.\n name: A name for the operation (optional).\n\n Returns:\n A `tensor` of the shape as data, except for dimension 0 which\n has size `k`, the number of segments specified via `num_segments` or\n inferred for the last element in `segments_ids`.\n "
return sparse_segment_mean(data, indices, segment_ids, name=name, num_segments=num_segments) | -4,683,962,204,175,395,000 | Computes the mean along sparse segments of a tensor.
Read [the section on
segmentation](https://tensorflow.org/api_guides/python/math_ops#Segmentation)
for an explanation of segments.
Like `SegmentMean`, but `segment_ids` can have rank less than `data`'s first
dimension, selecting a subset of dimension 0, specified by `indices`.
`segment_ids` is allowed to have missing ids, in which case the output will
be zeros at those indices. In those cases `num_segments` is used to determine
the size of the output.
Args:
data: A `Tensor` with data that will be assembled in the output.
indices: A 1-D `Tensor` with indices into `data`. Has same rank as
`segment_ids`.
segment_ids: A 1-D `Tensor` with indices into the output `Tensor`. Values
should be sorted and can be repeated.
num_segments: An optional int32 scalar. Indicates the size of the output
`Tensor`.
name: A name for the operation (optional).
Returns:
A `tensor` of the shape as data, except for dimension 0 which
has size `k`, the number of segments specified via `num_segments` or
inferred for the last element in `segments_ids`. | tensorflow/python/ops/math_ops.py | sparse_segment_mean_v2 | minminsun/tensorflow | python | @tf_export('sparse.segment_mean', v1=[])
def sparse_segment_mean_v2(data, indices, segment_ids, num_segments=None, name=None):
"Computes the mean along sparse segments of a tensor.\n\n Read [the section on\n segmentation](https://tensorflow.org/api_guides/python/math_ops#Segmentation)\n for an explanation of segments.\n\n Like `SegmentMean`, but `segment_ids` can have rank less than `data`'s first\n dimension, selecting a subset of dimension 0, specified by `indices`.\n `segment_ids` is allowed to have missing ids, in which case the output will\n be zeros at those indices. In those cases `num_segments` is used to determine\n the size of the output.\n\n Args:\n data: A `Tensor` with data that will be assembled in the output.\n indices: A 1-D `Tensor` with indices into `data`. Has same rank as\n `segment_ids`.\n segment_ids: A 1-D `Tensor` with indices into the output `Tensor`. Values\n should be sorted and can be repeated.\n num_segments: An optional int32 scalar. Indicates the size of the output\n `Tensor`.\n name: A name for the operation (optional).\n\n Returns:\n A `tensor` of the shape as data, except for dimension 0 which\n has size `k`, the number of segments specified via `num_segments` or\n inferred for the last element in `segments_ids`.\n "
return sparse_segment_mean(data, indices, segment_ids, name=name, num_segments=num_segments) |
@tf_export(v1=['sparse.segment_sqrt_n', 'sparse_segment_sqrt_n'])
@deprecation.deprecated_endpoints('sparse_segment_sqrt_n')
def sparse_segment_sqrt_n(data, indices, segment_ids, name=None, num_segments=None):
'Computes the sum along sparse segments of a tensor divided by the sqrt(N).\n\n `N` is the size of the segment being reduced.\n\n Args:\n data: A `Tensor` with data that will be assembled in the output.\n indices: A 1-D `Tensor` with indices into `data`. Has same rank as\n `segment_ids`.\n segment_ids: A 1-D `Tensor` with indices into the output `Tensor`.\n Values should be sorted and can be repeated.\n name: A name for the operation (optional).\n num_segments: An optional int32 scalar. Indicates the size of the output\n `Tensor`.\n\n Returns:\n A `tensor` of the shape as data, except for dimension 0 which\n has size `k`, the number of segments specified via `num_segments` or\n inferred for the last element in `segments_ids`.\n '
if (num_segments is not None):
return gen_math_ops.sparse_segment_sqrt_n_with_num_segments(data=data, indices=indices, segment_ids=segment_ids, num_segments=num_segments, name=name)
else:
return gen_math_ops.sparse_segment_sqrt_n(data=data, indices=indices, segment_ids=segment_ids, name=name) | 6,518,435,009,501,153,000 | Computes the sum along sparse segments of a tensor divided by the sqrt(N).
`N` is the size of the segment being reduced.
Args:
data: A `Tensor` with data that will be assembled in the output.
indices: A 1-D `Tensor` with indices into `data`. Has same rank as
`segment_ids`.
segment_ids: A 1-D `Tensor` with indices into the output `Tensor`.
Values should be sorted and can be repeated.
name: A name for the operation (optional).
num_segments: An optional int32 scalar. Indicates the size of the output
`Tensor`.
Returns:
A `tensor` of the shape as data, except for dimension 0 which
has size `k`, the number of segments specified via `num_segments` or
inferred for the last element in `segments_ids`. | tensorflow/python/ops/math_ops.py | sparse_segment_sqrt_n | minminsun/tensorflow | python | @tf_export(v1=['sparse.segment_sqrt_n', 'sparse_segment_sqrt_n'])
@deprecation.deprecated_endpoints('sparse_segment_sqrt_n')
def sparse_segment_sqrt_n(data, indices, segment_ids, name=None, num_segments=None):
'Computes the sum along sparse segments of a tensor divided by the sqrt(N).\n\n `N` is the size of the segment being reduced.\n\n Args:\n data: A `Tensor` with data that will be assembled in the output.\n indices: A 1-D `Tensor` with indices into `data`. Has same rank as\n `segment_ids`.\n segment_ids: A 1-D `Tensor` with indices into the output `Tensor`.\n Values should be sorted and can be repeated.\n name: A name for the operation (optional).\n num_segments: An optional int32 scalar. Indicates the size of the output\n `Tensor`.\n\n Returns:\n A `tensor` of the shape as data, except for dimension 0 which\n has size `k`, the number of segments specified via `num_segments` or\n inferred for the last element in `segments_ids`.\n '
if (num_segments is not None):
return gen_math_ops.sparse_segment_sqrt_n_with_num_segments(data=data, indices=indices, segment_ids=segment_ids, num_segments=num_segments, name=name)
else:
return gen_math_ops.sparse_segment_sqrt_n(data=data, indices=indices, segment_ids=segment_ids, name=name) |
@tf_export('sparse.segment_sqrt_n', v1=[])
def sparse_segment_sqrt_n_v2(data, indices, segment_ids, num_segments=None, name=None):
'Computes the sum along sparse segments of a tensor divided by the sqrt(N).\n\n `N` is the size of the segment being reduced.\n\n Args:\n data: A `Tensor` with data that will be assembled in the output.\n indices: A 1-D `Tensor` with indices into `data`. Has same rank as\n `segment_ids`.\n segment_ids: A 1-D `Tensor` with indices into the output `Tensor`. Values\n should be sorted and can be repeated.\n num_segments: An optional int32 scalar. Indicates the size of the output\n `Tensor`.\n name: A name for the operation (optional).\n\n Returns:\n A `tensor` of the shape as data, except for dimension 0 which\n has size `k`, the number of segments specified via `num_segments` or\n inferred for the last element in `segments_ids`.\n '
return sparse_segment_sqrt_n(data, indices, segment_ids, name=name, num_segments=num_segments) | -5,794,129,291,528,013,000 | Computes the sum along sparse segments of a tensor divided by the sqrt(N).
`N` is the size of the segment being reduced.
Args:
data: A `Tensor` with data that will be assembled in the output.
indices: A 1-D `Tensor` with indices into `data`. Has same rank as
`segment_ids`.
segment_ids: A 1-D `Tensor` with indices into the output `Tensor`. Values
should be sorted and can be repeated.
num_segments: An optional int32 scalar. Indicates the size of the output
`Tensor`.
name: A name for the operation (optional).
Returns:
A `tensor` of the shape as data, except for dimension 0 which
has size `k`, the number of segments specified via `num_segments` or
inferred for the last element in `segments_ids`. | tensorflow/python/ops/math_ops.py | sparse_segment_sqrt_n_v2 | minminsun/tensorflow | python | @tf_export('sparse.segment_sqrt_n', v1=[])
def sparse_segment_sqrt_n_v2(data, indices, segment_ids, num_segments=None, name=None):
'Computes the sum along sparse segments of a tensor divided by the sqrt(N).\n\n `N` is the size of the segment being reduced.\n\n Args:\n data: A `Tensor` with data that will be assembled in the output.\n indices: A 1-D `Tensor` with indices into `data`. Has same rank as\n `segment_ids`.\n segment_ids: A 1-D `Tensor` with indices into the output `Tensor`. Values\n should be sorted and can be repeated.\n num_segments: An optional int32 scalar. Indicates the size of the output\n `Tensor`.\n name: A name for the operation (optional).\n\n Returns:\n A `tensor` of the shape as data, except for dimension 0 which\n has size `k`, the number of segments specified via `num_segments` or\n inferred for the last element in `segments_ids`.\n '
return sparse_segment_sqrt_n(data, indices, segment_ids, name=name, num_segments=num_segments) |
@tf_export('tensordot', 'linalg.tensordot')
def tensordot(a, b, axes, name=None):
'Tensor contraction of a and b along specified axes.\n\n Tensordot (also known as tensor contraction) sums the product of elements\n from `a` and `b` over the indices specified by `a_axes` and `b_axes`.\n The lists `a_axes` and `b_axes` specify those pairs of axes along which to\n contract the tensors. The axis `a_axes[i]` of `a` must have the same dimension\n as axis `b_axes[i]` of `b` for all `i` in `range(0, len(a_axes))`. The lists\n `a_axes` and `b_axes` must have identical length and consist of unique\n integers that specify valid axes for each of the tensors.\n\n This operation corresponds to `numpy.tensordot(a, b, axes)`.\n\n Example 1: When `a` and `b` are matrices (order 2), the case `axes = 1`\n is equivalent to matrix multiplication.\n\n Example 2: When `a` and `b` are matrices (order 2), the case\n `axes = [[1], [0]]` is equivalent to matrix multiplication.\n\n Example 3: Suppose that \\\\(a_{ijk}\\\\) and \\\\(b_{lmn}\\\\) represent two\n tensors of order 3. Then, `contract(a, b, [[0], [2]])` is the order 4 tensor\n \\\\(c_{jklm}\\\\) whose entry\n corresponding to the indices \\\\((j,k,l,m)\\\\) is given by:\n\n \\\\( c_{jklm} = \\sum_i a_{ijk} b_{lmi} \\\\).\n\n In general, `order(c) = order(a) + order(b) - 2*len(axes[0])`.\n\n Args:\n a: `Tensor` of type `float32` or `float64`.\n b: `Tensor` with the same type as `a`.\n axes: Either a scalar `N`, or a list or an `int32` `Tensor` of shape [2, k].\n If axes is a scalar, sum over the last N axes of a and the first N axes of\n b in order. If axes is a list or `Tensor` the first and second row contain\n the set of unique integers specifying axes along which the contraction is\n computed, for `a` and `b`, respectively. The number of axes for `a` and\n `b` must be equal.\n name: A name for the operation (optional).\n\n Returns:\n A `Tensor` with the same type as `a`.\n\n Raises:\n ValueError: If the shapes of `a`, `b`, and `axes` are incompatible.\n IndexError: If the values in axes exceed the rank of the corresponding\n tensor.\n '
def _tensordot_reshape(a, axes, flipped=False):
'Helper method to perform transpose and reshape for contraction op.\n\n This method is helpful in reducing `math_ops.tensordot` to `math_ops.matmul`\n using `array_ops.transpose` and `array_ops.reshape`. The method takes a\n tensor and performs the correct transpose and reshape operation for a given\n set of indices. It returns the reshaped tensor as well as a list of indices\n necessary to reshape the tensor again after matrix multiplication.\n\n Args:\n a: `Tensor`.\n axes: List or `int32` `Tensor` of unique indices specifying valid axes of\n `a`.\n flipped: An optional `bool`. Defaults to `False`. If `True`, the method\n assumes that `a` is the second argument in the contraction operation.\n\n Returns:\n A tuple `(reshaped_a, free_dims, free_dims_static)` where `reshaped_a` is\n the tensor `a` reshaped to allow contraction via `matmul`, `free_dims` is\n either a list of integers or an `int32` `Tensor`, depending on whether\n the shape of a is fully specified, and free_dims_static is either a list\n of integers and None values, or None, representing the inferred\n static shape of the free dimensions\n '
if (a.get_shape().is_fully_defined() and isinstance(axes, (list, tuple))):
shape_a = a.get_shape().as_list()
axes = [(i if (i >= 0) else (i + len(shape_a))) for i in axes]
free = [i for i in xrange(len(shape_a)) if (i not in axes)]
free_dims = [shape_a[i] for i in free]
prod_free = int(np.prod([shape_a[i] for i in free]))
prod_axes = int(np.prod([shape_a[i] for i in axes]))
perm = ((list(axes) + free) if flipped else (free + list(axes)))
new_shape = ([prod_axes, prod_free] if flipped else [prod_free, prod_axes])
reshaped_a = array_ops.reshape(array_ops.transpose(a, perm), new_shape)
return (reshaped_a, free_dims, free_dims)
else:
if ((a.get_shape().ndims is not None) and isinstance(axes, (list, tuple))):
shape_a = a.get_shape().as_list()
axes = [(i if (i >= 0) else (i + len(shape_a))) for i in axes]
free = [i for i in xrange(len(shape_a)) if (i not in axes)]
axes_dims = [shape_a[i] for i in axes]
free_dims = [shape_a[i] for i in free]
free_dims_static = free_dims
axes = ops.convert_to_tensor(axes, dtype=dtypes.int32, name='axes')
free = ops.convert_to_tensor(free, dtype=dtypes.int32, name='free')
shape_a = array_ops.shape(a)
else:
free_dims_static = None
shape_a = array_ops.shape(a)
rank_a = array_ops.rank(a)
axes = ops.convert_to_tensor(axes, dtype=dtypes.int32, name='axes')
axes = array_ops.where((axes >= 0), axes, (axes + rank_a))
(free, _) = array_ops.setdiff1d(range(rank_a), axes)
free_dims = array_ops.gather(shape_a, free)
axes_dims = array_ops.gather(shape_a, axes)
prod_free_dims = reduce_prod(free_dims)
prod_axes_dims = reduce_prod(axes_dims)
if flipped:
perm = array_ops.concat([axes, free], 0)
new_shape = array_ops.stack([prod_axes_dims, prod_free_dims])
else:
perm = array_ops.concat([free, axes], 0)
new_shape = array_ops.stack([prod_free_dims, prod_axes_dims])
reshaped_a = array_ops.reshape(array_ops.transpose(a, perm), new_shape)
return (reshaped_a, free_dims, free_dims_static)
def _tensordot_axes(a, axes):
'Generates two sets of contraction axes for the two tensor arguments.'
a_shape = a.get_shape()
if isinstance(axes, compat.integral_types):
if (axes < 0):
raise ValueError("'axes' must be at least 0.")
if (a_shape.ndims is not None):
if (axes > a_shape.ndims):
raise ValueError(("'axes' must not be larger than the number of dimensions of tensor %s." % a))
return (list(xrange((a_shape.ndims - axes), a_shape.ndims)), list(xrange(axes)))
else:
rank = array_ops.rank(a)
return (range((rank - axes), rank, dtype=dtypes.int32), range(axes, dtype=dtypes.int32))
elif isinstance(axes, (list, tuple)):
if (len(axes) != 2):
raise ValueError("'axes' must be an integer or have length 2.")
a_axes = axes[0]
b_axes = axes[1]
if (isinstance(a_axes, compat.integral_types) and isinstance(b_axes, compat.integral_types)):
a_axes = [a_axes]
b_axes = [b_axes]
if (len(a_axes) != len(b_axes)):
raise ValueError(("Different number of contraction axes 'a' and 'b', %s != %s." % (len(a_axes), len(b_axes))))
return (a_axes, b_axes)
else:
axes = ops.convert_to_tensor(axes, name='axes', dtype=dtypes.int32)
return (axes[0], axes[1])
with ops.name_scope(name, 'Tensordot', [a, b, axes]) as name:
a = ops.convert_to_tensor(a, name='a')
b = ops.convert_to_tensor(b, name='b')
(a_axes, b_axes) = _tensordot_axes(a, axes)
(a_reshape, a_free_dims, a_free_dims_static) = _tensordot_reshape(a, a_axes)
(b_reshape, b_free_dims, b_free_dims_static) = _tensordot_reshape(b, b_axes, True)
ab_matmul = matmul(a_reshape, b_reshape)
if (isinstance(a_free_dims, list) and isinstance(b_free_dims, list)):
return array_ops.reshape(ab_matmul, (a_free_dims + b_free_dims), name=name)
else:
a_free_dims = ops.convert_to_tensor(a_free_dims, dtype=dtypes.int32)
b_free_dims = ops.convert_to_tensor(b_free_dims, dtype=dtypes.int32)
product = array_ops.reshape(ab_matmul, array_ops.concat([a_free_dims, b_free_dims], 0), name=name)
if ((a_free_dims_static is not None) and (b_free_dims_static is not None)):
product.set_shape((a_free_dims_static + b_free_dims_static))
return product | -722,363,931,524,994,300 | Tensor contraction of a and b along specified axes.
Tensordot (also known as tensor contraction) sums the product of elements
from `a` and `b` over the indices specified by `a_axes` and `b_axes`.
The lists `a_axes` and `b_axes` specify those pairs of axes along which to
contract the tensors. The axis `a_axes[i]` of `a` must have the same dimension
as axis `b_axes[i]` of `b` for all `i` in `range(0, len(a_axes))`. The lists
`a_axes` and `b_axes` must have identical length and consist of unique
integers that specify valid axes for each of the tensors.
This operation corresponds to `numpy.tensordot(a, b, axes)`.
Example 1: When `a` and `b` are matrices (order 2), the case `axes = 1`
is equivalent to matrix multiplication.
Example 2: When `a` and `b` are matrices (order 2), the case
`axes = [[1], [0]]` is equivalent to matrix multiplication.
Example 3: Suppose that \\(a_{ijk}\\) and \\(b_{lmn}\\) represent two
tensors of order 3. Then, `contract(a, b, [[0], [2]])` is the order 4 tensor
\\(c_{jklm}\\) whose entry
corresponding to the indices \\((j,k,l,m)\\) is given by:
\\( c_{jklm} = \sum_i a_{ijk} b_{lmi} \\).
In general, `order(c) = order(a) + order(b) - 2*len(axes[0])`.
Args:
a: `Tensor` of type `float32` or `float64`.
b: `Tensor` with the same type as `a`.
axes: Either a scalar `N`, or a list or an `int32` `Tensor` of shape [2, k].
If axes is a scalar, sum over the last N axes of a and the first N axes of
b in order. If axes is a list or `Tensor` the first and second row contain
the set of unique integers specifying axes along which the contraction is
computed, for `a` and `b`, respectively. The number of axes for `a` and
`b` must be equal.
name: A name for the operation (optional).
Returns:
A `Tensor` with the same type as `a`.
Raises:
ValueError: If the shapes of `a`, `b`, and `axes` are incompatible.
IndexError: If the values in axes exceed the rank of the corresponding
tensor. | tensorflow/python/ops/math_ops.py | tensordot | minminsun/tensorflow | python | @tf_export('tensordot', 'linalg.tensordot')
def tensordot(a, b, axes, name=None):
'Tensor contraction of a and b along specified axes.\n\n Tensordot (also known as tensor contraction) sums the product of elements\n from `a` and `b` over the indices specified by `a_axes` and `b_axes`.\n The lists `a_axes` and `b_axes` specify those pairs of axes along which to\n contract the tensors. The axis `a_axes[i]` of `a` must have the same dimension\n as axis `b_axes[i]` of `b` for all `i` in `range(0, len(a_axes))`. The lists\n `a_axes` and `b_axes` must have identical length and consist of unique\n integers that specify valid axes for each of the tensors.\n\n This operation corresponds to `numpy.tensordot(a, b, axes)`.\n\n Example 1: When `a` and `b` are matrices (order 2), the case `axes = 1`\n is equivalent to matrix multiplication.\n\n Example 2: When `a` and `b` are matrices (order 2), the case\n `axes = [[1], [0]]` is equivalent to matrix multiplication.\n\n Example 3: Suppose that \\\\(a_{ijk}\\\\) and \\\\(b_{lmn}\\\\) represent two\n tensors of order 3. Then, `contract(a, b, [[0], [2]])` is the order 4 tensor\n \\\\(c_{jklm}\\\\) whose entry\n corresponding to the indices \\\\((j,k,l,m)\\\\) is given by:\n\n \\\\( c_{jklm} = \\sum_i a_{ijk} b_{lmi} \\\\).\n\n In general, `order(c) = order(a) + order(b) - 2*len(axes[0])`.\n\n Args:\n a: `Tensor` of type `float32` or `float64`.\n b: `Tensor` with the same type as `a`.\n axes: Either a scalar `N`, or a list or an `int32` `Tensor` of shape [2, k].\n If axes is a scalar, sum over the last N axes of a and the first N axes of\n b in order. If axes is a list or `Tensor` the first and second row contain\n the set of unique integers specifying axes along which the contraction is\n computed, for `a` and `b`, respectively. The number of axes for `a` and\n `b` must be equal.\n name: A name for the operation (optional).\n\n Returns:\n A `Tensor` with the same type as `a`.\n\n Raises:\n ValueError: If the shapes of `a`, `b`, and `axes` are incompatible.\n IndexError: If the values in axes exceed the rank of the corresponding\n tensor.\n '
def _tensordot_reshape(a, axes, flipped=False):
'Helper method to perform transpose and reshape for contraction op.\n\n This method is helpful in reducing `math_ops.tensordot` to `math_ops.matmul`\n using `array_ops.transpose` and `array_ops.reshape`. The method takes a\n tensor and performs the correct transpose and reshape operation for a given\n set of indices. It returns the reshaped tensor as well as a list of indices\n necessary to reshape the tensor again after matrix multiplication.\n\n Args:\n a: `Tensor`.\n axes: List or `int32` `Tensor` of unique indices specifying valid axes of\n `a`.\n flipped: An optional `bool`. Defaults to `False`. If `True`, the method\n assumes that `a` is the second argument in the contraction operation.\n\n Returns:\n A tuple `(reshaped_a, free_dims, free_dims_static)` where `reshaped_a` is\n the tensor `a` reshaped to allow contraction via `matmul`, `free_dims` is\n either a list of integers or an `int32` `Tensor`, depending on whether\n the shape of a is fully specified, and free_dims_static is either a list\n of integers and None values, or None, representing the inferred\n static shape of the free dimensions\n '
if (a.get_shape().is_fully_defined() and isinstance(axes, (list, tuple))):
shape_a = a.get_shape().as_list()
axes = [(i if (i >= 0) else (i + len(shape_a))) for i in axes]
free = [i for i in xrange(len(shape_a)) if (i not in axes)]
free_dims = [shape_a[i] for i in free]
prod_free = int(np.prod([shape_a[i] for i in free]))
prod_axes = int(np.prod([shape_a[i] for i in axes]))
perm = ((list(axes) + free) if flipped else (free + list(axes)))
new_shape = ([prod_axes, prod_free] if flipped else [prod_free, prod_axes])
reshaped_a = array_ops.reshape(array_ops.transpose(a, perm), new_shape)
return (reshaped_a, free_dims, free_dims)
else:
if ((a.get_shape().ndims is not None) and isinstance(axes, (list, tuple))):
shape_a = a.get_shape().as_list()
axes = [(i if (i >= 0) else (i + len(shape_a))) for i in axes]
free = [i for i in xrange(len(shape_a)) if (i not in axes)]
axes_dims = [shape_a[i] for i in axes]
free_dims = [shape_a[i] for i in free]
free_dims_static = free_dims
axes = ops.convert_to_tensor(axes, dtype=dtypes.int32, name='axes')
free = ops.convert_to_tensor(free, dtype=dtypes.int32, name='free')
shape_a = array_ops.shape(a)
else:
free_dims_static = None
shape_a = array_ops.shape(a)
rank_a = array_ops.rank(a)
axes = ops.convert_to_tensor(axes, dtype=dtypes.int32, name='axes')
axes = array_ops.where((axes >= 0), axes, (axes + rank_a))
(free, _) = array_ops.setdiff1d(range(rank_a), axes)
free_dims = array_ops.gather(shape_a, free)
axes_dims = array_ops.gather(shape_a, axes)
prod_free_dims = reduce_prod(free_dims)
prod_axes_dims = reduce_prod(axes_dims)
if flipped:
perm = array_ops.concat([axes, free], 0)
new_shape = array_ops.stack([prod_axes_dims, prod_free_dims])
else:
perm = array_ops.concat([free, axes], 0)
new_shape = array_ops.stack([prod_free_dims, prod_axes_dims])
reshaped_a = array_ops.reshape(array_ops.transpose(a, perm), new_shape)
return (reshaped_a, free_dims, free_dims_static)
def _tensordot_axes(a, axes):
'Generates two sets of contraction axes for the two tensor arguments.'
a_shape = a.get_shape()
if isinstance(axes, compat.integral_types):
if (axes < 0):
raise ValueError("'axes' must be at least 0.")
if (a_shape.ndims is not None):
if (axes > a_shape.ndims):
raise ValueError(("'axes' must not be larger than the number of dimensions of tensor %s." % a))
return (list(xrange((a_shape.ndims - axes), a_shape.ndims)), list(xrange(axes)))
else:
rank = array_ops.rank(a)
return (range((rank - axes), rank, dtype=dtypes.int32), range(axes, dtype=dtypes.int32))
elif isinstance(axes, (list, tuple)):
if (len(axes) != 2):
raise ValueError("'axes' must be an integer or have length 2.")
a_axes = axes[0]
b_axes = axes[1]
if (isinstance(a_axes, compat.integral_types) and isinstance(b_axes, compat.integral_types)):
a_axes = [a_axes]
b_axes = [b_axes]
if (len(a_axes) != len(b_axes)):
raise ValueError(("Different number of contraction axes 'a' and 'b', %s != %s." % (len(a_axes), len(b_axes))))
return (a_axes, b_axes)
else:
axes = ops.convert_to_tensor(axes, name='axes', dtype=dtypes.int32)
return (axes[0], axes[1])
with ops.name_scope(name, 'Tensordot', [a, b, axes]) as name:
a = ops.convert_to_tensor(a, name='a')
b = ops.convert_to_tensor(b, name='b')
(a_axes, b_axes) = _tensordot_axes(a, axes)
(a_reshape, a_free_dims, a_free_dims_static) = _tensordot_reshape(a, a_axes)
(b_reshape, b_free_dims, b_free_dims_static) = _tensordot_reshape(b, b_axes, True)
ab_matmul = matmul(a_reshape, b_reshape)
if (isinstance(a_free_dims, list) and isinstance(b_free_dims, list)):
return array_ops.reshape(ab_matmul, (a_free_dims + b_free_dims), name=name)
else:
a_free_dims = ops.convert_to_tensor(a_free_dims, dtype=dtypes.int32)
b_free_dims = ops.convert_to_tensor(b_free_dims, dtype=dtypes.int32)
product = array_ops.reshape(ab_matmul, array_ops.concat([a_free_dims, b_free_dims], 0), name=name)
if ((a_free_dims_static is not None) and (b_free_dims_static is not None)):
product.set_shape((a_free_dims_static + b_free_dims_static))
return product |
@tf_export('math.polyval')
def polyval(coeffs, x, name=None):
"Computes the elementwise value of a polynomial.\n\n If `x` is a tensor and `coeffs` is a list n + 1 tensors, this function returns\n the value of the n-th order polynomial\n\n p(x) = coeffs[n-1] + coeffs[n-2] * x + ... + coeffs[0] * x**(n-1)\n\n evaluated using Horner's method, i.e.\n\n p(x) = coeffs[n-1] + x * (coeffs[n-2] + ... + x * (coeffs[1] +\n x * coeffs[0]))\n\n Args:\n coeffs: A list of `Tensor` representing the coefficients of the polynomial.\n x: A `Tensor` representing the variable of the polynomial.\n name: A name for the operation (optional).\n\n Returns:\n A `tensor` of the shape as the expression p(x) with usual broadcasting rules\n for element-wise addition and multiplication applied.\n\n @compatibility(numpy)\n Equivalent to numpy.polyval.\n @end_compatibility\n "
with ops.name_scope(name, 'polyval', (nest.flatten(coeffs) + [x])) as name:
x = ops.convert_to_tensor(x, name='x')
if (len(coeffs) < 1):
return array_ops.zeros_like(x, name=name)
coeffs = [ops.convert_to_tensor(coeff, name=('coeff_%d' % index)) for (index, coeff) in enumerate(coeffs)]
p = coeffs[0]
for c in coeffs[1:]:
p = (c + (p * x))
return p | -3,919,992,842,877,895,000 | Computes the elementwise value of a polynomial.
If `x` is a tensor and `coeffs` is a list n + 1 tensors, this function returns
the value of the n-th order polynomial
p(x) = coeffs[n-1] + coeffs[n-2] * x + ... + coeffs[0] * x**(n-1)
evaluated using Horner's method, i.e.
p(x) = coeffs[n-1] + x * (coeffs[n-2] + ... + x * (coeffs[1] +
x * coeffs[0]))
Args:
coeffs: A list of `Tensor` representing the coefficients of the polynomial.
x: A `Tensor` representing the variable of the polynomial.
name: A name for the operation (optional).
Returns:
A `tensor` of the shape as the expression p(x) with usual broadcasting rules
for element-wise addition and multiplication applied.
@compatibility(numpy)
Equivalent to numpy.polyval.
@end_compatibility | tensorflow/python/ops/math_ops.py | polyval | minminsun/tensorflow | python | @tf_export('math.polyval')
def polyval(coeffs, x, name=None):
"Computes the elementwise value of a polynomial.\n\n If `x` is a tensor and `coeffs` is a list n + 1 tensors, this function returns\n the value of the n-th order polynomial\n\n p(x) = coeffs[n-1] + coeffs[n-2] * x + ... + coeffs[0] * x**(n-1)\n\n evaluated using Horner's method, i.e.\n\n p(x) = coeffs[n-1] + x * (coeffs[n-2] + ... + x * (coeffs[1] +\n x * coeffs[0]))\n\n Args:\n coeffs: A list of `Tensor` representing the coefficients of the polynomial.\n x: A `Tensor` representing the variable of the polynomial.\n name: A name for the operation (optional).\n\n Returns:\n A `tensor` of the shape as the expression p(x) with usual broadcasting rules\n for element-wise addition and multiplication applied.\n\n @compatibility(numpy)\n Equivalent to numpy.polyval.\n @end_compatibility\n "
with ops.name_scope(name, 'polyval', (nest.flatten(coeffs) + [x])) as name:
x = ops.convert_to_tensor(x, name='x')
if (len(coeffs) < 1):
return array_ops.zeros_like(x, name=name)
coeffs = [ops.convert_to_tensor(coeff, name=('coeff_%d' % index)) for (index, coeff) in enumerate(coeffs)]
p = coeffs[0]
for c in coeffs[1:]:
p = (c + (p * x))
return p |
def __init__(self, x, name):
'Construct DivideDelegateWithName.\n\n Args:\n x: Tensor to use as left operand in operator overloads\n name: The name that is preferred for the op created.\n '
self.x = x
self.name = name | 5,227,219,078,160,836,000 | Construct DivideDelegateWithName.
Args:
x: Tensor to use as left operand in operator overloads
name: The name that is preferred for the op created. | tensorflow/python/ops/math_ops.py | __init__ | minminsun/tensorflow | python | def __init__(self, x, name):
'Construct DivideDelegateWithName.\n\n Args:\n x: Tensor to use as left operand in operator overloads\n name: The name that is preferred for the op created.\n '
self.x = x
self.name = name |
def _tensordot_reshape(a, axes, flipped=False):
'Helper method to perform transpose and reshape for contraction op.\n\n This method is helpful in reducing `math_ops.tensordot` to `math_ops.matmul`\n using `array_ops.transpose` and `array_ops.reshape`. The method takes a\n tensor and performs the correct transpose and reshape operation for a given\n set of indices. It returns the reshaped tensor as well as a list of indices\n necessary to reshape the tensor again after matrix multiplication.\n\n Args:\n a: `Tensor`.\n axes: List or `int32` `Tensor` of unique indices specifying valid axes of\n `a`.\n flipped: An optional `bool`. Defaults to `False`. If `True`, the method\n assumes that `a` is the second argument in the contraction operation.\n\n Returns:\n A tuple `(reshaped_a, free_dims, free_dims_static)` where `reshaped_a` is\n the tensor `a` reshaped to allow contraction via `matmul`, `free_dims` is\n either a list of integers or an `int32` `Tensor`, depending on whether\n the shape of a is fully specified, and free_dims_static is either a list\n of integers and None values, or None, representing the inferred\n static shape of the free dimensions\n '
if (a.get_shape().is_fully_defined() and isinstance(axes, (list, tuple))):
shape_a = a.get_shape().as_list()
axes = [(i if (i >= 0) else (i + len(shape_a))) for i in axes]
free = [i for i in xrange(len(shape_a)) if (i not in axes)]
free_dims = [shape_a[i] for i in free]
prod_free = int(np.prod([shape_a[i] for i in free]))
prod_axes = int(np.prod([shape_a[i] for i in axes]))
perm = ((list(axes) + free) if flipped else (free + list(axes)))
new_shape = ([prod_axes, prod_free] if flipped else [prod_free, prod_axes])
reshaped_a = array_ops.reshape(array_ops.transpose(a, perm), new_shape)
return (reshaped_a, free_dims, free_dims)
else:
if ((a.get_shape().ndims is not None) and isinstance(axes, (list, tuple))):
shape_a = a.get_shape().as_list()
axes = [(i if (i >= 0) else (i + len(shape_a))) for i in axes]
free = [i for i in xrange(len(shape_a)) if (i not in axes)]
axes_dims = [shape_a[i] for i in axes]
free_dims = [shape_a[i] for i in free]
free_dims_static = free_dims
axes = ops.convert_to_tensor(axes, dtype=dtypes.int32, name='axes')
free = ops.convert_to_tensor(free, dtype=dtypes.int32, name='free')
shape_a = array_ops.shape(a)
else:
free_dims_static = None
shape_a = array_ops.shape(a)
rank_a = array_ops.rank(a)
axes = ops.convert_to_tensor(axes, dtype=dtypes.int32, name='axes')
axes = array_ops.where((axes >= 0), axes, (axes + rank_a))
(free, _) = array_ops.setdiff1d(range(rank_a), axes)
free_dims = array_ops.gather(shape_a, free)
axes_dims = array_ops.gather(shape_a, axes)
prod_free_dims = reduce_prod(free_dims)
prod_axes_dims = reduce_prod(axes_dims)
if flipped:
perm = array_ops.concat([axes, free], 0)
new_shape = array_ops.stack([prod_axes_dims, prod_free_dims])
else:
perm = array_ops.concat([free, axes], 0)
new_shape = array_ops.stack([prod_free_dims, prod_axes_dims])
reshaped_a = array_ops.reshape(array_ops.transpose(a, perm), new_shape)
return (reshaped_a, free_dims, free_dims_static) | -1,413,959,816,581,312,000 | Helper method to perform transpose and reshape for contraction op.
This method is helpful in reducing `math_ops.tensordot` to `math_ops.matmul`
using `array_ops.transpose` and `array_ops.reshape`. The method takes a
tensor and performs the correct transpose and reshape operation for a given
set of indices. It returns the reshaped tensor as well as a list of indices
necessary to reshape the tensor again after matrix multiplication.
Args:
a: `Tensor`.
axes: List or `int32` `Tensor` of unique indices specifying valid axes of
`a`.
flipped: An optional `bool`. Defaults to `False`. If `True`, the method
assumes that `a` is the second argument in the contraction operation.
Returns:
A tuple `(reshaped_a, free_dims, free_dims_static)` where `reshaped_a` is
the tensor `a` reshaped to allow contraction via `matmul`, `free_dims` is
either a list of integers or an `int32` `Tensor`, depending on whether
the shape of a is fully specified, and free_dims_static is either a list
of integers and None values, or None, representing the inferred
static shape of the free dimensions | tensorflow/python/ops/math_ops.py | _tensordot_reshape | minminsun/tensorflow | python | def _tensordot_reshape(a, axes, flipped=False):
'Helper method to perform transpose and reshape for contraction op.\n\n This method is helpful in reducing `math_ops.tensordot` to `math_ops.matmul`\n using `array_ops.transpose` and `array_ops.reshape`. The method takes a\n tensor and performs the correct transpose and reshape operation for a given\n set of indices. It returns the reshaped tensor as well as a list of indices\n necessary to reshape the tensor again after matrix multiplication.\n\n Args:\n a: `Tensor`.\n axes: List or `int32` `Tensor` of unique indices specifying valid axes of\n `a`.\n flipped: An optional `bool`. Defaults to `False`. If `True`, the method\n assumes that `a` is the second argument in the contraction operation.\n\n Returns:\n A tuple `(reshaped_a, free_dims, free_dims_static)` where `reshaped_a` is\n the tensor `a` reshaped to allow contraction via `matmul`, `free_dims` is\n either a list of integers or an `int32` `Tensor`, depending on whether\n the shape of a is fully specified, and free_dims_static is either a list\n of integers and None values, or None, representing the inferred\n static shape of the free dimensions\n '
if (a.get_shape().is_fully_defined() and isinstance(axes, (list, tuple))):
shape_a = a.get_shape().as_list()
axes = [(i if (i >= 0) else (i + len(shape_a))) for i in axes]
free = [i for i in xrange(len(shape_a)) if (i not in axes)]
free_dims = [shape_a[i] for i in free]
prod_free = int(np.prod([shape_a[i] for i in free]))
prod_axes = int(np.prod([shape_a[i] for i in axes]))
perm = ((list(axes) + free) if flipped else (free + list(axes)))
new_shape = ([prod_axes, prod_free] if flipped else [prod_free, prod_axes])
reshaped_a = array_ops.reshape(array_ops.transpose(a, perm), new_shape)
return (reshaped_a, free_dims, free_dims)
else:
if ((a.get_shape().ndims is not None) and isinstance(axes, (list, tuple))):
shape_a = a.get_shape().as_list()
axes = [(i if (i >= 0) else (i + len(shape_a))) for i in axes]
free = [i for i in xrange(len(shape_a)) if (i not in axes)]
axes_dims = [shape_a[i] for i in axes]
free_dims = [shape_a[i] for i in free]
free_dims_static = free_dims
axes = ops.convert_to_tensor(axes, dtype=dtypes.int32, name='axes')
free = ops.convert_to_tensor(free, dtype=dtypes.int32, name='free')
shape_a = array_ops.shape(a)
else:
free_dims_static = None
shape_a = array_ops.shape(a)
rank_a = array_ops.rank(a)
axes = ops.convert_to_tensor(axes, dtype=dtypes.int32, name='axes')
axes = array_ops.where((axes >= 0), axes, (axes + rank_a))
(free, _) = array_ops.setdiff1d(range(rank_a), axes)
free_dims = array_ops.gather(shape_a, free)
axes_dims = array_ops.gather(shape_a, axes)
prod_free_dims = reduce_prod(free_dims)
prod_axes_dims = reduce_prod(axes_dims)
if flipped:
perm = array_ops.concat([axes, free], 0)
new_shape = array_ops.stack([prod_axes_dims, prod_free_dims])
else:
perm = array_ops.concat([free, axes], 0)
new_shape = array_ops.stack([prod_free_dims, prod_axes_dims])
reshaped_a = array_ops.reshape(array_ops.transpose(a, perm), new_shape)
return (reshaped_a, free_dims, free_dims_static) |
def _tensordot_axes(a, axes):
'Generates two sets of contraction axes for the two tensor arguments.'
a_shape = a.get_shape()
if isinstance(axes, compat.integral_types):
if (axes < 0):
raise ValueError("'axes' must be at least 0.")
if (a_shape.ndims is not None):
if (axes > a_shape.ndims):
raise ValueError(("'axes' must not be larger than the number of dimensions of tensor %s." % a))
return (list(xrange((a_shape.ndims - axes), a_shape.ndims)), list(xrange(axes)))
else:
rank = array_ops.rank(a)
return (range((rank - axes), rank, dtype=dtypes.int32), range(axes, dtype=dtypes.int32))
elif isinstance(axes, (list, tuple)):
if (len(axes) != 2):
raise ValueError("'axes' must be an integer or have length 2.")
a_axes = axes[0]
b_axes = axes[1]
if (isinstance(a_axes, compat.integral_types) and isinstance(b_axes, compat.integral_types)):
a_axes = [a_axes]
b_axes = [b_axes]
if (len(a_axes) != len(b_axes)):
raise ValueError(("Different number of contraction axes 'a' and 'b', %s != %s." % (len(a_axes), len(b_axes))))
return (a_axes, b_axes)
else:
axes = ops.convert_to_tensor(axes, name='axes', dtype=dtypes.int32)
return (axes[0], axes[1]) | 7,019,879,053,513,074,000 | Generates two sets of contraction axes for the two tensor arguments. | tensorflow/python/ops/math_ops.py | _tensordot_axes | minminsun/tensorflow | python | def _tensordot_axes(a, axes):
a_shape = a.get_shape()
if isinstance(axes, compat.integral_types):
if (axes < 0):
raise ValueError("'axes' must be at least 0.")
if (a_shape.ndims is not None):
if (axes > a_shape.ndims):
raise ValueError(("'axes' must not be larger than the number of dimensions of tensor %s." % a))
return (list(xrange((a_shape.ndims - axes), a_shape.ndims)), list(xrange(axes)))
else:
rank = array_ops.rank(a)
return (range((rank - axes), rank, dtype=dtypes.int32), range(axes, dtype=dtypes.int32))
elif isinstance(axes, (list, tuple)):
if (len(axes) != 2):
raise ValueError("'axes' must be an integer or have length 2.")
a_axes = axes[0]
b_axes = axes[1]
if (isinstance(a_axes, compat.integral_types) and isinstance(b_axes, compat.integral_types)):
a_axes = [a_axes]
b_axes = [b_axes]
if (len(a_axes) != len(b_axes)):
raise ValueError(("Different number of contraction axes 'a' and 'b', %s != %s." % (len(a_axes), len(b_axes))))
return (a_axes, b_axes)
else:
axes = ops.convert_to_tensor(axes, name='axes', dtype=dtypes.int32)
return (axes[0], axes[1]) |
def robust_mean_mixture(x):
"Compute the mean via a mixture of two Gaussians\n\n One Gaussian accounts for outliers, and one Gaussian accounts for\n the true distribution. This cannot be computed analytically, so\n it uses scipy's function optimization\n "
if (len(x) == 1):
return x
x = x.ravel()
mu_bg = np.mean(x)
sig_bg = (3 * np.std(x))
likelihood = (lambda v: (- np.sum(np.log((norm.pdf(x, v[0], v[1]) + norm.pdf(x, mu_bg, sig_bg))))))
v0 = np.array([0, 30])
v_best = optimize.fmin(likelihood, v0, disp=False)
return v_best[0] | -6,581,423,013,018,028,000 | Compute the mean via a mixture of two Gaussians
One Gaussian accounts for outliers, and one Gaussian accounts for
the true distribution. This cannot be computed analytically, so
it uses scipy's function optimization | book_figures/chapter3/fig_cauchy_median_mean.py | robust_mean_mixture | larsmans/astroML | python | def robust_mean_mixture(x):
"Compute the mean via a mixture of two Gaussians\n\n One Gaussian accounts for outliers, and one Gaussian accounts for\n the true distribution. This cannot be computed analytically, so\n it uses scipy's function optimization\n "
if (len(x) == 1):
return x
x = x.ravel()
mu_bg = np.mean(x)
sig_bg = (3 * np.std(x))
likelihood = (lambda v: (- np.sum(np.log((norm.pdf(x, v[0], v[1]) + norm.pdf(x, mu_bg, sig_bg))))))
v0 = np.array([0, 30])
v_best = optimize.fmin(likelihood, v0, disp=False)
return v_best[0] |
def robust_mean_iterated(x, sigma_cut=3):
'Compute the robust mean iteratively\n\n After computing the mean, points further than 3 sigma from the mean\n are removed and the result is repeated until convergence.\n '
flag = np.ones(x.shape, dtype=bool)
n_to_keep = x.size
while True:
xf = x[flag]
mu = xf.mean()
sig = xf.std()
if (len(xf) == 1):
break
x_sig = abs(((x - mu) / sig))
too_far = (x_sig > sigma_cut)
flag[too_far] = False
n_flag = flag.sum()
if (n_flag == n_to_keep):
break
else:
n_to_keep = n_flag
return mu | 8,003,899,538,360,857,000 | Compute the robust mean iteratively
After computing the mean, points further than 3 sigma from the mean
are removed and the result is repeated until convergence. | book_figures/chapter3/fig_cauchy_median_mean.py | robust_mean_iterated | larsmans/astroML | python | def robust_mean_iterated(x, sigma_cut=3):
'Compute the robust mean iteratively\n\n After computing the mean, points further than 3 sigma from the mean\n are removed and the result is repeated until convergence.\n '
flag = np.ones(x.shape, dtype=bool)
n_to_keep = x.size
while True:
xf = x[flag]
mu = xf.mean()
sig = xf.std()
if (len(xf) == 1):
break
x_sig = abs(((x - mu) / sig))
too_far = (x_sig > sigma_cut)
flag[too_far] = False
n_flag = flag.sum()
if (n_flag == n_to_keep):
break
else:
n_to_keep = n_flag
return mu |
def hex_str(an_int):
'Converts an int to an hexadecimal string\n '
return '{0:#x}'.format(an_int) | 7,558,796,261,362,834,000 | Converts an int to an hexadecimal string | Sklearn_scipy_numpy/source/sklearn/externals/joblib/numpy_pickle.py | hex_str | Con-Mi/lambda-packs | python | def hex_str(an_int):
'\n '
return '{0:#x}'.format(an_int) |
def _read_magic(file_handle):
' Utility to check the magic signature of a file identifying it as a\n Zfile\n '
magic = file_handle.read(len(_ZFILE_PREFIX))
file_handle.seek(0)
return magic | -8,760,349,105,058,396,000 | Utility to check the magic signature of a file identifying it as a
Zfile | Sklearn_scipy_numpy/source/sklearn/externals/joblib/numpy_pickle.py | _read_magic | Con-Mi/lambda-packs | python | def _read_magic(file_handle):
' Utility to check the magic signature of a file identifying it as a\n Zfile\n '
magic = file_handle.read(len(_ZFILE_PREFIX))
file_handle.seek(0)
return magic |
def read_zfile(file_handle):
'Read the z-file and return the content as a string\n\n Z-files are raw data compressed with zlib used internally by joblib\n for persistence. Backward compatibility is not guaranteed. Do not\n use for external purposes.\n '
file_handle.seek(0)
assert (_read_magic(file_handle) == _ZFILE_PREFIX), 'File does not have the right magic'
header_length = (len(_ZFILE_PREFIX) + _MAX_LEN)
length = file_handle.read(header_length)
length = length[len(_ZFILE_PREFIX):]
length = int(length, 16)
next_byte = file_handle.read(1)
if (next_byte != b' '):
file_handle.seek(header_length)
data = zlib.decompress(file_handle.read(), 15, length)
assert (len(data) == length), ('Incorrect data length while decompressing %s.The file could be corrupted.' % file_handle)
return data | 5,326,646,524,738,486,000 | Read the z-file and return the content as a string
Z-files are raw data compressed with zlib used internally by joblib
for persistence. Backward compatibility is not guaranteed. Do not
use for external purposes. | Sklearn_scipy_numpy/source/sklearn/externals/joblib/numpy_pickle.py | read_zfile | Con-Mi/lambda-packs | python | def read_zfile(file_handle):
'Read the z-file and return the content as a string\n\n Z-files are raw data compressed with zlib used internally by joblib\n for persistence. Backward compatibility is not guaranteed. Do not\n use for external purposes.\n '
file_handle.seek(0)
assert (_read_magic(file_handle) == _ZFILE_PREFIX), 'File does not have the right magic'
header_length = (len(_ZFILE_PREFIX) + _MAX_LEN)
length = file_handle.read(header_length)
length = length[len(_ZFILE_PREFIX):]
length = int(length, 16)
next_byte = file_handle.read(1)
if (next_byte != b' '):
file_handle.seek(header_length)
data = zlib.decompress(file_handle.read(), 15, length)
assert (len(data) == length), ('Incorrect data length while decompressing %s.The file could be corrupted.' % file_handle)
return data |
def write_zfile(file_handle, data, compress=1):
'Write the data in the given file as a Z-file.\n\n Z-files are raw data compressed with zlib used internally by joblib\n for persistence. Backward compatibility is not guarantied. Do not\n use for external purposes.\n '
file_handle.write(_ZFILE_PREFIX)
length = hex_str(len(data))
file_handle.write(asbytes(length.ljust(_MAX_LEN)))
file_handle.write(zlib.compress(asbytes(data), compress)) | 3,700,030,578,405,151,000 | Write the data in the given file as a Z-file.
Z-files are raw data compressed with zlib used internally by joblib
for persistence. Backward compatibility is not guarantied. Do not
use for external purposes. | Sklearn_scipy_numpy/source/sklearn/externals/joblib/numpy_pickle.py | write_zfile | Con-Mi/lambda-packs | python | def write_zfile(file_handle, data, compress=1):
'Write the data in the given file as a Z-file.\n\n Z-files are raw data compressed with zlib used internally by joblib\n for persistence. Backward compatibility is not guarantied. Do not\n use for external purposes.\n '
file_handle.write(_ZFILE_PREFIX)
length = hex_str(len(data))
file_handle.write(asbytes(length.ljust(_MAX_LEN)))
file_handle.write(zlib.compress(asbytes(data), compress)) |
def dump(value, filename, compress=0, cache_size=100, protocol=None):
'Fast persistence of an arbitrary Python object into one or multiple\n files, with dedicated storage for numpy arrays.\n\n Parameters\n -----------\n value: any Python object\n The object to store to disk\n filename: string\n The name of the file in which it is to be stored\n compress: integer for 0 to 9, optional\n Optional compression level for the data. 0 is no compression.\n Higher means more compression, but also slower read and\n write times. Using a value of 3 is often a good compromise.\n See the notes for more details.\n cache_size: positive number, optional\n Fixes the order of magnitude (in megabytes) of the cache used\n for in-memory compression. Note that this is just an order of\n magnitude estimate and that for big arrays, the code will go\n over this value at dump and at load time.\n protocol: positive int\n Pickle protocol, see pickle.dump documentation for more details.\n\n Returns\n -------\n filenames: list of strings\n The list of file names in which the data is stored. If\n compress is false, each array is stored in a different file.\n\n See Also\n --------\n joblib.load : corresponding loader\n\n Notes\n -----\n Memmapping on load cannot be used for compressed files. Thus\n using compression can significantly slow down loading. In\n addition, compressed files take extra extra memory during\n dump and load.\n '
if (compress is True):
compress = 3
if (not isinstance(filename, _basestring)):
raise ValueError(('Second argument should be a filename, %s (type %s) was given' % (filename, type(filename))))
try:
pickler = NumpyPickler(filename, compress=compress, cache_size=cache_size, protocol=protocol)
pickler.dump(value)
pickler.close()
finally:
if (('pickler' in locals()) and hasattr(pickler, 'file')):
pickler.file.flush()
pickler.file.close()
return pickler._filenames | 3,711,028,077,857,704,000 | Fast persistence of an arbitrary Python object into one or multiple
files, with dedicated storage for numpy arrays.
Parameters
-----------
value: any Python object
The object to store to disk
filename: string
The name of the file in which it is to be stored
compress: integer for 0 to 9, optional
Optional compression level for the data. 0 is no compression.
Higher means more compression, but also slower read and
write times. Using a value of 3 is often a good compromise.
See the notes for more details.
cache_size: positive number, optional
Fixes the order of magnitude (in megabytes) of the cache used
for in-memory compression. Note that this is just an order of
magnitude estimate and that for big arrays, the code will go
over this value at dump and at load time.
protocol: positive int
Pickle protocol, see pickle.dump documentation for more details.
Returns
-------
filenames: list of strings
The list of file names in which the data is stored. If
compress is false, each array is stored in a different file.
See Also
--------
joblib.load : corresponding loader
Notes
-----
Memmapping on load cannot be used for compressed files. Thus
using compression can significantly slow down loading. In
addition, compressed files take extra extra memory during
dump and load. | Sklearn_scipy_numpy/source/sklearn/externals/joblib/numpy_pickle.py | dump | Con-Mi/lambda-packs | python | def dump(value, filename, compress=0, cache_size=100, protocol=None):
'Fast persistence of an arbitrary Python object into one or multiple\n files, with dedicated storage for numpy arrays.\n\n Parameters\n -----------\n value: any Python object\n The object to store to disk\n filename: string\n The name of the file in which it is to be stored\n compress: integer for 0 to 9, optional\n Optional compression level for the data. 0 is no compression.\n Higher means more compression, but also slower read and\n write times. Using a value of 3 is often a good compromise.\n See the notes for more details.\n cache_size: positive number, optional\n Fixes the order of magnitude (in megabytes) of the cache used\n for in-memory compression. Note that this is just an order of\n magnitude estimate and that for big arrays, the code will go\n over this value at dump and at load time.\n protocol: positive int\n Pickle protocol, see pickle.dump documentation for more details.\n\n Returns\n -------\n filenames: list of strings\n The list of file names in which the data is stored. If\n compress is false, each array is stored in a different file.\n\n See Also\n --------\n joblib.load : corresponding loader\n\n Notes\n -----\n Memmapping on load cannot be used for compressed files. Thus\n using compression can significantly slow down loading. In\n addition, compressed files take extra extra memory during\n dump and load.\n '
if (compress is True):
compress = 3
if (not isinstance(filename, _basestring)):
raise ValueError(('Second argument should be a filename, %s (type %s) was given' % (filename, type(filename))))
try:
pickler = NumpyPickler(filename, compress=compress, cache_size=cache_size, protocol=protocol)
pickler.dump(value)
pickler.close()
finally:
if (('pickler' in locals()) and hasattr(pickler, 'file')):
pickler.file.flush()
pickler.file.close()
return pickler._filenames |
def load(filename, mmap_mode=None):
"Reconstruct a Python object from a file persisted with joblib.dump.\n\n Parameters\n -----------\n filename: string\n The name of the file from which to load the object\n mmap_mode: {None, 'r+', 'r', 'w+', 'c'}, optional\n If not None, the arrays are memory-mapped from the disk. This\n mode has no effect for compressed files. Note that in this\n case the reconstructed object might not longer match exactly\n the originally pickled object.\n\n Returns\n -------\n result: any Python object\n The object stored in the file.\n\n See Also\n --------\n joblib.dump : function to save an object\n\n Notes\n -----\n\n This function can load numpy array files saved separately during the\n dump. If the mmap_mode argument is given, it is passed to np.load and\n arrays are loaded as memmaps. As a consequence, the reconstructed\n object might not match the original pickled object. Note that if the\n file was saved with compression, the arrays cannot be memmaped.\n "
with open(filename, 'rb') as file_handle:
if (_read_magic(file_handle) == _ZFILE_PREFIX):
if (mmap_mode is not None):
warnings.warn(('file "%(filename)s" appears to be a zip, ignoring mmap_mode "%(mmap_mode)s" flag passed' % locals()), Warning, stacklevel=2)
unpickler = ZipNumpyUnpickler(filename, file_handle=file_handle)
else:
unpickler = NumpyUnpickler(filename, file_handle=file_handle, mmap_mode=mmap_mode)
try:
obj = unpickler.load()
except UnicodeDecodeError as exc:
if PY3_OR_LATER:
new_exc = ValueError('You may be trying to read with python 3 a joblib pickle generated with python 2. This feature is not supported by joblib.')
new_exc.__cause__ = exc
raise new_exc
finally:
if hasattr(unpickler, 'file_handle'):
unpickler.file_handle.close()
return obj | -3,146,841,016,032,771,000 | Reconstruct a Python object from a file persisted with joblib.dump.
Parameters
-----------
filename: string
The name of the file from which to load the object
mmap_mode: {None, 'r+', 'r', 'w+', 'c'}, optional
If not None, the arrays are memory-mapped from the disk. This
mode has no effect for compressed files. Note that in this
case the reconstructed object might not longer match exactly
the originally pickled object.
Returns
-------
result: any Python object
The object stored in the file.
See Also
--------
joblib.dump : function to save an object
Notes
-----
This function can load numpy array files saved separately during the
dump. If the mmap_mode argument is given, it is passed to np.load and
arrays are loaded as memmaps. As a consequence, the reconstructed
object might not match the original pickled object. Note that if the
file was saved with compression, the arrays cannot be memmaped. | Sklearn_scipy_numpy/source/sklearn/externals/joblib/numpy_pickle.py | load | Con-Mi/lambda-packs | python | def load(filename, mmap_mode=None):
"Reconstruct a Python object from a file persisted with joblib.dump.\n\n Parameters\n -----------\n filename: string\n The name of the file from which to load the object\n mmap_mode: {None, 'r+', 'r', 'w+', 'c'}, optional\n If not None, the arrays are memory-mapped from the disk. This\n mode has no effect for compressed files. Note that in this\n case the reconstructed object might not longer match exactly\n the originally pickled object.\n\n Returns\n -------\n result: any Python object\n The object stored in the file.\n\n See Also\n --------\n joblib.dump : function to save an object\n\n Notes\n -----\n\n This function can load numpy array files saved separately during the\n dump. If the mmap_mode argument is given, it is passed to np.load and\n arrays are loaded as memmaps. As a consequence, the reconstructed\n object might not match the original pickled object. Note that if the\n file was saved with compression, the arrays cannot be memmaped.\n "
with open(filename, 'rb') as file_handle:
if (_read_magic(file_handle) == _ZFILE_PREFIX):
if (mmap_mode is not None):
warnings.warn(('file "%(filename)s" appears to be a zip, ignoring mmap_mode "%(mmap_mode)s" flag passed' % locals()), Warning, stacklevel=2)
unpickler = ZipNumpyUnpickler(filename, file_handle=file_handle)
else:
unpickler = NumpyUnpickler(filename, file_handle=file_handle, mmap_mode=mmap_mode)
try:
obj = unpickler.load()
except UnicodeDecodeError as exc:
if PY3_OR_LATER:
new_exc = ValueError('You may be trying to read with python 3 a joblib pickle generated with python 2. This feature is not supported by joblib.')
new_exc.__cause__ = exc
raise new_exc
finally:
if hasattr(unpickler, 'file_handle'):
unpickler.file_handle.close()
return obj |
def __init__(self, filename, subclass, allow_mmap=True):
'Store the useful information for later'
self.filename = filename
self.subclass = subclass
self.allow_mmap = allow_mmap | 2,602,862,781,666,437,600 | Store the useful information for later | Sklearn_scipy_numpy/source/sklearn/externals/joblib/numpy_pickle.py | __init__ | Con-Mi/lambda-packs | python | def __init__(self, filename, subclass, allow_mmap=True):
self.filename = filename
self.subclass = subclass
self.allow_mmap = allow_mmap |
def read(self, unpickler):
'Reconstruct the array'
filename = os.path.join(unpickler._dirname, self.filename)
np_ver = [int(x) for x in unpickler.np.__version__.split('.', 2)[:2]]
allow_mmap = getattr(self, 'allow_mmap', True)
memmap_kwargs = ({} if (not allow_mmap) else {'mmap_mode': unpickler.mmap_mode})
array = unpickler.np.load(filename, **memmap_kwargs)
if (hasattr(array, '__array_prepare__') and (not (self.subclass in (unpickler.np.ndarray, unpickler.np.memmap)))):
new_array = unpickler.np.core.multiarray._reconstruct(self.subclass, (0,), 'b')
new_array.__array_prepare__(array)
array = new_array
return array | -6,502,246,441,225,244,000 | Reconstruct the array | Sklearn_scipy_numpy/source/sklearn/externals/joblib/numpy_pickle.py | read | Con-Mi/lambda-packs | python | def read(self, unpickler):
filename = os.path.join(unpickler._dirname, self.filename)
np_ver = [int(x) for x in unpickler.np.__version__.split('.', 2)[:2]]
allow_mmap = getattr(self, 'allow_mmap', True)
memmap_kwargs = ({} if (not allow_mmap) else {'mmap_mode': unpickler.mmap_mode})
array = unpickler.np.load(filename, **memmap_kwargs)
if (hasattr(array, '__array_prepare__') and (not (self.subclass in (unpickler.np.ndarray, unpickler.np.memmap)))):
new_array = unpickler.np.core.multiarray._reconstruct(self.subclass, (0,), 'b')
new_array.__array_prepare__(array)
array = new_array
return array |
def __init__(self, filename, init_args, state):
'Store the useful information for later'
self.filename = filename
self.state = state
self.init_args = init_args | 314,920,583,705,363,460 | Store the useful information for later | Sklearn_scipy_numpy/source/sklearn/externals/joblib/numpy_pickle.py | __init__ | Con-Mi/lambda-packs | python | def __init__(self, filename, init_args, state):
self.filename = filename
self.state = state
self.init_args = init_args |
def read(self, unpickler):
'Reconstruct the array from the meta-information and the z-file'
filename = os.path.join(unpickler._dirname, self.filename)
array = unpickler.np.core.multiarray._reconstruct(*self.init_args)
with open(filename, 'rb') as f:
data = read_zfile(f)
state = (self.state + (data,))
array.__setstate__(state)
return array | -2,455,838,817,075,382,300 | Reconstruct the array from the meta-information and the z-file | Sklearn_scipy_numpy/source/sklearn/externals/joblib/numpy_pickle.py | read | Con-Mi/lambda-packs | python | def read(self, unpickler):
filename = os.path.join(unpickler._dirname, self.filename)
array = unpickler.np.core.multiarray._reconstruct(*self.init_args)
with open(filename, 'rb') as f:
data = read_zfile(f)
state = (self.state + (data,))
array.__setstate__(state)
return array |
def save(self, obj):
' Subclass the save method, to save ndarray subclasses in npy\n files, rather than pickling them. Of course, this is a\n total abuse of the Pickler class.\n '
if ((self.np is not None) and (type(obj) in (self.np.ndarray, self.np.matrix, self.np.memmap))):
size = (obj.size * obj.itemsize)
if (self.compress and (size < (self.cache_size * _MEGA))):
if (type(obj) is self.np.memmap):
obj = self.np.asarray(obj)
return Pickler.save(self, obj)
if (not obj.dtype.hasobject):
try:
filename = ('%s_%02i.npy' % (self._filename, self._npy_counter))
(obj, filename) = self._write_array(obj, filename)
self._filenames.append(filename)
self._npy_counter += 1
except Exception:
print(('Failed to save %s to .npy file:\n%s' % (type(obj), traceback.format_exc())))
return Pickler.save(self, obj) | 5,880,806,143,418,513,000 | Subclass the save method, to save ndarray subclasses in npy
files, rather than pickling them. Of course, this is a
total abuse of the Pickler class. | Sklearn_scipy_numpy/source/sklearn/externals/joblib/numpy_pickle.py | save | Con-Mi/lambda-packs | python | def save(self, obj):
' Subclass the save method, to save ndarray subclasses in npy\n files, rather than pickling them. Of course, this is a\n total abuse of the Pickler class.\n '
if ((self.np is not None) and (type(obj) in (self.np.ndarray, self.np.matrix, self.np.memmap))):
size = (obj.size * obj.itemsize)
if (self.compress and (size < (self.cache_size * _MEGA))):
if (type(obj) is self.np.memmap):
obj = self.np.asarray(obj)
return Pickler.save(self, obj)
if (not obj.dtype.hasobject):
try:
filename = ('%s_%02i.npy' % (self._filename, self._npy_counter))
(obj, filename) = self._write_array(obj, filename)
self._filenames.append(filename)
self._npy_counter += 1
except Exception:
print(('Failed to save %s to .npy file:\n%s' % (type(obj), traceback.format_exc())))
return Pickler.save(self, obj) |
def load_build(self):
' This method is called to set the state of a newly created\n object.\n\n We capture it to replace our place-holder objects,\n NDArrayWrapper, by the array we are interested in. We\n replace them directly in the stack of pickler.\n '
Unpickler.load_build(self)
if isinstance(self.stack[(- 1)], NDArrayWrapper):
if (self.np is None):
raise ImportError("Trying to unpickle an ndarray, but numpy didn't import correctly")
nd_array_wrapper = self.stack.pop()
array = nd_array_wrapper.read(self)
self.stack.append(array) | -5,773,961,076,715,824,000 | This method is called to set the state of a newly created
object.
We capture it to replace our place-holder objects,
NDArrayWrapper, by the array we are interested in. We
replace them directly in the stack of pickler. | Sklearn_scipy_numpy/source/sklearn/externals/joblib/numpy_pickle.py | load_build | Con-Mi/lambda-packs | python | def load_build(self):
' This method is called to set the state of a newly created\n object.\n\n We capture it to replace our place-holder objects,\n NDArrayWrapper, by the array we are interested in. We\n replace them directly in the stack of pickler.\n '
Unpickler.load_build(self)
if isinstance(self.stack[(- 1)], NDArrayWrapper):
if (self.np is None):
raise ImportError("Trying to unpickle an ndarray, but numpy didn't import correctly")
nd_array_wrapper = self.stack.pop()
array = nd_array_wrapper.read(self)
self.stack.append(array) |
def infer_language_pair(path):
'Infer language pair from filename: <split>.<lang1>-<lang2>.(...).idx'
(src, dst) = (None, None)
for filename in PathManager.ls(path):
parts = filename.split('.')
if ((len(parts) >= 3) and (len(parts[1].split('-')) == 2)):
return parts[1].split('-')
return (src, dst) | 1,323,945,075,611,131,000 | Infer language pair from filename: <split>.<lang1>-<lang2>.(...).idx | fairseq/data/data_utils.py | infer_language_pair | 1130310223/fairseq | python | def infer_language_pair(path):
(src, dst) = (None, None)
for filename in PathManager.ls(path):
parts = filename.split('.')
if ((len(parts) >= 3) and (len(parts[1].split('-')) == 2)):
return parts[1].split('-')
return (src, dst) |
def collate_tokens(values, pad_idx, eos_idx=None, left_pad=False, move_eos_to_beginning=False, pad_to_length=None, pad_to_multiple=1, pad_to_bsz=None):
'Convert a list of 1d tensors into a padded 2d tensor.'
size = max((v.size(0) for v in values))
size = (size if (pad_to_length is None) else max(size, pad_to_length))
if ((pad_to_multiple != 1) and ((size % pad_to_multiple) != 0)):
size = int(((((size - 0.1) // pad_to_multiple) + 1) * pad_to_multiple))
batch_size = (len(values) if (pad_to_bsz is None) else max(len(values), pad_to_bsz))
res = values[0].new(batch_size, size).fill_(pad_idx)
def copy_tensor(src, dst):
assert (dst.numel() == src.numel())
if move_eos_to_beginning:
if (eos_idx is None):
dst[0] = src[(- 1)]
else:
dst[0] = eos_idx
dst[1:] = src[:(- 1)]
else:
dst.copy_(src)
for (i, v) in enumerate(values):
copy_tensor(v, (res[i][(size - len(v)):] if left_pad else res[i][:len(v)]))
return res | -6,598,988,593,867,076,000 | Convert a list of 1d tensors into a padded 2d tensor. | fairseq/data/data_utils.py | collate_tokens | 1130310223/fairseq | python | def collate_tokens(values, pad_idx, eos_idx=None, left_pad=False, move_eos_to_beginning=False, pad_to_length=None, pad_to_multiple=1, pad_to_bsz=None):
size = max((v.size(0) for v in values))
size = (size if (pad_to_length is None) else max(size, pad_to_length))
if ((pad_to_multiple != 1) and ((size % pad_to_multiple) != 0)):
size = int(((((size - 0.1) // pad_to_multiple) + 1) * pad_to_multiple))
batch_size = (len(values) if (pad_to_bsz is None) else max(len(values), pad_to_bsz))
res = values[0].new(batch_size, size).fill_(pad_idx)
def copy_tensor(src, dst):
assert (dst.numel() == src.numel())
if move_eos_to_beginning:
if (eos_idx is None):
dst[0] = src[(- 1)]
else:
dst[0] = eos_idx
dst[1:] = src[:(- 1)]
else:
dst.copy_(src)
for (i, v) in enumerate(values):
copy_tensor(v, (res[i][(size - len(v)):] if left_pad else res[i][:len(v)]))
return res |
def load_indexed_dataset(path, dictionary=None, dataset_impl=None, combine=False, default='cached'):
"A helper function for loading indexed datasets.\n\n Args:\n path (str): path to indexed dataset (e.g., 'data-bin/train')\n dictionary (~fairseq.data.Dictionary): data dictionary\n dataset_impl (str, optional): which dataset implementation to use. If\n not provided, it will be inferred automatically. For legacy indexed\n data we use the 'cached' implementation by default.\n combine (bool, optional): automatically load and combine multiple\n datasets. For example, if *path* is 'data-bin/train', then we will\n combine 'data-bin/train', 'data-bin/train1', ... and return a\n single ConcatDataset instance.\n "
import fairseq.data.indexed_dataset as indexed_dataset
from fairseq.data.concat_dataset import ConcatDataset
datasets = []
for k in itertools.count():
path_k = (path + (str(k) if (k > 0) else ''))
try:
path_k = indexed_dataset.get_indexed_dataset_to_local(path_k)
except Exception as e:
if ('StorageException: [404] Path not found' in str(e)):
logger.warning(f'path_k: {e} not found')
else:
raise e
dataset_impl_k = dataset_impl
if (dataset_impl_k is None):
dataset_impl_k = indexed_dataset.infer_dataset_impl(path_k)
dataset = indexed_dataset.make_dataset(path_k, impl=(dataset_impl_k or default), fix_lua_indexing=True, dictionary=dictionary)
if (dataset is None):
break
logger.info('loaded {:,} examples from: {}'.format(len(dataset), path_k))
datasets.append(dataset)
if (not combine):
break
if (len(datasets) == 0):
return None
elif (len(datasets) == 1):
return datasets[0]
else:
return ConcatDataset(datasets) | -5,094,570,305,231,014,000 | A helper function for loading indexed datasets.
Args:
path (str): path to indexed dataset (e.g., 'data-bin/train')
dictionary (~fairseq.data.Dictionary): data dictionary
dataset_impl (str, optional): which dataset implementation to use. If
not provided, it will be inferred automatically. For legacy indexed
data we use the 'cached' implementation by default.
combine (bool, optional): automatically load and combine multiple
datasets. For example, if *path* is 'data-bin/train', then we will
combine 'data-bin/train', 'data-bin/train1', ... and return a
single ConcatDataset instance. | fairseq/data/data_utils.py | load_indexed_dataset | 1130310223/fairseq | python | def load_indexed_dataset(path, dictionary=None, dataset_impl=None, combine=False, default='cached'):
"A helper function for loading indexed datasets.\n\n Args:\n path (str): path to indexed dataset (e.g., 'data-bin/train')\n dictionary (~fairseq.data.Dictionary): data dictionary\n dataset_impl (str, optional): which dataset implementation to use. If\n not provided, it will be inferred automatically. For legacy indexed\n data we use the 'cached' implementation by default.\n combine (bool, optional): automatically load and combine multiple\n datasets. For example, if *path* is 'data-bin/train', then we will\n combine 'data-bin/train', 'data-bin/train1', ... and return a\n single ConcatDataset instance.\n "
import fairseq.data.indexed_dataset as indexed_dataset
from fairseq.data.concat_dataset import ConcatDataset
datasets = []
for k in itertools.count():
path_k = (path + (str(k) if (k > 0) else ))
try:
path_k = indexed_dataset.get_indexed_dataset_to_local(path_k)
except Exception as e:
if ('StorageException: [404] Path not found' in str(e)):
logger.warning(f'path_k: {e} not found')
else:
raise e
dataset_impl_k = dataset_impl
if (dataset_impl_k is None):
dataset_impl_k = indexed_dataset.infer_dataset_impl(path_k)
dataset = indexed_dataset.make_dataset(path_k, impl=(dataset_impl_k or default), fix_lua_indexing=True, dictionary=dictionary)
if (dataset is None):
break
logger.info('loaded {:,} examples from: {}'.format(len(dataset), path_k))
datasets.append(dataset)
if (not combine):
break
if (len(datasets) == 0):
return None
elif (len(datasets) == 1):
return datasets[0]
else:
return ConcatDataset(datasets) |
@contextlib.contextmanager
def numpy_seed(seed, *addl_seeds):
'Context manager which seeds the NumPy PRNG with the specified seed and\n restores the state afterward'
if (seed is None):
(yield)
return
if (len(addl_seeds) > 0):
seed = int((hash((seed, *addl_seeds)) % 1000000.0))
state = np.random.get_state()
np.random.seed(seed)
try:
(yield)
finally:
np.random.set_state(state) | 3,241,145,856,189,170,000 | Context manager which seeds the NumPy PRNG with the specified seed and
restores the state afterward | fairseq/data/data_utils.py | numpy_seed | 1130310223/fairseq | python | @contextlib.contextmanager
def numpy_seed(seed, *addl_seeds):
'Context manager which seeds the NumPy PRNG with the specified seed and\n restores the state afterward'
if (seed is None):
(yield)
return
if (len(addl_seeds) > 0):
seed = int((hash((seed, *addl_seeds)) % 1000000.0))
state = np.random.get_state()
np.random.seed(seed)
try:
(yield)
finally:
np.random.set_state(state) |
def collect_filtered(function, iterable, filtered):
'\n Similar to :func:`filter` but collects filtered elements in ``filtered``.\n\n Args:\n function (callable): function that returns ``False`` for elements that\n should be filtered\n iterable (iterable): iterable to filter\n filtered (list): list to store filtered elements\n '
for el in iterable:
if function(el):
(yield el)
else:
filtered.append(el) | 6,198,038,143,385,185,000 | Similar to :func:`filter` but collects filtered elements in ``filtered``.
Args:
function (callable): function that returns ``False`` for elements that
should be filtered
iterable (iterable): iterable to filter
filtered (list): list to store filtered elements | fairseq/data/data_utils.py | collect_filtered | 1130310223/fairseq | python | def collect_filtered(function, iterable, filtered):
'\n Similar to :func:`filter` but collects filtered elements in ``filtered``.\n\n Args:\n function (callable): function that returns ``False`` for elements that\n should be filtered\n iterable (iterable): iterable to filter\n filtered (list): list to store filtered elements\n '
for el in iterable:
if function(el):
(yield el)
else:
filtered.append(el) |
def filter_by_size(indices, dataset, max_positions, raise_exception=False):
'\n [deprecated] Filter indices based on their size.\n Use `FairseqDataset::filter_indices_by_size` instead.\n\n Args:\n indices (List[int]): ordered list of dataset indices\n dataset (FairseqDataset): fairseq dataset instance\n max_positions (tuple): filter elements larger than this size.\n Comparisons are done component-wise.\n raise_exception (bool, optional): if ``True``, raise an exception if\n any elements are filtered (default: False).\n '
warnings.warn('data_utils.filter_by_size is deprecated. Use `FairseqDataset::filter_indices_by_size` instead.', stacklevel=2)
if (isinstance(max_positions, float) or isinstance(max_positions, int)):
if (hasattr(dataset, 'sizes') and isinstance(dataset.sizes, np.ndarray)):
ignored = indices[(dataset.sizes[indices] > max_positions)].tolist()
indices = indices[(dataset.sizes[indices] <= max_positions)]
elif (hasattr(dataset, 'sizes') and isinstance(dataset.sizes, list) and (len(dataset.sizes) == 1)):
ignored = indices[(dataset.sizes[0][indices] > max_positions)].tolist()
indices = indices[(dataset.sizes[0][indices] <= max_positions)]
else:
(indices, ignored) = _filter_by_size_dynamic(indices, dataset.size, max_positions)
else:
(indices, ignored) = _filter_by_size_dynamic(indices, dataset.size, max_positions)
if ((len(ignored) > 0) and raise_exception):
raise Exception('Size of sample #{} is invalid (={}) since max_positions={}, skip this example with --skip-invalid-size-inputs-valid-test'.format(ignored[0], dataset.size(ignored[0]), max_positions))
if (len(ignored) > 0):
logger.warning('{} samples have invalid sizes and will be skipped, max_positions={}, first few sample ids={}'.format(len(ignored), max_positions, ignored[:10]))
return indices | 217,252,323,563,451,330 | [deprecated] Filter indices based on their size.
Use `FairseqDataset::filter_indices_by_size` instead.
Args:
indices (List[int]): ordered list of dataset indices
dataset (FairseqDataset): fairseq dataset instance
max_positions (tuple): filter elements larger than this size.
Comparisons are done component-wise.
raise_exception (bool, optional): if ``True``, raise an exception if
any elements are filtered (default: False). | fairseq/data/data_utils.py | filter_by_size | 1130310223/fairseq | python | def filter_by_size(indices, dataset, max_positions, raise_exception=False):
'\n [deprecated] Filter indices based on their size.\n Use `FairseqDataset::filter_indices_by_size` instead.\n\n Args:\n indices (List[int]): ordered list of dataset indices\n dataset (FairseqDataset): fairseq dataset instance\n max_positions (tuple): filter elements larger than this size.\n Comparisons are done component-wise.\n raise_exception (bool, optional): if ``True``, raise an exception if\n any elements are filtered (default: False).\n '
warnings.warn('data_utils.filter_by_size is deprecated. Use `FairseqDataset::filter_indices_by_size` instead.', stacklevel=2)
if (isinstance(max_positions, float) or isinstance(max_positions, int)):
if (hasattr(dataset, 'sizes') and isinstance(dataset.sizes, np.ndarray)):
ignored = indices[(dataset.sizes[indices] > max_positions)].tolist()
indices = indices[(dataset.sizes[indices] <= max_positions)]
elif (hasattr(dataset, 'sizes') and isinstance(dataset.sizes, list) and (len(dataset.sizes) == 1)):
ignored = indices[(dataset.sizes[0][indices] > max_positions)].tolist()
indices = indices[(dataset.sizes[0][indices] <= max_positions)]
else:
(indices, ignored) = _filter_by_size_dynamic(indices, dataset.size, max_positions)
else:
(indices, ignored) = _filter_by_size_dynamic(indices, dataset.size, max_positions)
if ((len(ignored) > 0) and raise_exception):
raise Exception('Size of sample #{} is invalid (={}) since max_positions={}, skip this example with --skip-invalid-size-inputs-valid-test'.format(ignored[0], dataset.size(ignored[0]), max_positions))
if (len(ignored) > 0):
logger.warning('{} samples have invalid sizes and will be skipped, max_positions={}, first few sample ids={}'.format(len(ignored), max_positions, ignored[:10]))
return indices |
def filter_paired_dataset_indices_by_size(src_sizes, tgt_sizes, indices, max_sizes):
'Filter a list of sample indices. Remove those that are longer\n than specified in max_sizes.\n\n Args:\n indices (np.array): original array of sample indices\n max_sizes (int or list[int] or tuple[int]): max sample size,\n can be defined separately for src and tgt (then list or tuple)\n\n Returns:\n np.array: filtered sample array\n list: list of removed indices\n '
if (max_sizes is None):
return (indices, [])
if (type(max_sizes) in (int, float)):
(max_src_size, max_tgt_size) = (max_sizes, max_sizes)
else:
(max_src_size, max_tgt_size) = max_sizes
if (tgt_sizes is None):
ignored = indices[(src_sizes[indices] > max_src_size)]
else:
ignored = indices[((src_sizes[indices] > max_src_size) | (tgt_sizes[indices] > max_tgt_size))]
if (len(ignored) > 0):
if (tgt_sizes is None):
indices = indices[(src_sizes[indices] <= max_src_size)]
else:
indices = indices[((src_sizes[indices] <= max_src_size) & (tgt_sizes[indices] <= max_tgt_size))]
return (indices, ignored.tolist()) | 5,178,672,285,530,145,000 | Filter a list of sample indices. Remove those that are longer
than specified in max_sizes.
Args:
indices (np.array): original array of sample indices
max_sizes (int or list[int] or tuple[int]): max sample size,
can be defined separately for src and tgt (then list or tuple)
Returns:
np.array: filtered sample array
list: list of removed indices | fairseq/data/data_utils.py | filter_paired_dataset_indices_by_size | 1130310223/fairseq | python | def filter_paired_dataset_indices_by_size(src_sizes, tgt_sizes, indices, max_sizes):
'Filter a list of sample indices. Remove those that are longer\n than specified in max_sizes.\n\n Args:\n indices (np.array): original array of sample indices\n max_sizes (int or list[int] or tuple[int]): max sample size,\n can be defined separately for src and tgt (then list or tuple)\n\n Returns:\n np.array: filtered sample array\n list: list of removed indices\n '
if (max_sizes is None):
return (indices, [])
if (type(max_sizes) in (int, float)):
(max_src_size, max_tgt_size) = (max_sizes, max_sizes)
else:
(max_src_size, max_tgt_size) = max_sizes
if (tgt_sizes is None):
ignored = indices[(src_sizes[indices] > max_src_size)]
else:
ignored = indices[((src_sizes[indices] > max_src_size) | (tgt_sizes[indices] > max_tgt_size))]
if (len(ignored) > 0):
if (tgt_sizes is None):
indices = indices[(src_sizes[indices] <= max_src_size)]
else:
indices = indices[((src_sizes[indices] <= max_src_size) & (tgt_sizes[indices] <= max_tgt_size))]
return (indices, ignored.tolist()) |
def batch_by_size(indices, num_tokens_fn, num_tokens_vec=None, max_tokens=None, max_sentences=None, required_batch_size_multiple=1, fixed_shapes=None):
'\n Yield mini-batches of indices bucketed by size. Batches may contain\n sequences of different lengths.\n\n Args:\n indices (List[int]): ordered list of dataset indices\n num_tokens_fn (callable): function that returns the number of tokens at\n a given index\n num_tokens_vec (List[int], optional): precomputed vector of the number\n of tokens for each index in indices (to enable faster batch generation)\n max_tokens (int, optional): max number of tokens in each batch\n (default: None).\n max_sentences (int, optional): max number of sentences in each\n batch (default: None).\n required_batch_size_multiple (int, optional): require batch size to\n be less than N or a multiple of N (default: 1).\n fixed_shapes (List[Tuple[int, int]], optional): if given, batches will\n only be created with the given shapes. *max_sentences* and\n *required_batch_size_multiple* will be ignored (default: None).\n '
try:
from fairseq.data.data_utils_fast import batch_by_size_fn, batch_by_size_vec, batch_fixed_shapes_fast
except ImportError:
raise ImportError('Please build Cython components with: `python setup.py build_ext --inplace`')
except ValueError:
raise ValueError('Please build (or rebuild) Cython components with `python setup.py build_ext --inplace`.')
max_tokens = (int(max_tokens) if (max_tokens is not None) else (- 1))
max_sentences = (max_sentences if (max_sentences is not None) else (- 1))
bsz_mult = required_batch_size_multiple
if (not isinstance(indices, np.ndarray)):
indices = np.fromiter(indices, dtype=np.int64, count=(- 1))
if ((num_tokens_vec is not None) and (not isinstance(num_tokens_vec, np.ndarray))):
num_tokens_vec = np.fromiter(num_tokens_vec, dtype=np.int64, count=(- 1))
if (fixed_shapes is None):
if (num_tokens_vec is None):
return batch_by_size_fn(indices, num_tokens_fn, max_tokens, max_sentences, bsz_mult)
else:
return batch_by_size_vec(indices, num_tokens_vec, max_tokens, max_sentences, bsz_mult)
else:
fixed_shapes = np.array(fixed_shapes, dtype=np.int64)
sort_order = np.lexsort([fixed_shapes[:, 1].argsort(), fixed_shapes[:, 0].argsort()])
fixed_shapes_sorted = fixed_shapes[sort_order]
return batch_fixed_shapes_fast(indices, num_tokens_fn, fixed_shapes_sorted) | -8,882,598,935,316,831,000 | Yield mini-batches of indices bucketed by size. Batches may contain
sequences of different lengths.
Args:
indices (List[int]): ordered list of dataset indices
num_tokens_fn (callable): function that returns the number of tokens at
a given index
num_tokens_vec (List[int], optional): precomputed vector of the number
of tokens for each index in indices (to enable faster batch generation)
max_tokens (int, optional): max number of tokens in each batch
(default: None).
max_sentences (int, optional): max number of sentences in each
batch (default: None).
required_batch_size_multiple (int, optional): require batch size to
be less than N or a multiple of N (default: 1).
fixed_shapes (List[Tuple[int, int]], optional): if given, batches will
only be created with the given shapes. *max_sentences* and
*required_batch_size_multiple* will be ignored (default: None). | fairseq/data/data_utils.py | batch_by_size | 1130310223/fairseq | python | def batch_by_size(indices, num_tokens_fn, num_tokens_vec=None, max_tokens=None, max_sentences=None, required_batch_size_multiple=1, fixed_shapes=None):
'\n Yield mini-batches of indices bucketed by size. Batches may contain\n sequences of different lengths.\n\n Args:\n indices (List[int]): ordered list of dataset indices\n num_tokens_fn (callable): function that returns the number of tokens at\n a given index\n num_tokens_vec (List[int], optional): precomputed vector of the number\n of tokens for each index in indices (to enable faster batch generation)\n max_tokens (int, optional): max number of tokens in each batch\n (default: None).\n max_sentences (int, optional): max number of sentences in each\n batch (default: None).\n required_batch_size_multiple (int, optional): require batch size to\n be less than N or a multiple of N (default: 1).\n fixed_shapes (List[Tuple[int, int]], optional): if given, batches will\n only be created with the given shapes. *max_sentences* and\n *required_batch_size_multiple* will be ignored (default: None).\n '
try:
from fairseq.data.data_utils_fast import batch_by_size_fn, batch_by_size_vec, batch_fixed_shapes_fast
except ImportError:
raise ImportError('Please build Cython components with: `python setup.py build_ext --inplace`')
except ValueError:
raise ValueError('Please build (or rebuild) Cython components with `python setup.py build_ext --inplace`.')
max_tokens = (int(max_tokens) if (max_tokens is not None) else (- 1))
max_sentences = (max_sentences if (max_sentences is not None) else (- 1))
bsz_mult = required_batch_size_multiple
if (not isinstance(indices, np.ndarray)):
indices = np.fromiter(indices, dtype=np.int64, count=(- 1))
if ((num_tokens_vec is not None) and (not isinstance(num_tokens_vec, np.ndarray))):
num_tokens_vec = np.fromiter(num_tokens_vec, dtype=np.int64, count=(- 1))
if (fixed_shapes is None):
if (num_tokens_vec is None):
return batch_by_size_fn(indices, num_tokens_fn, max_tokens, max_sentences, bsz_mult)
else:
return batch_by_size_vec(indices, num_tokens_vec, max_tokens, max_sentences, bsz_mult)
else:
fixed_shapes = np.array(fixed_shapes, dtype=np.int64)
sort_order = np.lexsort([fixed_shapes[:, 1].argsort(), fixed_shapes[:, 0].argsort()])
fixed_shapes_sorted = fixed_shapes[sort_order]
return batch_fixed_shapes_fast(indices, num_tokens_fn, fixed_shapes_sorted) |
def compute_mask_indices(shape: Tuple[(int, int)], padding_mask: Optional[torch.Tensor], mask_prob: float, mask_length: int, mask_type: str='static', mask_other: float=0.0, min_masks: int=0, no_overlap: bool=False, min_space: int=0) -> np.ndarray:
'\n Computes random mask spans for a given shape\n\n Args:\n shape: the the shape for which to compute masks.\n should be of size 2 where first element is batch size and 2nd is timesteps\n padding_mask: optional padding mask of the same size as shape, which will prevent masking padded elements\n mask_prob: probability for each token to be chosen as start of the span to be masked. this will be multiplied by\n number of timesteps divided by length of mask span to mask approximately this percentage of all elements.\n however due to overlaps, the actual number will be smaller (unless no_overlap is True)\n mask_type: how to compute mask lengths\n static = fixed size\n uniform = sample from uniform distribution [mask_other, mask_length*2]\n normal = sample from normal distribution with mean mask_length and stdev mask_other. mask is min 1 element\n poisson = sample from possion distribution with lambda = mask length\n min_masks: minimum number of masked spans\n no_overlap: if false, will switch to an alternative recursive algorithm that prevents spans from overlapping\n min_space: only used if no_overlap is True, this is how many elements to keep unmasked between spans\n '
(bsz, all_sz) = shape
mask = np.full((bsz, all_sz), False)
all_num_mask = int((((mask_prob * all_sz) / float(mask_length)) + np.random.rand()))
all_num_mask = max(min_masks, all_num_mask)
mask_idcs = []
for i in range(bsz):
if (padding_mask is not None):
sz = (all_sz - padding_mask[i].long().sum().item())
num_mask = int((((mask_prob * sz) / float(mask_length)) + np.random.rand()))
num_mask = max(min_masks, num_mask)
else:
sz = all_sz
num_mask = all_num_mask
if (mask_type == 'static'):
lengths = np.full(num_mask, mask_length)
elif (mask_type == 'uniform'):
lengths = np.random.randint(mask_other, ((mask_length * 2) + 1), size=num_mask)
elif (mask_type == 'normal'):
lengths = np.random.normal(mask_length, mask_other, size=num_mask)
lengths = [max(1, int(round(x))) for x in lengths]
elif (mask_type == 'poisson'):
lengths = np.random.poisson(mask_length, size=num_mask)
lengths = [int(round(x)) for x in lengths]
else:
raise Exception(('unknown mask selection ' + mask_type))
if (sum(lengths) == 0):
lengths[0] = min(mask_length, (sz - 1))
if no_overlap:
mask_idc = []
def arrange(s, e, length, keep_length):
span_start = np.random.randint(s, (e - length))
mask_idc.extend(((span_start + i) for i in range(length)))
new_parts = []
if (((span_start - s) - min_space) >= keep_length):
new_parts.append((s, ((span_start - min_space) + 1)))
if ((((e - span_start) - keep_length) - min_space) > keep_length):
new_parts.append((((span_start + length) + min_space), e))
return new_parts
parts = [(0, sz)]
min_length = min(lengths)
for length in sorted(lengths, reverse=True):
lens = np.fromiter((((e - s) if ((e - s) >= (length + min_space)) else 0) for (s, e) in parts), np.int)
l_sum = np.sum(lens)
if (l_sum == 0):
break
probs = (lens / np.sum(lens))
c = np.random.choice(len(parts), p=probs)
(s, e) = parts.pop(c)
parts.extend(arrange(s, e, length, min_length))
mask_idc = np.asarray(mask_idc)
else:
min_len = min(lengths)
if ((sz - min_len) <= num_mask):
min_len = ((sz - num_mask) - 1)
mask_idc = np.random.choice((sz - min_len), num_mask, replace=False)
mask_idc = np.asarray([(mask_idc[j] + offset) for j in range(len(mask_idc)) for offset in range(lengths[j])])
mask_idcs.append(np.unique(mask_idc[(mask_idc < sz)]))
min_len = min([len(m) for m in mask_idcs])
for (i, mask_idc) in enumerate(mask_idcs):
if (len(mask_idc) > min_len):
mask_idc = np.random.choice(mask_idc, min_len, replace=False)
mask[(i, mask_idc)] = True
return mask | -2,985,380,715,055,749,600 | Computes random mask spans for a given shape
Args:
shape: the the shape for which to compute masks.
should be of size 2 where first element is batch size and 2nd is timesteps
padding_mask: optional padding mask of the same size as shape, which will prevent masking padded elements
mask_prob: probability for each token to be chosen as start of the span to be masked. this will be multiplied by
number of timesteps divided by length of mask span to mask approximately this percentage of all elements.
however due to overlaps, the actual number will be smaller (unless no_overlap is True)
mask_type: how to compute mask lengths
static = fixed size
uniform = sample from uniform distribution [mask_other, mask_length*2]
normal = sample from normal distribution with mean mask_length and stdev mask_other. mask is min 1 element
poisson = sample from possion distribution with lambda = mask length
min_masks: minimum number of masked spans
no_overlap: if false, will switch to an alternative recursive algorithm that prevents spans from overlapping
min_space: only used if no_overlap is True, this is how many elements to keep unmasked between spans | fairseq/data/data_utils.py | compute_mask_indices | 1130310223/fairseq | python | def compute_mask_indices(shape: Tuple[(int, int)], padding_mask: Optional[torch.Tensor], mask_prob: float, mask_length: int, mask_type: str='static', mask_other: float=0.0, min_masks: int=0, no_overlap: bool=False, min_space: int=0) -> np.ndarray:
'\n Computes random mask spans for a given shape\n\n Args:\n shape: the the shape for which to compute masks.\n should be of size 2 where first element is batch size and 2nd is timesteps\n padding_mask: optional padding mask of the same size as shape, which will prevent masking padded elements\n mask_prob: probability for each token to be chosen as start of the span to be masked. this will be multiplied by\n number of timesteps divided by length of mask span to mask approximately this percentage of all elements.\n however due to overlaps, the actual number will be smaller (unless no_overlap is True)\n mask_type: how to compute mask lengths\n static = fixed size\n uniform = sample from uniform distribution [mask_other, mask_length*2]\n normal = sample from normal distribution with mean mask_length and stdev mask_other. mask is min 1 element\n poisson = sample from possion distribution with lambda = mask length\n min_masks: minimum number of masked spans\n no_overlap: if false, will switch to an alternative recursive algorithm that prevents spans from overlapping\n min_space: only used if no_overlap is True, this is how many elements to keep unmasked between spans\n '
(bsz, all_sz) = shape
mask = np.full((bsz, all_sz), False)
all_num_mask = int((((mask_prob * all_sz) / float(mask_length)) + np.random.rand()))
all_num_mask = max(min_masks, all_num_mask)
mask_idcs = []
for i in range(bsz):
if (padding_mask is not None):
sz = (all_sz - padding_mask[i].long().sum().item())
num_mask = int((((mask_prob * sz) / float(mask_length)) + np.random.rand()))
num_mask = max(min_masks, num_mask)
else:
sz = all_sz
num_mask = all_num_mask
if (mask_type == 'static'):
lengths = np.full(num_mask, mask_length)
elif (mask_type == 'uniform'):
lengths = np.random.randint(mask_other, ((mask_length * 2) + 1), size=num_mask)
elif (mask_type == 'normal'):
lengths = np.random.normal(mask_length, mask_other, size=num_mask)
lengths = [max(1, int(round(x))) for x in lengths]
elif (mask_type == 'poisson'):
lengths = np.random.poisson(mask_length, size=num_mask)
lengths = [int(round(x)) for x in lengths]
else:
raise Exception(('unknown mask selection ' + mask_type))
if (sum(lengths) == 0):
lengths[0] = min(mask_length, (sz - 1))
if no_overlap:
mask_idc = []
def arrange(s, e, length, keep_length):
span_start = np.random.randint(s, (e - length))
mask_idc.extend(((span_start + i) for i in range(length)))
new_parts = []
if (((span_start - s) - min_space) >= keep_length):
new_parts.append((s, ((span_start - min_space) + 1)))
if ((((e - span_start) - keep_length) - min_space) > keep_length):
new_parts.append((((span_start + length) + min_space), e))
return new_parts
parts = [(0, sz)]
min_length = min(lengths)
for length in sorted(lengths, reverse=True):
lens = np.fromiter((((e - s) if ((e - s) >= (length + min_space)) else 0) for (s, e) in parts), np.int)
l_sum = np.sum(lens)
if (l_sum == 0):
break
probs = (lens / np.sum(lens))
c = np.random.choice(len(parts), p=probs)
(s, e) = parts.pop(c)
parts.extend(arrange(s, e, length, min_length))
mask_idc = np.asarray(mask_idc)
else:
min_len = min(lengths)
if ((sz - min_len) <= num_mask):
min_len = ((sz - num_mask) - 1)
mask_idc = np.random.choice((sz - min_len), num_mask, replace=False)
mask_idc = np.asarray([(mask_idc[j] + offset) for j in range(len(mask_idc)) for offset in range(lengths[j])])
mask_idcs.append(np.unique(mask_idc[(mask_idc < sz)]))
min_len = min([len(m) for m in mask_idcs])
for (i, mask_idc) in enumerate(mask_idcs):
if (len(mask_idc) > min_len):
mask_idc = np.random.choice(mask_idc, min_len, replace=False)
mask[(i, mask_idc)] = True
return mask |
def raise_if_valid_subsets_unintentionally_ignored(train_cfg) -> None:
"Raises if there are paths matching 'valid*[0-9].*' which are not combined or ignored."
if (train_cfg.dataset.ignore_unused_valid_subsets or train_cfg.dataset.combine_valid_subsets or train_cfg.dataset.disable_validation or (not hasattr(train_cfg.task, 'data'))):
return
other_paths = _find_extra_valid_paths(train_cfg.task.data)
specified_subsets = train_cfg.dataset.valid_subset.split(',')
ignored_paths = [p for p in other_paths if (p not in specified_subsets)]
if ignored_paths:
advice = 'Set --combine-val to combine them or --ignore-unused-valid-subsets to ignore them.'
msg = f'Valid paths {ignored_paths} will be ignored. {advice}'
raise ValueError(msg) | 560,671,202,644,717,800 | Raises if there are paths matching 'valid*[0-9].*' which are not combined or ignored. | fairseq/data/data_utils.py | raise_if_valid_subsets_unintentionally_ignored | 1130310223/fairseq | python | def raise_if_valid_subsets_unintentionally_ignored(train_cfg) -> None:
if (train_cfg.dataset.ignore_unused_valid_subsets or train_cfg.dataset.combine_valid_subsets or train_cfg.dataset.disable_validation or (not hasattr(train_cfg.task, 'data'))):
return
other_paths = _find_extra_valid_paths(train_cfg.task.data)
specified_subsets = train_cfg.dataset.valid_subset.split(',')
ignored_paths = [p for p in other_paths if (p not in specified_subsets)]
if ignored_paths:
advice = 'Set --combine-val to combine them or --ignore-unused-valid-subsets to ignore them.'
msg = f'Valid paths {ignored_paths} will be ignored. {advice}'
raise ValueError(msg) |
@commands.command(name='xkcd', brief='send xkcd comic')
async def xkcd(self, ctx, args=None):
'\n send xkcd comic\n *xkcd -> sends newest comic\n *xkcd random -> sends random comic\n *xkcd [number] -> sends a specific comic\n '
url = None
if (not args):
url = 'http://xkcd.com/info.0.json'
elif args.isdigit():
url = f'http://xkcd.com/{int(args)}/info.0.json'
elif (args.lower() == 'random'):
(result, error) = (await get_json('http://xkcd.com/info.0.json'))
if error:
(await ctx.send(error))
return
number = randint(0, result['num'])
url = f'http://xkcd.com/{number}/info.0.json'
(result, error) = (await get_json(url))
if error:
(await ctx.send(error))
return
embed = discord.Embed(color=choice(self.colours))
embed.set_image(url=result['img'])
(await ctx.send(embed=embed)) | 5,095,829,258,922,094,000 | send xkcd comic
*xkcd -> sends newest comic
*xkcd random -> sends random comic
*xkcd [number] -> sends a specific comic | extensions/api.py | xkcd | JoseFilipeFerreira/JBB.py | python | @commands.command(name='xkcd', brief='send xkcd comic')
async def xkcd(self, ctx, args=None):
'\n send xkcd comic\n *xkcd -> sends newest comic\n *xkcd random -> sends random comic\n *xkcd [number] -> sends a specific comic\n '
url = None
if (not args):
url = 'http://xkcd.com/info.0.json'
elif args.isdigit():
url = f'http://xkcd.com/{int(args)}/info.0.json'
elif (args.lower() == 'random'):
(result, error) = (await get_json('http://xkcd.com/info.0.json'))
if error:
(await ctx.send(error))
return
number = randint(0, result['num'])
url = f'http://xkcd.com/{number}/info.0.json'
(result, error) = (await get_json(url))
if error:
(await ctx.send(error))
return
embed = discord.Embed(color=choice(self.colours))
embed.set_image(url=result['img'])
(await ctx.send(embed=embed)) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.