Beispiel #1
0
def array_dtype(a):
  """Returns the tensorflow `DType` of the array.

  Note: This is similar to doing tf.convert_to_tensor(a).dtype but not
  exactly the same. When `a` is a python scalar or a python array_like
  object, Tensorflow attempts to treat it as an int32 or float32 whereas
  numpy defaults to int64 and float64 respectively.

  Args:
    a: Could be a numpy ndarray, a Tensor or a python object that can be
      converted to numpy ndarray.

  Returns:
    A `DType`.
  """
  if isinstance(a, tf.Tensor):
    return a.dtype
  elif isinstance(a, tf.IndexedSlices):
    return a.dtype
  elif isinstance(a, np.ndarray) or isinstance(a, arrays.ndarray):
    return tf.as_dtype(a.dtype)
  elif isinstance(a, arrays.ShardedNdArray):
    return a.tensors[0].dtype
  else:
    # If this is a python object, defer to numpy to decide the dtype.
    np_dtype = np.array(a, copy=False).dtype
    np_dtype = dtypes.canonicalize_dtype(np_dtype)
    return tf.as_dtype(np_dtype)
Beispiel #2
0
def to_tf_type(dtype):
  """Converts a native python or numpy type to TF DType.

  Args:
    dtype: Could be a python type, a numpy type or a TF DType.

  Returns:
    A tensorflow `DType`.
  """
  if isinstance(dtype, tf.DType):
    return dtype
  return tf.as_dtype(dtypes.canonicalize_dtype(np.dtype(dtype)))
Beispiel #3
0
def to_numpy_type(dtype):
  """Converts a native python or TF DType to numpy type.

  Args:
    dtype: Could be a python type, a numpy type or a TF DType.

  Returns:
    A NumPy `dtype`.
  """
  if isinstance(dtype, tf.DType):
    return dtype.as_numpy_dtype
  return dtypes.canonicalize_dtype(np.dtype(dtype))
Beispiel #4
0
def promote_types(type1, type2):
  """Returns the type resulting from applying NumPy type promotion.

  Args:
    type1: A numpy type.
    type2: A numpy type.

  Returns:
    A numpy type.
  """
  type1 = _to_numpy_type(type1)
  type2 = _to_numpy_type(type2)
  return dtypes.canonicalize_dtype(np.promote_types(type1, type2))