|
| 1 | +# coding: utf-8 |
| 2 | +# 2022/3/1 @ fannazya |
| 3 | +__all__ = ["GKTNet"] |
| 4 | + |
| 5 | +import json |
| 6 | +import networkx as nx |
| 7 | +import torch |
| 8 | +from torch import nn |
| 9 | +import torch.nn.functional as F |
| 10 | +from EduKTM.utils import GRUCell, begin_states, get_states, expand_tensor, \ |
| 11 | + format_sequence, mask_sequence_variable_length |
| 12 | + |
| 13 | + |
| 14 | +class GKTNet(nn.Module): |
| 15 | + def __init__(self, ku_num, graph, hidden_num=None, latent_dim=None, dropout=0.0): |
| 16 | + super(GKTNet, self).__init__() |
| 17 | + self.ku_num = int(ku_num) |
| 18 | + self.hidden_num = self.ku_num if hidden_num is None else int(hidden_num) |
| 19 | + self.latent_dim = self.ku_num if latent_dim is None else int(latent_dim) |
| 20 | + self.neighbor_dim = self.hidden_num + self.latent_dim |
| 21 | + self.graph = nx.DiGraph() |
| 22 | + self.graph.add_nodes_from(list(range(ku_num))) |
| 23 | + try: |
| 24 | + with open(graph) as f: |
| 25 | + self.graph.add_weighted_edges_from(json.load(f)) |
| 26 | + except ValueError: |
| 27 | + with open(graph) as f: |
| 28 | + self.graph.add_weighted_edges_from([e + [1.0] for e in json.load(f)]) |
| 29 | + |
| 30 | + self.rnn = GRUCell(self.hidden_num) |
| 31 | + self.response_embedding = nn.Embedding(2 * self.ku_num, self.latent_dim) |
| 32 | + self.concept_embedding = nn.Embedding(self.ku_num, self.latent_dim) |
| 33 | + self.f_self = nn.Linear(self.neighbor_dim, self.hidden_num) |
| 34 | + self.n_out = nn.Linear(2 * self.neighbor_dim, self.hidden_num) |
| 35 | + self.n_in = nn.Linear(2 * self.neighbor_dim, self.hidden_num) |
| 36 | + self.dropout = nn.Dropout(dropout) |
| 37 | + self.out = nn.Linear(self.hidden_num, 1) |
| 38 | + |
| 39 | + def in_weight(self, x, ordinal=True, with_weight=True): |
| 40 | + if isinstance(x, torch.Tensor): |
| 41 | + x = x.numpy().tolist() |
| 42 | + if isinstance(x, list): |
| 43 | + return [self.in_weight(_x) for _x in x] |
| 44 | + elif isinstance(x, (int, float)): |
| 45 | + if not ordinal: |
| 46 | + return list(self.graph.predecessors(int(x))) |
| 47 | + else: |
| 48 | + _ret = [0] * self.ku_num |
| 49 | + for i in self.graph.predecessors(int(x)): |
| 50 | + if with_weight: |
| 51 | + _ret[i] = self.graph[i][x]['weight'] |
| 52 | + else: |
| 53 | + _ret[i] = 1 |
| 54 | + return _ret |
| 55 | + else: |
| 56 | + raise TypeError("cannot handle %s" % type(x)) |
| 57 | + |
| 58 | + def out_weight(self, x, ordinal=True, with_weight=True): |
| 59 | + if isinstance(x, torch.Tensor): |
| 60 | + x = x.numpy().tolist() |
| 61 | + if isinstance(x, list): |
| 62 | + return [self.out_weight(_x) for _x in x] |
| 63 | + elif isinstance(x, (int, float)): |
| 64 | + if not ordinal: |
| 65 | + return list(self.graph.successors(int(x))) |
| 66 | + else: |
| 67 | + _ret = [0] * self.ku_num |
| 68 | + for i in self.graph.successors(int(x)): |
| 69 | + if with_weight: |
| 70 | + _ret[i] = self.graph[x][i]['weight'] |
| 71 | + else: |
| 72 | + _ret[i] = 1 |
| 73 | + return _ret |
| 74 | + else: |
| 75 | + raise TypeError("cannot handle %s" % type(x)) |
| 76 | + |
| 77 | + def neighbors(self, x, ordinal=True, with_weight=False): |
| 78 | + if isinstance(x, torch.Tensor): |
| 79 | + x = x.numpy().tolist() |
| 80 | + if isinstance(x, list): |
| 81 | + return [self.neighbors(_x) for _x in x] |
| 82 | + elif isinstance(x, (int, float)): |
| 83 | + if not ordinal: |
| 84 | + return list(self.graph.neighbors(int(x))) |
| 85 | + else: |
| 86 | + _ret = [0] * self.ku_num |
| 87 | + for i in self.graph.neighbors(int(x)): |
| 88 | + if with_weight: |
| 89 | + _ret[i] = self.graph[i][x]['weight'] |
| 90 | + else: |
| 91 | + _ret[i] = 1 |
| 92 | + return _ret |
| 93 | + else: |
| 94 | + raise TypeError("cannot handle %s" % type(x)) |
| 95 | + |
| 96 | + def forward(self, questions, answers, valid_length=None, compressed_out=True, layout="NTC"): |
| 97 | + length = questions.shape[1] |
| 98 | + inputs, axis, batch_size = format_sequence(length, questions, layout, False) |
| 99 | + answers, _, _ = format_sequence(length, answers, layout, False) |
| 100 | + |
| 101 | + states = begin_states([(batch_size, self.ku_num, self.hidden_num)])[0] |
| 102 | + outputs = [] |
| 103 | + all_states = [] |
| 104 | + for i in range(length): |
| 105 | + # neighbors - aggregate |
| 106 | + inputs_i = inputs[i].reshape([batch_size, ]) |
| 107 | + answer_i = answers[i].reshape([batch_size, ]) |
| 108 | + |
| 109 | + _neighbors = self.neighbors(inputs_i) |
| 110 | + neighbors_mask = expand_tensor(torch.Tensor(_neighbors), -1, self.hidden_num) |
| 111 | + _neighbors_mask = expand_tensor(torch.Tensor(_neighbors), -1, self.hidden_num + self.latent_dim) |
| 112 | + |
| 113 | + # get concept embedding |
| 114 | + concept_embeddings = self.concept_embedding.weight.data |
| 115 | + concept_embeddings = expand_tensor(concept_embeddings, 0, batch_size) |
| 116 | + |
| 117 | + agg_states = torch.cat((concept_embeddings, states), dim=-1) |
| 118 | + |
| 119 | + # aggregate |
| 120 | + _neighbors_states = _neighbors_mask * agg_states |
| 121 | + |
| 122 | + # self - aggregate |
| 123 | + _concept_embedding = get_states(inputs_i, states) |
| 124 | + _self_hidden_states = torch.cat((_concept_embedding, self.response_embedding(answer_i)), dim=-1) |
| 125 | + |
| 126 | + _self_mask = F.one_hot(inputs_i, self.ku_num) # p |
| 127 | + _self_mask = expand_tensor(_self_mask, -1, self.hidden_num) |
| 128 | + |
| 129 | + self_hidden_states = expand_tensor(_self_hidden_states, 1, self.ku_num) |
| 130 | + |
| 131 | + # aggregate |
| 132 | + _hidden_states = torch.cat((_neighbors_states, self_hidden_states), dim=-1) |
| 133 | + |
| 134 | + _in_state = self.n_in(_hidden_states) |
| 135 | + _out_state = self.n_out(_hidden_states) |
| 136 | + in_weight = expand_tensor(torch.Tensor(self.in_weight(inputs_i)), -1, self.hidden_num) |
| 137 | + out_weight = expand_tensor(torch.Tensor(self.out_weight(inputs_i)), -1, self.hidden_num) |
| 138 | + |
| 139 | + next_neighbors_states = in_weight * _in_state + out_weight * _out_state |
| 140 | + |
| 141 | + # self - update |
| 142 | + next_self_states = self.f_self(_self_hidden_states) |
| 143 | + next_self_states = expand_tensor(next_self_states, 1, self.ku_num) |
| 144 | + next_self_states = _self_mask * next_self_states |
| 145 | + |
| 146 | + next_states = neighbors_mask * next_neighbors_states + next_self_states |
| 147 | + |
| 148 | + next_states, _ = self.rnn(next_states, [states]) |
| 149 | + next_states = (_self_mask + neighbors_mask) * next_states + (1 - _self_mask - neighbors_mask) * states |
| 150 | + |
| 151 | + states = self.dropout(next_states) |
| 152 | + output = torch.sigmoid(self.out(states).squeeze(axis=-1)) # p |
| 153 | + outputs.append(output) |
| 154 | + if valid_length is not None and not compressed_out: |
| 155 | + all_states.append([states]) |
| 156 | + |
| 157 | + if valid_length is not None: |
| 158 | + if compressed_out: |
| 159 | + states = None |
| 160 | + outputs = mask_sequence_variable_length(torch, outputs, length, valid_length, axis, merge=True) |
| 161 | + |
| 162 | + return outputs, states |
0 commit comments