Python tensorflow.compat.v2.identity() Examples

The following are 9 code examples of tensorflow.compat.v2.identity(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module tensorflow.compat.v2 , or try the search function .
Example #1
Source File: array_ops.py    From trax with Apache License 2.0 5 votes vote down vote up
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) 
Example #2
Source File: arrays.py    From trax with Apache License 2.0 5 votes vote down vote up
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 
Example #3
Source File: gam.py    From ranking with Apache License 2.0 5 votes vote down vote up
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 
Example #4
Source File: tensor_wrapper.py    From tf-quant-finance with Apache License 2.0 5 votes vote down vote up
def identity(self):
    """See tf.identity."""
    return self._apply_op(tf.identity) 
Example #5
Source File: date_tensor.py    From tf-quant-finance with Apache License 2.0 5 votes vote down vote up
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) 
Example #6
Source File: mt_agent.py    From valan with Apache License 2.0 5 votes vote down vote up
def grad_reverse(x):
  y = tf.identity(x)

  def custom_grad(dy):
    return -dy * _LAMBDA_VAL

  return y, custom_grad 
Example #7
Source File: exporter_lib_tf2_test.py    From models with Apache License 2.0 5 votes vote down vote up
def preprocess(self, inputs):
    true_image_shapes = []  # Doesn't matter for the fake model.
    return tf.identity(inputs), true_image_shapes 
Example #8
Source File: array_ops.py    From trax with Apache License 2.0 4 votes vote down vote up
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) 
Example #9
Source File: date_tensor.py    From tf-quant-finance with Apache License 2.0 4 votes vote down vote up
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)