Ejemplo n.º 1
0
def is_tensor(x):  # pylint: disable=invalid-name
    """Checks whether `x` is a TF-native type that can be passed to many TF ops.

  Use is_tensor to differentiate types that can ingested by TensorFlow ops
  without any conversion (e.g., `tf.Tensor`, `tf.SparseTensor`, and
  `tf.RaggedTensor`) from types that need to be converted into tensors before
  they are ingested (e.g., numpy `ndarray` and Python scalars).

  For example, in the following code block:

  ```python
  if not tf.is_tensor(t):
    t = tf.convert_to_tensor(t)
  return t.dtype
  ```

  we check to make sure that `t` is a tensor (and convert it if not) before
  accessing its `shape` and `dtype`.

  Args:
    x: A python object to check.

  Returns:
    `True` if `x` is a tensor or "tensor-like", `False` if not.
  """
    return (isinstance(x, internal.NativeObject) or ops.is_dense_tensor_like(x)
            or getattr(x, "is_tensor_like", False))
Ejemplo n.º 2
0
def is_tensor(x):  # pylint: disable=invalid-name
  """Check whether `x` is of tensor type.

  Check whether an object is a tensor. Equivalent to
  `isinstance(x, [tf.Tensor, tf.SparseTensor, tf.Variable])`.

  Args:
    x: An python object to check.

  Returns:
    `True` if `x` is a tensor, `False` if not.
  """
  return isinstance(x, ops._TensorLike) or ops.is_dense_tensor_like(x)  # pylint: disable=protected-access
Ejemplo n.º 3
0
def is_tensor(x):  # pylint: disable=invalid-name
    """Checks whether `x` is a tensor or "tensor-like".

  If `is_tensor(x)` returns `True`, it is safe to assume that `x` is a tensor or
  can be converted to a tensor using `ops.convert_to_tensor(x)`.

  Args:
    x: A python object to check.

  Returns:
    `True` if `x` is a tensor or "tensor-like", `False` if not.
  """
    return (isinstance(x, tensor_like._TensorLike) or  # pylint: disable=protected-access
            ops.is_dense_tensor_like(x) or getattr(x, "is_tensor_like", False))
Ejemplo n.º 4
0
def is_tensor(x):  # pylint: disable=invalid-name
  """Checks whether `x` is a tensor or "tensor-like".

  If `is_tensor(x)` returns `True`, it is safe to assume that `x` is a tensor or
  can be converted to a tensor using `ops.convert_to_tensor(x)`.

  Args:
    x: A python object to check.

  Returns:
    `True` if `x` is a tensor or "tensor-like", `False` if not.
  """
  return (isinstance(x, ops._TensorLike) or ops.is_dense_tensor_like(x) or  # pylint: disable=protected-access
          getattr(x, "is_tensor_like", False))
Ejemplo n.º 5
0
def is_tensor(x):  # pylint: disable=invalid-name
  """Check whether `x` is of tensor type.

  Check whether an object is a tensor. This check is equivalent to calling
  `isinstance(x, (tf.Tensor, tf.SparseTensor, tf.Variable))` and also checks
  if all the component variables of a MirroredVariable or a TowerLocalVariable
  are tensors.

  Args:
    x: A python object to check.

  Returns:
    `True` if `x` is a tensor, `False` if not.
  """
  return (isinstance(x, ops._TensorLike) or ops.is_dense_tensor_like(x) or  # pylint: disable=protected-access
          (hasattr(x, "is_tensor_like") and x.is_tensor_like))
Ejemplo n.º 6
0
def is_tensor(x):  # pylint: disable=invalid-name
    """Check whether `x` is of tensor type.

  Check whether an object is a tensor. This check is equivalent to calling
  `isinstance(x, (tf.Tensor, tf.SparseTensor, tf.Variable))` and also checks
  if all the component variables of a MirroredVariable or a TowerLocalVariable
  are tensors.

  Args:
    x: A python object to check.

  Returns:
    `True` if `x` is a tensor, `False` if not.
  """
    return (isinstance(x, ops._TensorLike) or ops.is_dense_tensor_like(x) or  # pylint: disable=protected-access
            (hasattr(x, "is_tensor_like") and x.is_tensor_like))
Ejemplo n.º 7
0
def is_tensor(x):  # pylint: disable=invalid-name
    """Checks whether `x` is a tensor or "tensor-like".

  If `is_tensor(x)` returns `True`, it is safe to assume that `x` is a tensor or
  can be converted to a tensor using `ops.convert_to_tensor(x)`.
  
  Usage example:
  
  >>> tf.is_tensor(tf.constant([[1,2,3],[4,5,6],[7,8,9]])) 
  True
  >>> tf.is_tensor("Hello World")
  False
    
  Args:
    x: A python object to check.

  Returns:
    `True` if `x` is a tensor or "tensor-like", `False` if not.
  """
    return (isinstance(x, tensor_like._TensorLike) or  # pylint: disable=protected-access
            ops.is_dense_tensor_like(x) or getattr(x, "is_tensor_like", False))
Ejemplo n.º 8
0
def _check_is_tensor(x, tensor_name):
    """Returns `x` if it is a `Tensor`, raises TypeError otherwise."""
    if not ops.is_dense_tensor_like(x):
        raise TypeError('{} must be Tensor, given: {}'.format(tensor_name, x))
    return x
Ejemplo n.º 9
0
def _check_is_tensor_or_operation(x, name):
    if not (isinstance(x, tf.Operation) or ops.is_dense_tensor_like(x)):
        raise TypeError('{} must be Operation or Tensor, given: {}'.format(
            name, x))
Ejemplo n.º 10
0
    def __init__(self, inputs=None, outputs=None, name=None):
        """
        Initializing the Model.

        Parameters
        ----------
        inputs : Tensor or list of tensors
            Input tensor(s), which must come from tl.layers.Input()
        outputs : Tensor or list of tensors
            Output tensor(s), which must be the output(s) of some TL layers
        name : str or None
            Name for this network
        """
        # Auto naming if the name is not given
        global _global_model_name_dict
        global _global_model_name_set
        if name is None:
            prefix = self.__class__.__name__.lower()
            if _global_model_name_dict.get(prefix) is not None:
                _global_model_name_dict[prefix] += 1
                name = prefix + '_' + str(_global_model_name_dict[prefix])
            else:
                _global_model_name_dict[prefix] = 0
                name = prefix
            while name in _global_model_name_set:
                _global_model_name_dict[prefix] += 1
                name = prefix + '_' + str(_global_model_name_dict[prefix])
            _global_model_name_set.add(name)
        else:
            if name in _global_model_name_set:
                raise ValueError(
                    'Model name \'%s\' has already been used by another model. Please change the model name.'
                    % name)
            _global_model_name_set.add(name)
            _global_model_name_dict[name] = 0

        # Model properties
        self.name = name

        # Model state: train or test
        self.is_train = None

        # Model weights
        self._weights = None

        # Model inputs and outputs
        # TODO: note that in dynamic network, inputs and outputs are both None, may cause problem, test needed
        self._inputs = inputs
        self._outputs = outputs

        # Model converted into a Layer
        self._model_layer = None

        # Layer Node status
        self._nodes_fixed = False

        # Model layers
        self._all_layers = None

        if inputs is None and outputs is None:
            pass

        else:
            # check type of inputs and outputs
            check_order = ['inputs', 'outputs']
            for co, check_argu in enumerate([inputs, outputs]):
                if isinstance(check_argu, tf_ops._TensorLike
                              ) or tf_ops.is_dense_tensor_like(check_argu):
                    pass
                elif isinstance(check_argu, list):
                    if len(check_argu) == 0:
                        raise ValueError(
                            "The argument `%s` is detected as an empty list. "
                            % check_order[co] +
                            "It should be either Tensor or a list of Tensor.")
                    for idx in range(len(check_argu)):
                        if not isinstance(check_argu[idx], tf_ops._TensorLike
                                          ) or not tf_ops.is_dense_tensor_like(
                                              check_argu[idx]):
                            raise TypeError(
                                "The argument `%s` should be either Tensor or a list of Tensor "
                                % (check_order[co]) +
                                "but the %s[%d] is detected as %s" %
                                (check_order[co], idx, type(check_argu[idx])))
                else:
                    raise TypeError(
                        "The argument `%s` should be either Tensor or a list of Tensor but received %s"
                        % (check_order[co], type(check_argu)))

            if not _check_tl_layer_tensors(inputs):
                raise TypeError(
                    "The argument `inputs` should be either Tensor or a list of Tensor "
                    "that come from TensorLayer's Input layer: tl.layers.Input(shape). "
                )
            if not _check_tl_layer_tensors(outputs):
                raise TypeError(
                    "The argument `outputs` should be either Tensor or a list of Tensor "
                    "that is/are outputs from some TensorLayer's layers, e.g. tl.layers.Dense, tl.layers.Conv2d."
                )

            # build network graph
            self._node_by_depth, self._all_layers = self._construct_graph()

            self._fix_nodes_for_layers()
Ejemplo n.º 11
0
def _check_is_tensor(x, tensor_name):
  """Returns `x` if it is a `Tensor`, raises TypeError otherwise."""
  if not ops.is_dense_tensor_like(x):
    raise TypeError('{} must be Tensor, given: {}'.format(tensor_name, x))
  return x
Ejemplo n.º 12
0
def _check_is_tensor_or_operation(x, name):
  if not (isinstance(x, ops.Operation) or ops.is_dense_tensor_like(x)):
    raise TypeError('{} must be Operation or Tensor, given: {}'.format(name, x))
Ejemplo n.º 13
0
 def is_tensor(x):
     return isinstance(
         x, tf_ops._TensorLike) or tf_ops.is_dense_tensor_like(x)
Ejemplo n.º 14
0
def is_tensor(node):
  try:
    # TODO(b/154650521): Use tf.Tensor instead of core.Tensor.
    return isinstance(node, core.Tensor)
  except NameError:
    return tf_ops.is_dense_tensor_like(node)
Ejemplo n.º 15
0
    def __init__(self, inputs=None, outputs=None, name=None):
        """
        Initializing the Model.

        Parameters
        ----------
        inputs : Tensor or list of tensors
            Input tensor(s), which must come from tl.layers.Input()
        outputs : Tensor or list of tensors
            Output tensor(s), which must be the output(s) of some TL layers
        name : str or None
            Name for this network
        """
        # Auto naming if the name is not given
        global _global_model_name_dict
        global _global_model_name_set
        if name is None:
            prefix = self.__class__.__name__.lower()
            if _global_model_name_dict.get(prefix) is not None:
                _global_model_name_dict[prefix] += 1
                name = prefix + '_' + str(_global_model_name_dict[prefix])
            else:
                _global_model_name_dict[prefix] = 0
                name = prefix
            while name in _global_model_name_set:
                _global_model_name_dict[prefix] += 1
                name = prefix + '_' + str(_global_model_name_dict[prefix])
            _global_model_name_set.add(name)
        else:
            if name in _global_model_name_set:
                raise ValueError(
                    'Model name \'%s\' has already been used by another model. Please change the model name.' % name
                )
            _global_model_name_set.add(name)
            _global_model_name_dict[name] = 0

        # Model properties
        self.name = name

        # Model state: train or test
        self.is_train = None

        # Model weights
        self._weights = None

        # Model inputs and outputs
        # TODO: note that in dynamic network, inputs and outputs are both None, may cause problem, test needed
        self._inputs = inputs
        self._outputs = outputs

        # Model converted into a Layer
        self._model_layer = None

        # Layer Node status
        self._nodes_fixed = False

        # Model layers
        self._all_layers = None

        if inputs is None and outputs is None:
            pass

        else:
            # check type of inputs and outputs
            check_order = ['inputs', 'outputs']
            for co, check_argu in enumerate([inputs, outputs]):
                if isinstance(check_argu, tf_ops._TensorLike) or tf_ops.is_dense_tensor_like(check_argu):
                    pass
                elif isinstance(check_argu, list):
                    if len(check_argu) == 0:
                        raise ValueError(
                            "The argument `%s` is detected as an empty list. " % check_order[co] +
                            "It should be either Tensor or a list of Tensor."
                        )
                    for idx in range(len(check_argu)):
                        if not isinstance(check_argu[idx], tf_ops._TensorLike) or not tf_ops.is_dense_tensor_like(
                                check_argu[idx]):
                            raise TypeError(
                                "The argument `%s` should be either Tensor or a list of Tensor " % (check_order[co]) +
                                "but the %s[%d] is detected as %s" % (check_order[co], idx, type(check_argu[idx]))
                            )
                else:
                    raise TypeError(
                        "The argument `%s` should be either Tensor or a list of Tensor but received %s" %
                        (check_order[co], type(check_argu))
                    )

            if not _check_tl_layer_tensors(inputs):
                raise TypeError(
                    "The argument `inputs` should be either Tensor or a list of Tensor "
                    "that come from TensorLayer's Input layer: tl.layers.Input(shape). "
                )
            if not _check_tl_layer_tensors(outputs):
                raise TypeError(
                    "The argument `outputs` should be either Tensor or a list of Tensor "
                    "that is/are outputs from some TensorLayer's layers, e.g. tl.layers.Dense, tl.layers.Conv2d."
                )

            # build network graph
            self._node_by_depth, self._all_layers = self._construct_graph()

            self._fix_nodes_for_layers()
Ejemplo n.º 16
0
def is_tensor(x):
    return isinstance(x, tf_ops._TensorLike) or \
           tf_ops.is_dense_tensor_like(x) or \
           isinstance(x, tf.SparseTensor)
Ejemplo n.º 17
0
def is_tensor(node):
    # return (isinstance(node, (tf.Tensor, tf.Variable))
    #         or resource_variable_ops.is_resource_variable(node))
    return tf_ops.is_dense_tensor_like(node)