生成one-hot编码
def encode_onehot(labels):
classes = set(labels)
classes_dict = {c: np.identity(len(classes))[i, :] for i, c in
enumerate(classes)}
labels_onehot = np.array(list(map(classes_dict.get, labels)),
dtype=np.int32)
return labels_onehot
创建对称的邻接矩阵,推导过程略,总之能把一个矩阵变换成对称的
# adj 是 coo_matrix
adj = adj + adj.T.multiply(adj.T > adj) - adj.multiply(adj.T > adj)
row normalize,防止梯度消失
一般这里有两种方式
D
−
1
A
D^{-1}A
D−1A和
D
−
1
/
2
A
D
−
1
/
2
D^{-1/2}AD^{-1/2}
D−1/2AD−1/2
下面的代码是方式1
def normalize(mx):
"""Row-normalize sparse matrix"""
rowsum = np.array(mx.sum(1)) # degree matrix
r_inv = np.power(rowsum, -1).flatten()
r_inv[np.isinf(r_inv)] = 0.
r_mat_inv = sp.diags(r_inv)
mx = r_mat_inv.dot(mx)
return mx
coo_matrix转成tensor
def sparse_mx_to_torch_sparse_tensor(sparse_mx):
"""Convert a scipy sparse matrix to a torch sparse tensor."""
sparse_mx = sparse_mx.tocoo().astype(np.float32)
indices = torch.from_numpy(
np.vstack((sparse_mx.row, sparse_mx.col)).astype(np.int64))
values = torch.from_numpy(sparse_mx.data)
shape = torch.Size(sparse_mx.shape)
return torch.sparse.FloatTensor(indices, values, shape)
计算acc
def accuracy(output, labels):
preds = output.max(1)[1].type_as(labels)
correct = preds.eq(labels).double()
correct = correct.sum()
return correct / len(labels)