Exemple #1
0
def createMultiGraphDataset(X1, X2, y):
    """
    Create the graph dataset for the multi-channel signals
    """
    Xg = []
    for k in range(X1.shape[0]):
        W1 = X1[k]
        W2 = X2[k]

        edge_index = np.empty((2, 0))
        edge_attr = np.empty((0, 2))
        for i in range(8):
            for j in range(8):
                if W1[i, j] == 0 and W2[i, j] == 0:
                    continue
                else:
                    ei = np.array([i, j]).reshape(2, 1)
                    ea = np.array([W1[i, j], W2[i, j]]).reshape(1, 2)
                    edge_index = np.hstack((edge_index, ei))
                    edge_attr = np.vstack((edge_attr, ea))

        edge_index = torch.tensor(edge_index, dtype=torch.long)
        edge_attr = torch.tensor(edge_attr.squeeze())
        edge_index, edge_attr = remove_self_loops(edge_index, edge_attr)
        x = torch.tensor(np.identity(8), dtype=torch.float)
        yg = torch.tensor([y[k]], dtype=torch.long)
        data = Data(x=x, edge_index=edge_index, edge_attr=edge_attr, y=yg)
        Xg.append(data)
    return Xg
Exemple #2
0
def recon_loss(z, pos_edge_index, neg_edge_index=None):
    r"""Given latent variables :obj:`z`, computes the binary cross
    entropy loss for positive edges :obj:`pos_edge_index` and negative
    sampled edges.
    Args:
        z (Tensor): The latent space :math:`\mathbf{Z}`.
        pos_edge_index (LongTensor): The positive edges to train against.
        neg_edge_index (LongTensor, optional): The negative edges to train
            against. If not given, uses negative sampling to calculate
            negative edges. (default: :obj:`None`)
    """
    EPS = 1e-15
    decoder = InnerProductDecoder()

    pos_loss = -torch.log(decoder(z, pos_edge_index, sigmoid=True) +
                          EPS).mean()

    # Do not include self-loops in negative samples
    pos_edge_index, _ = remove_self_loops(pos_edge_index)
    pos_edge_index, _ = add_self_loops(pos_edge_index)
    if neg_edge_index is None:
        neg_edge_index = negative_sampling(pos_edge_index, z.size(0))
    neg_loss = -torch.log(1 - decoder(z, neg_edge_index, sigmoid=True) +
                          EPS).mean()

    return pos_loss + neg_loss
def construct_edge(graph_dict, num_nodes):
    row, col = [], []
    for key, value in graph_dict.items():
        row += repeat(key, len(value))
        col += value
    edge_index = torch.stack([torch.tensor(row), torch.tensor(col)], dim=0)
    edge_index, _ = loop.remove_self_loops(edge_index)   # 去除重复的边
    edge_index, _ = coalesce(edge_index, None, num_nodes, num_nodes)
    return edge_index
Exemple #4
0
def createGraphDataset(X, y):
    """
    Create the graph dataset for the multi-channel signals
    """
    Xg = []
    for i in range(X.shape[0]):
        W = X[i]
        A = coo_matrix(W)
        edge_index, edge_attr = from_scipy_sparse_matrix(A)
        edge_index, edge_attr = remove_self_loops(edge_index, edge_attr)
        x = torch.tensor(np.identity(8), dtype=torch.float)
        yg = torch.tensor([y[i]], dtype=torch.long)
        data = Data(x=x, edge_index=edge_index, edge_attr=edge_attr, y=yg)
        Xg.append(data)
    return Xg
Exemple #5
0
    def forward(self,
                x: Union[Tensor, OptPairTensor],
                edge_index: Adj,
                edge_weight: OptTensor = None,
                **kwargs) -> Tensor:
        """"""
        self.num_nodes = x.shape[0]
        if isinstance(x, Tensor):
            x: OptPairTensor = (x, x)

        # propagate_type: (x: OptPairTensor)
        if edge_weight is not None:
            self.edge_weight = edge_weight
            assert edge_weight.shape[0] == edge_index.shape[1]
            self.reweight = False
        else:
            edge_index, _ = remove_self_loops(edge_index)
            self_loop_edge_index, _ = add_self_loops(edge_index,
                                                     num_nodes=self.num_nodes)
            if self_loop_edge_index.shape[1] != edge_index.shape[1]:
                edge_index = self_loop_edge_index
            self.reweight = True
        out = self.propagate(edge_index, x=x[0], size=None)

        if data_args.task == 'explain':
            layer_extractor = []
            hooks = []

            def register_hook(module: nn.Module):
                if not list(module.children()):
                    hooks.append(module.register_forward_hook(forward_hook))

            def forward_hook(module: nn.Module, input: Tuple[Tensor],
                             output: Tensor):
                # input contains x and edge_index
                layer_extractor.append((module, input[0], output))

            # --- register hooks ---
            self.nn.apply(register_hook)

            nn_out = self.nn(out)

            for hook in hooks:
                hook.remove()

            fc_steps = []
            step = {'input': None, 'module': [], 'output': None}
            for layer in layer_extractor:
                if isinstance(layer[0], nn.Linear):
                    if step['module']:
                        fc_steps.append(step)
                    # step = {'input': layer[1], 'module': [], 'output': None}
                    step = {'input': None, 'module': [], 'output': None}
                step['module'].append(layer[0])
                if kwargs.get('probe'):
                    step['output'] = layer[2]
                else:
                    step['output'] = None

            if step['module']:
                fc_steps.append(step)
            self.fc_steps = fc_steps
        else:
            nn_out = self.nn(out)

        return nn_out
Exemple #6
0
dic2 = sio.loadmat(
    'graph_data/subject_1001_Ashwin/smoothSignal_test_graph_topologies.mat')
X2 = dic2['W']
y2 = dic2['y'].squeeze()

## creating the graph dataset using the TMA first order terms of each channel
graphTrainDataset = []

for i in range(X_train.shape[0]):
    tma = X_train[i, ...].squeeze()
    x = torch.tensor(tma, dtype=torch.float)
    y = torch.tensor([y_train[i]], dtype=torch.long)
    W = X1[i]
    A = coo_matrix(W)
    edge_index, edge_attr = from_scipy_sparse_matrix(A)
    edge_index, edge_attr = remove_self_loops(edge_index, edge_attr)
    data = Data(x=x, edge_index=edge_index, edge_attr=edge_attr, y=y)
    graphTrainDataset.append(data)

graphTestDataset = []

for i in range(X_test.shape[0]):
    tma = X_test[i, ...].squeeze()
    x = torch.tensor(tma, dtype=torch.float)
    y = torch.tensor([y_test[i]], dtype=torch.long)
    W = X2[i]
    A = coo_matrix(W)
    edge_index, edge_attr = from_scipy_sparse_matrix(A)
    edge_index, edge_attr = remove_self_loops(edge_index, edge_attr)
    data = Data(x=x, edge_index=edge_index, edge_attr=edge_attr, y=y)
    graphTestDataset.append(data)