예제 #1
0
def astensor(x, *, dtype=None, device=None, escape=None):

    try:
        if x is None or (escape is not None and isinstance(x, escape)):
            return x
    except TypeError:
        raise TypeError(f"argument 'escape' must be a type or tuple of types.")

    if dtype is None:
        dtype = gf.infer_type(x)

    if isinstance(dtype, (np.dtype, str)):
        dtype = data_type_dict().get(str(dtype), dtype)
    elif not isinstance(dtype, torch.dtype):
        raise TypeError(
            f"argument 'dtype' must be torch.dtype, np.dtype or str, but got {type(dtype)}."
        )

    if is_tensor(x):
        tensor = x.to(dtype)
    elif gf.is_tensor(x, backend='tensorflow'):
        return astensor(gf.tensoras(x),
                        dtype=dtype,
                        device=device,
                        escape=escape)
    elif sp.isspmatrix(x):
        if gg.backend() == "dgl_torch":
            import dgl
            tensor = dgl.from_scipy(x, idtype=getattr(torch, gg.intx()))
        elif gg.backend() == "pyg":
            edge_index, edge_weight = gf.sparse_adj_to_edge(x)
            return (astensor(edge_index,
                             dtype=gg.intx(),
                             device=device,
                             escape=escape),
                    astensor(edge_weight,
                             dtype=gg.floatx(),
                             device=device,
                             escape=escape))
        else:
            tensor = sparse_adj_to_sparse_tensor(x, dtype=dtype)
    elif any((isinstance(x, (np.ndarray, np.matrix)), gg.is_listlike(x),
              gg.is_scalar(x))):
        tensor = torch.tensor(x, dtype=dtype, device=device)
    else:
        raise TypeError(
            f"Invalid type of inputs. Allowed data type (Tensor, SparseTensor, Numpy array, Scipy sparse tensor, None), but got {type(x)}."
        )
    return tensor.to(device)
예제 #2
0
    def nx(self):
        attr_flips = self.nx_flips
        if self.modified_nx is None:
            if attr_flips is not None:
                self.modified_nx = gf.flip_attr(self.graph.node_attr,
                                                attr_flips)
            else:
                self.modified_nx = self.graph.node_attr

        x = self.modified_nx

        if sp.isspmatrix(x):
            x = x.A
        elif gf.is_anytensor(x):
            x = gf.tensoras(x)
        elif not isinstance(x, np.ndarray):
            raise TypeError(x)
        return x
예제 #3
0
def astensor(x, *, dtype=None, device=None, escape=None):

    try:
        if x is None or (escape is not None and isinstance(x, escape)):
            return x
    except TypeError:
        raise TypeError(f"argument 'escape' must be a type or tuple of types.")
    if dtype is None:
        dtype = gf.infer_type(x)
    elif isinstance(dtype, tf.dtypes.DType):
        dtype = dtype.name
    elif isinstance(dtype, (np.dtype, str)):
        dtype = str(dtype)
    else:
        raise TypeError(
            f"argument 'dtype' must be tf.dtypes.DType, np.dtype or str, but got {type(dtype)}."
        )

    with tf.device(device):
        if is_tensor(x):
            if x.dtype != dtype:
                return tf.cast(x, dtype=dtype)
            return tf.identity(x)
        elif gf.is_tensor(x, backend='torch'):
            return astensor(gf.tensoras(x),
                            dtype=dtype,
                            device=device,
                            escape=escape)
        elif sp.isspmatrix(x):
            if gg.backend() == "dgl_tf":
                import dgl
                return dgl.from_scipy(x, idtype=getattr(tf,
                                                        gg.intx())).to(device)
            else:
                return sparse_adj_to_sparse_tensor(x, dtype=dtype)
        elif any((isinstance(x, (np.ndarray, np.matrix)), gg.is_listlike(x),
                  gg.is_scalar(x))):
            return tf.convert_to_tensor(x, dtype=dtype)
        else:
            raise TypeError(
                f"Invalid type of inputs. Allowed data type(Tensor, SparseTensor, Numpy array, Scipy sparse matrix, None), but got {type(x)}."
            )
예제 #4
0
    def A(self):
        adj_flips = self.edge_flips
        if self.modified_adj is None:
            if adj_flips is not None:
                self.modified_adj = gf.flip_adj(self.graph.adj_matrix,
                                                adj_flips)
            else:
                self.modified_adj = self.graph.adj_matrix

        adj = self.modified_adj

        if gf.is_anytensor(adj):
            adj = gf.tensoras(adj)

        if isinstance(adj, np.ndarray):
            adj = sp.csr_matrix(adj)
        elif sp.isspmatrix(adj):
            adj = adj.tocsr(copy=False)
        else:
            raise TypeError(adj)

        return adj
예제 #5
0
################### Surrogate model ############################
# Nettack takes no activation layer
trainer = gg.gallery.GCN(graph, seed=42).process().build(acts=None)
his = trainer.train(splits.train_nodes,
                    splits.val_nodes,
                    verbose=1,
                    epochs=100)
# surrogate weights
if gg.backend() == "tensorflow":
    w1, w2 = trainer.model.weights
    W = w1 @ w2
else:
    w1, w2 = trainer.model.parameters()
    W = (w2 @ w1).T
W = gf.tensoras(W)

################### Attacker model ############################
target = 0
attacker = gg.attack.targeted.Nettack(graph, seed=123).process(W)
attacker.attack(target,
                direct_attack=True,
                structure_attack=True,
                feature_attack=False)

################### Victim model ############################
# Before attack
trainer = gg.gallery.GCN(graph, seed=123).process().build()
his = trainer.train(splits.train_nodes,
                    splits.val_nodes,
                    verbose=1,