Esempio n. 1
0
def infer_type(x: Any) -> str:
    """Infer the type of the input 'x'.

    Parameters:
    ----------
    x: Any python object

    Returns:
    ----------
    dtype: string, the proper data type of 'x':
        1. 'graphgallery.floatx()' if 'x' is floating,
        2. 'graphgallery.intx()' if 'x' is integer,
        3. 'graphgallery.boolx()' if 'x' is boolean.
    """
    # For tensor or variable
    if pytorch.is_tensor(x):
        if x.dtype.is_floating_point:
            return gg.floatx()
        elif x.dtype == torch.bool:
            return gg.boolx()
        elif 'int' in str(x.dtype):
            return gg.intx()
        else:
            raise TypeError(f"Invalid type of pytorch Tensor: '{type(x)}'")

    elif tensorflow.is_tensor(x):
        if x.dtype.is_floating:
            return gg.floatx()
        elif x.dtype.is_integer or x.dtype.is_unsigned:
            return gg.intx()
        elif x.dtype.is_bool:
            return gg.boolx()
        else:
            raise TypeError(f"Invalid type of tensorflow Tensor: '{type(x)}'")

    _x = x
    if not hasattr(_x, 'dtype'):
        _x = np.asarray(_x)

    if _x.dtype.kind in {'f', 'c'}:
        return gg.floatx()
    elif _x.dtype.kind in {'i', 'u'}:
        return gg.intx()
    elif _x.dtype.kind == 'b':
        return gg.boolx()
    elif _x.dtype.kind == 'O':
        raise TypeError(f"Invalid inputs of '{x}'.")
    else:
        raise TypeError(f"Invalid input of '{type(x).__name__}'.")
Esempio n. 2
0
    def __init__(self, *, device="cpu", seed=None, name=None, **kwargs):
        """
        Parameters:
        ----------
        device: string. optional
            The device where the model running on.
        seed: interger scalar. optional
            Used to create a reproducible sequence of tensors
            across multiple calls.
        name: string. optional
            Specified name for the model. (default: :str: `class name`)
        kwargs: other custom keyword arguments. 
        """
        # if graph is not None and not isinstance(graph, gg.data.BaseGraph):
        #     raise ValueError(f"Unrecognized graph: {graph}.")

        kwargs.pop("self", None)
        kwargs.pop("__class__", None)

        cfg = gg.CfgNode()
        cfg.merge_from_dict(kwargs)
        cfg.intx = self.intx = gg.intx()
        cfg.floatx = self.floatx = gg.floatx()
        cfg.boolx = self.boolx = gg.boolx()
        cfg.seed = self.seed = seed
        cfg.name = self.name = name or self.__class__.__name__
        cfg.device = device
        _backend = gg.backend()
        cfg.backend = getattr(_backend, "name", None)

        if seed:
            gf.random_seed(seed, _backend)

        self.device = gf.device(device, _backend)
        self.data_device = self.device
        self.backend = _backend

        # data types, default: `float32`,`int32` and `bool`
        self._cache = gf.BunchDict()
        self.transform = gf.BunchDict()

        self._model = None
        self._graph = None
        self.cfg = cfg
        self.setup_cfg()
        self.custom_setup()
Esempio n. 3
0
    def __init__(self, *graph, device="cpu:0", seed=None, name=None, **kwargs):
        """

        Parameters:
        ----------
            graph: Graph or MultiGraph, or a dict of them.
            device: string. optional
                The device where the model running on.
            seed: interger scalar. optional
                Used in combination with `tf.random.set_seed` & `np.random.seed`
                & `random.seed` to create a reproducible sequence of tensors
                across multiple calls.
            name: string. optional
                Specified name for the model. (default: :str: `class.__name__`)
            kwargs: other custom keyword parameters.

        """
        graph = parse_graph_inputs(*graph)
        _backend = gg.backend()

        gg.utils.raise_error.raise_if_kwargs(kwargs)

        if seed is not None:
            np.random.seed(seed)
            random.seed(seed)
            if _backend == "torch":
                torch.manual_seed(seed)
                torch.cuda.manual_seed(seed)
                # torch.cuda.manual_seed_all(seed)
            else:
                tf.random.set_seed(seed)

        if name is None:
            name = self.__class__.__name__

        self.seed = seed
        self.name = name
        self.graph = graph.copy()
        self.device = gg.functional.device(device, _backend)
        self.backend = _backend

        # data types, default: `float32`,`int32` and `bool`
        self.floatx = gg.floatx()
        self.intx = gg.intx()
        self.boolx = gg.boolx()
Esempio n. 4
0
    def __init__(self, graph, device="cpu", seed=None, name=None, **kwargs):
        """

        Parameters:
        ----------
        graph: Graph or MultiGraph.
        device: string. optional
            The device where the model running on.
        seed: interger scalar. optional
            Used in combination with `tf.random.set_seed` & `np.random.seed`
            & `random.seed` to create a reproducible sequence of tensors
            across multiple calls.
        name: string. optional
            Specified name for the model. (default: :str: `class.__name__`)
        kwargs: other custom keyword arguments. 
        """
        if not isinstance(graph, gg.data.BaseGraph):
            raise ValueError(f"Unrecognized graph: {graph}.")

        _backend = gg.backend()

        # It currently takes no keyword arguments
        gg.utils.raise_error.raise_if_kwargs(kwargs)

        if seed:
            gf.random_seed(seed, _backend)

        if name is None:
            name = self.__class__.__name__

        self.seed = seed
        self.name = name
        self.graph = graph.copy()
        self.device = gf.device(device, _backend)
        self.backend = _backend

        # data types, default: `float32`,`int32` and `bool`
        self.floatx = gg.floatx()
        self.intx = gg.intx()
        self.boolx = gg.boolx()
        self._cache = gf.BunchDict()
Esempio n. 5
0
def index_to_mask(indices: np.ndarray, shape: tuple) -> np.ndarray:
    mask = np.zeros(shape, dtype=gg.boolx())
    mask[indices] = True
    return mask