Пример #1
0
def array(val, dtype=None, copy=True, ndmin=0):
    """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.to_tf_type(dtype)
    if isinstance(val, arrays.ndarray):
        result_t = val.data
    else:
        result_t = val

    if isinstance(result_t, tf.Tensor):
        # Copy only if copy=True and a copy would not otherwise be made to satisfy
        # dtype or ndmin.
        if (copy and (dtype is None or dtype == utils.array_dtype(val))
                and val.ndim >= ndmin):
            # 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):
        # Note: We don't just call tf.convert_to_tensor because, unlike NumPy,
        # TensorFlow prefers int32 and float32 over int64 and float64. So we compute
        # the NumPy type of `result_t` and create a tensor of that type instead.
        if not dtype:
            dtype = utils.array_dtype(result_t)
        result_t = tf.convert_to_tensor(result_t)
        result_t = tf.cast(result_t, dtype=dtype)
    elif dtype:
        result_t = utils.maybe_cast(result_t, dtype)
    ndims = len(result_t.shape)
    if ndmin > ndims:
        old_shape = list(result_t.shape)
        new_shape = [1 for _ in range(ndmin - ndims)] + old_shape
        result_t = tf.reshape(result_t, new_shape)
    return utils.tensor_to_ndarray(result_t)
Пример #2
0
def arange(start, stop=None, step=1, dtype=None):
    """Returns `step`-separated values in the range [start, stop).

  Args:
    start: Start of the interval. Included in the range.
    stop: End of the interval. If not specified, `start` is treated as 0 and
      `start` value is used as `stop`. If specified, it is not included in the
      range if `step` is integer. When `step` is floating point, it may or may
      not be included.
    step: The difference between 2 consecutive values in the output range.
      It is recommended to use `linspace` instead of using non-integer values
      for `step`.
    dtype: Optional. Type of the resulting ndarray. Could be a python type, a
      NumPy type or a TensorFlow `DType`. If not provided, the largest type of
      `start`, `stop`, `step` is used.

  Raises:
    ValueError: If step is zero.
  """
    if not step:
        raise ValueError('step must be non-zero.')
    if dtype:
        dtype = utils.to_tf_type(dtype)
    else:
        dtype = utils.result_type(
            utils.array_dtype(start).as_numpy_dtype,
            utils.array_dtype(step).as_numpy_dtype)
        if stop is not None:
            dtype = utils.result_type(dtype,
                                      utils.array_dtype(stop).as_numpy_dtype)
        dtype = utils.to_tf_type(dtype)
    if step > 0 and ((stop is not None and start > stop) or
                     (stop is None and start < 0)):
        return array([], dtype=dtype)
    if step < 0 and ((stop is not None and start < stop) or
                     (stop is None and start > 0)):
        return array([], dtype=dtype)
    # TODO(srbs): There are some bugs when start or stop is float type and dtype
    # is integer type.
    return utils.tensor_to_ndarray(
        tf.cast(tf.range(start, limit=stop, delta=step), dtype=dtype))
Пример #3
0
def zeros_like(a, dtype=None):
    """Returns an array of zeros with the shape and type of the input array.

  Args:
    a: array_like. Could be an ndarray, a Tensor or any object that can
      be converted to a Tensor using `tf.convert_to_tensor`.
    dtype: Optional, defaults to dtype of the input array. The type of the
      resulting ndarray. Could be a python type, a NumPy type or a TensorFlow
      `DType`.

  Returns:
    An ndarray.
  """
    if isinstance(a, arrays.ndarray):
        a = a.data
    if dtype is None:
        dtype = utils.array_dtype(a)
    else:
        dtype = utils.to_tf_type(dtype)
    return utils.tensor_to_ndarray(tf.zeros_like(a, dtype))
Пример #4
0
def full_like(a, fill_value, dtype=None):
    """Returns an array with same shape and dtype as `a` filled with `fill_value`.

  Args:
    a: array_like. Could be an ndarray, a Tensor or any object that
      can be converted to a Tensor using `tf.convert_to_tensor`.
    fill_value: 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 `a`. The type of the
      resulting ndarray. Could be a python type, a NumPy type or a TensorFlow
      `DType`.

  Returns:
    An ndarray.

  Raises:
    ValueError: if `fill_value` can not be broadcast to shape `shape`.
  """
    if not isinstance(a, arrays.ndarray):
        a = array(a, copy=False)
    dtype = dtype or utils.array_dtype(a)
    return full(a.shape, fill_value, dtype)