|
| 1 | +# !/usr/bin/env python |
| 2 | +# -*- encoding: utf-8 -*- |
| 3 | + |
| 4 | +import os |
| 5 | +# os.environ['CUDA_VISIBLE_DEVICES'] = '0' |
| 6 | +# os.environ['TL_BACKEND'] = 'torch' |
| 7 | +os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' |
| 8 | +# 0:Output all; 1:Filter out INFO; 2:Filter out INFO and WARNING; 3:Filter out INFO, WARNING, and ERROR |
| 9 | + |
| 10 | +import yaml |
| 11 | +import argparse |
| 12 | +import tensorlayerx as tlx |
| 13 | +from gammagl.datasets import Planetoid, Amazon |
| 14 | +from gammagl.models import MLP |
| 15 | +from gammagl.utils import mask_to_index |
| 16 | +from tensorlayerx.model import TrainOneStep, WithLoss |
| 17 | + |
| 18 | + |
| 19 | +class SemiSpvzLoss(WithLoss): |
| 20 | + def __init__(self, net, loss_fn): |
| 21 | + super(SemiSpvzLoss, self).__init__(backbone=net, loss_fn=loss_fn) |
| 22 | + |
| 23 | + def forward(self, data, teacher_logits): |
| 24 | + student_logits = self.backbone_network(data['x']) |
| 25 | + train_y = tlx.gather(data['y'], data['t_idx']) |
| 26 | + train_teacher_logits = tlx.gather(teacher_logits, data['t_idx']) |
| 27 | + train_student_logits = tlx.gather(student_logits, data['t_idx']) |
| 28 | + loss = self._loss_fn(train_y, train_student_logits, train_teacher_logits, args.lamb) |
| 29 | + return loss |
| 30 | + |
| 31 | + |
| 32 | +def get_training_config(config_path, model_name, dataset): |
| 33 | + with open(config_path, "r") as conf: |
| 34 | + full_config = yaml.load(conf, Loader=yaml.FullLoader) |
| 35 | + dataset_specific_config = full_config["global"] |
| 36 | + model_specific_config = full_config[dataset][model_name] |
| 37 | + |
| 38 | + if model_specific_config is not None: |
| 39 | + specific_config = dict(dataset_specific_config, **model_specific_config) |
| 40 | + else: |
| 41 | + specific_config = dataset_specific_config |
| 42 | + |
| 43 | + specific_config["model_name"] = model_name |
| 44 | + return specific_config |
| 45 | + |
| 46 | + |
| 47 | +def calculate_acc(logits, y, metrics): |
| 48 | + metrics.update(logits, y) |
| 49 | + rst = metrics.result() |
| 50 | + metrics.reset() |
| 51 | + return rst |
| 52 | + |
| 53 | + |
| 54 | +def kl_divergence(teacher_logits, student_logits): |
| 55 | + # convert logits to probabilities |
| 56 | + teacher_probs = tlx.softmax(teacher_logits) |
| 57 | + student_probs = tlx.softmax(student_logits) |
| 58 | + # compute KL divergence |
| 59 | + kl_div = tlx.reduce_sum(teacher_probs * (tlx.log(teacher_probs+1e-10) - tlx.log(student_probs+1e-10)), axis=-1) |
| 60 | + return tlx.reduce_mean(kl_div) |
| 61 | + |
| 62 | + |
| 63 | +def cal_mlp_loss(labels, student_logits, teacher_logits, lamb): |
| 64 | + loss_l = tlx.losses.softmax_cross_entropy_with_logits(student_logits, labels) |
| 65 | + loss_t = kl_divergence(teacher_logits, student_logits) |
| 66 | + return lamb * loss_l + (1 - lamb) * loss_t |
| 67 | + |
| 68 | + |
| 69 | +def train_student(args): |
| 70 | + # load datasets |
| 71 | + if str.lower(args.dataset) not in ['cora','pubmed','citeseer','computers','photo']: |
| 72 | + raise ValueError('Unknown dataset: {}'.format(args.dataset)) |
| 73 | + if args.dataset in ['cora', 'pubmed', 'citeseer']: |
| 74 | + dataset = Planetoid(args.dataset_path, args.dataset) |
| 75 | + elif args.dataset == 'computers': |
| 76 | + dataset = Amazon(args.dataset_path, args.dataset, train_ratio=200/13752, val_ratio=(200/13752)*1.5) |
| 77 | + elif args.dataset == 'photo': |
| 78 | + dataset = Amazon(args.dataset_path, args.dataset, train_ratio=160/7650, val_ratio=(160/7650)*1.5) |
| 79 | + graph = dataset[0] |
| 80 | + |
| 81 | + # load teacher_logits from .npy file |
| 82 | + teacher_logits = tlx.files.load_npy_to_any(path = r'./', name = f'{args.dataset}_{args.teacher}_logits.npy') |
| 83 | + teacher_logits = tlx.ops.convert_to_tensor(teacher_logits) |
| 84 | + |
| 85 | + # for mindspore, it should be passed into node indices |
| 86 | + train_idx = mask_to_index(graph.train_mask) |
| 87 | + test_idx = mask_to_index(graph.test_mask) |
| 88 | + val_idx = mask_to_index(graph.val_mask) |
| 89 | + t_idx = tlx.concat([train_idx, test_idx, val_idx], axis=0) |
| 90 | + |
| 91 | + net = MLP(in_channels=dataset.num_node_features, |
| 92 | + hidden_channels=conf["hidden_dim"], |
| 93 | + out_channels=dataset.num_classes, |
| 94 | + num_layers=conf["num_layers"], |
| 95 | + act=tlx.nn.ReLU(), |
| 96 | + norm=None, |
| 97 | + dropout=float(conf["dropout_ratio"])) |
| 98 | + |
| 99 | + optimizer = tlx.optimizers.Adam(lr=conf["learning_rate"], weight_decay=conf["weight_decay"]) |
| 100 | + metrics = tlx.metrics.Accuracy() |
| 101 | + train_weights = net.trainable_weights |
| 102 | + |
| 103 | + loss_func = SemiSpvzLoss(net, cal_mlp_loss) |
| 104 | + train_one_step = TrainOneStep(loss_func, optimizer, train_weights) |
| 105 | + |
| 106 | + data = { |
| 107 | + "x": graph.x, |
| 108 | + "y": graph.y, |
| 109 | + "train_idx": train_idx, |
| 110 | + "test_idx": test_idx, |
| 111 | + "val_idx": val_idx, |
| 112 | + "t_idx": t_idx |
| 113 | + } |
| 114 | + |
| 115 | + best_val_acc = 0 |
| 116 | + for epoch in range(args.n_epoch): |
| 117 | + net.set_train() |
| 118 | + train_loss = train_one_step(data, teacher_logits) |
| 119 | + net.set_eval() |
| 120 | + logits = net(data['x']) |
| 121 | + val_logits = tlx.gather(logits, data['val_idx']) |
| 122 | + val_y = tlx.gather(data['y'], data['val_idx']) |
| 123 | + val_acc = calculate_acc(val_logits, val_y, metrics) |
| 124 | + |
| 125 | + print("Epoch [{:0>3d}] ".format(epoch+1)\ |
| 126 | + + " train loss: {:.4f}".format(train_loss.item())\ |
| 127 | + + " val acc: {:.4f}".format(val_acc)) |
| 128 | + |
| 129 | + # save best model on evaluation set |
| 130 | + if val_acc > best_val_acc: |
| 131 | + best_val_acc = val_acc |
| 132 | + net.save_weights(args.best_model_path+args.dataset+"_"+args.teacher+"_MLP.npz", format='npz_dict') |
| 133 | + |
| 134 | + net.load_weights(args.best_model_path+args.dataset+"_"+args.teacher+"_MLP.npz", format='npz_dict') |
| 135 | + net.set_eval() |
| 136 | + logits = net(data['x']) |
| 137 | + test_logits = tlx.gather(logits, data['test_idx']) |
| 138 | + test_y = tlx.gather(data['y'], data['test_idx']) |
| 139 | + test_acc = calculate_acc(test_logits, test_y, metrics) |
| 140 | + print("Test acc: {:.4f}".format(test_acc)) |
| 141 | + |
| 142 | + |
| 143 | + |
| 144 | +if __name__ == '__main__': |
| 145 | + # parameters setting |
| 146 | + parser = argparse.ArgumentParser() |
| 147 | + parser.add_argument("--model_config_path",type=str,default="./train.conf.yaml",help="path to modelconfigeration") |
| 148 | + parser.add_argument("--teacher", type=str, default="SAGE", help="teacher model") |
| 149 | + parser.add_argument("--lamb", type=float, default=0, help="parameter balances loss from hard labels and teacher outputs") |
| 150 | + parser.add_argument("--n_epoch", type=int, default=200, help="number of epoch") |
| 151 | + parser.add_argument('--dataset', type=str, default="cora", help="dataset") |
| 152 | + parser.add_argument("--dataset_path", type=str, default=r'./data', help="path to save dataset") |
| 153 | + parser.add_argument("--best_model_path", type=str, default=r'./', help="path to save best model") |
| 154 | + parser.add_argument("--gpu", type=int, default=0) |
| 155 | + |
| 156 | + args = parser.parse_args() |
| 157 | + |
| 158 | + conf = {} |
| 159 | + if args.model_config_path is not None: |
| 160 | + conf = get_training_config(args.model_config_path, args.teacher, args.dataset) |
| 161 | + conf = dict(args.__dict__, **conf) |
| 162 | + |
| 163 | + if args.gpu >= 0: |
| 164 | + tlx.set_device("GPU", args.gpu) |
| 165 | + else: |
| 166 | + tlx.set_device("CPU") |
| 167 | + |
| 168 | + train_student(args) |
0 commit comments