本文整理汇总了Python中tensorflow.compat.v2.identity方法的典型用法代码示例。如果您正苦于以下问题:Python v2.identity方法的具体用法?Python v2.identity怎么用?Python v2.identity使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类tensorflow.compat.v2
的用法示例。
在下文中一共展示了v2.identity方法的9个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: identity
# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import identity [as 别名]
def identity(n, dtype=float):
"""Returns a square array with ones on the main diagonal and zeros elsewhere.
Args:
n: number of rows/cols.
dtype: Optional, defaults to float. The type of the resulting ndarray. Could
be a python type, a NumPy type or a TensorFlow `DType`.
Returns:
An ndarray of shape (n, n) and requested type.
"""
return eye(N=n, M=n, dtype=dtype)
示例2: ndarray_to_tensor
# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import identity [as 别名]
def ndarray_to_tensor(arr, dtype=None, name=None, as_ref=False):
if as_ref:
raise ValueError('as_ref is not supported.')
if dtype and tf.as_dtype(arr.dtype) != dtype:
return tf.cast(arr.data, dtype)
result_t = arr.data
if name:
result_t = tf.identity(result_t, name=name)
return result_t
示例3: _make_tower_layers
# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import identity [as 别名]
def _make_tower_layers(hidden_layer_dims,
output_units,
activation=None,
use_batch_norm=True,
batch_norm_moment=0.999,
dropout=0.5):
"""Defines tower using keras layers.
Args:
hidden_layer_dims: Iterable of number hidden units per layer.
All layers are fully connected. Ex. `[64, 32]` means first layer has 64
nodes and second one has 32.
output_units: (int) Size of output logits from this tower.
activation: Activation function applied to each layer. If `None`, will use
an identity activation, which is default behavior in Keras activations.
use_batch_norm: Whether to use batch normalization after each hidden layer.
batch_norm_moment: Momentum for the moving average in batch normalization.
dropout: When not `None`, the probability we will drop out a given
coordinate.
Returns:
A list of Keras layers for this tower.
"""
layers = []
if not hidden_layer_dims:
return layers
if use_batch_norm:
layers.append(
tf.keras.layers.BatchNormalization(momentum=batch_norm_moment))
for layer_width in hidden_layer_dims:
layers.append(tf.keras.layers.Dense(units=layer_width))
if use_batch_norm:
layers.append(
tf.keras.layers.BatchNormalization(momentum=batch_norm_moment))
layers.append(tf.keras.layers.Activation(activation=activation))
if dropout:
layers.append(tf.keras.layers.Dropout(rate=dropout))
layers.append(tf.keras.layers.Dense(units=output_units))
return layers
示例4: identity
# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import identity [as 别名]
def identity(self):
"""See tf.identity."""
return self._apply_op(tf.identity)
示例5: from_ordinals
# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import identity [as 别名]
def from_ordinals(ordinals, validate=True):
"""Creates DateTensor from tensors of ordinals.
Args:
ordinals: Tensor of type int32. Each value is number of days since 1 Jan
0001. 1 Jan 0001 has `ordinal=1`.
validate: Whether to validate the dates.
Returns:
DateTensor object.
#### Example
```python
ordinals = tf.constant([
735703, # 2015-4-12
736693 # 2017-12-30
], dtype=tf.int32)
date_tensor = tff.datetime.dates_from_ordinals(ordinals)
```
"""
ordinals = tf.convert_to_tensor(ordinals, dtype=tf.int32)
control_deps = []
if validate:
control_deps.append(
tf.debugging.assert_positive(
ordinals, message="Ordinals must be positive."))
with tf.compat.v1.control_dependencies(control_deps):
ordinals = tf.identity(ordinals)
with tf.compat.v1.control_dependencies(control_deps):
years, months, days = date_utils.ordinal_to_year_month_day(ordinals)
return DateTensor(ordinals, years, months, days)
示例6: grad_reverse
# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import identity [as 别名]
def grad_reverse(x):
y = tf.identity(x)
def custom_grad(dy):
return -dy * _LAMBDA_VAL
return y, custom_grad
示例7: preprocess
# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import identity [as 别名]
def preprocess(self, inputs):
true_image_shapes = [] # Doesn't matter for the fake model.
return tf.identity(inputs), true_image_shapes
示例8: array
# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import identity [as 别名]
def array(val, dtype=None, copy=True, ndmin=0): # pylint: disable=redefined-outer-name
"""Creates an ndarray with the contents of val.
Args:
val: array_like. Could be an ndarray, a Tensor or any object that can be
converted to a Tensor using `tf.convert_to_tensor`.
dtype: Optional, defaults to dtype of the `val`. The type of the resulting
ndarray. Could be a python type, a NumPy type or a TensorFlow `DType`.
copy: Determines whether to create a copy of the backing buffer. Since
Tensors are immutable, a copy is made only if val is placed on a different
device than the current one. Even if `copy` is False, a new Tensor may
need to be built to satisfy `dtype` and `ndim`. This is used only if `val`
is an ndarray or a Tensor.
ndmin: The minimum rank of the returned array.
Returns:
An ndarray.
"""
if dtype:
dtype = utils.result_type(dtype)
if isinstance(val, arrays_lib.ndarray):
result_t = val.data
else:
result_t = val
if copy and isinstance(result_t, tf.Tensor):
# Note: In eager mode, a copy of `result_t` is made only if it is not on
# the context device.
result_t = tf.identity(result_t)
if not isinstance(result_t, tf.Tensor):
if not dtype:
dtype = utils.result_type(result_t)
# We can't call `convert_to_tensor(result_t, dtype=dtype)` here because
# convert_to_tensor doesn't allow incompatible arguments such as (5.5, int)
# while np.array allows them. We need to convert-then-cast.
def maybe_data(x):
if isinstance(x, arrays_lib.ndarray):
return x.data
return x
# Handles lists of ndarrays
result_t = tf.nest.map_structure(maybe_data, result_t)
result_t = arrays_lib.convert_to_tensor(result_t)
result_t = tf.cast(result_t, dtype=dtype)
elif dtype:
result_t = tf.cast(result_t, dtype)
ndims = tf.rank(result_t)
def true_fn():
old_shape = tf.shape(result_t)
new_shape = tf.concat([tf.ones(ndmin - ndims, tf.int32), old_shape], axis=0)
return tf.reshape(result_t, new_shape)
result_t = utils.cond(utils.greater(ndmin, ndims), true_fn, lambda: result_t)
return arrays_lib.tensor_to_ndarray(result_t)
示例9: from_year_month_day
# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import identity [as 别名]
def from_year_month_day(year, month, day, validate=True):
"""Creates DateTensor from tensors of years, months and days.
Args:
year: Tensor of int32 type. Elements should be positive.
month: Tensor of int32 type of same shape as `year`. Elements should be in
range `[1, 12]`.
day: Tensor of int32 type of same shape as `year`. Elements should be in
range `[1, 31]` and represent valid dates together with corresponding
elements of `month` and `year` Tensors.
validate: Whether to validate the dates.
Returns:
DateTensor object.
#### Example
```python
year = tf.constant([2015, 2017], dtype=tf.int32)
month = tf.constant([4, 12], dtype=tf.int32)
day = tf.constant([15, 30], dtype=tf.int32)
date_tensor = tff.datetime.dates_from_year_month_day(year, month, day)
```
"""
year = tf.convert_to_tensor(year, tf.int32)
month = tf.convert_to_tensor(month, tf.int32)
day = tf.convert_to_tensor(day, tf.int32)
control_deps = []
if validate:
control_deps.append(
tf.debugging.assert_positive(year, message="Year must be positive."))
control_deps.append(
tf.debugging.assert_greater_equal(
month,
constants.Month.JANUARY.value,
message=f"Month must be >= {constants.Month.JANUARY.value}"))
control_deps.append(
tf.debugging.assert_less_equal(
month,
constants.Month.DECEMBER.value,
message="Month must be <= {constants.Month.JANUARY.value}"))
control_deps.append(
tf.debugging.assert_positive(day, message="Day must be positive."))
is_leap = date_utils.is_leap_year(year)
days_in_months = tf.constant(_DAYS_IN_MONTHS_COMBINED, tf.int32)
max_days = tf.gather(days_in_months,
month + 12 * tf.dtypes.cast(is_leap, np.int32))
control_deps.append(
tf.debugging.assert_less_equal(
day, max_days, message="Invalid day-month pairing."))
with tf.compat.v1.control_dependencies(control_deps):
# Ensure years, months, days themselves are under control_deps.
year = tf.identity(year)
month = tf.identity(month)
day = tf.identity(day)
with tf.compat.v1.control_dependencies(control_deps):
ordinal = date_utils.year_month_day_to_ordinal(year, month, day)
return DateTensor(ordinal, year, month, day)