-
Notifications
You must be signed in to change notification settings - Fork 30
/
problem.py
153 lines (120 loc) · 4.71 KB
/
problem.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
#!/usr/bin/env python
"""
problem.py
"""
from __future__ import division
from __future__ import print_function
import os
import sys
import h5py
import cPickle
import numpy as np
from scipy import sparse
from sklearn import metrics
from scipy.sparse import csr_matrix
import torch
from torch.autograd import Variable
from torch.nn import functional as F
# --
# Helper classes
class ProblemLosses:
@staticmethod
def multilabel_classification(preds, targets):
return F.multilabel_soft_margin_loss(preds, targets)
@staticmethod
def classification(preds, targets):
return F.cross_entropy(preds, targets)
@staticmethod
def regression_mae(preds, targets):
return F.l1_loss(preds, targets)
# @staticmethod
# def regression_mse(preds, targets):
# return F.mse_loss(preds - targets)
class ProblemMetrics:
@staticmethod
def multilabel_classification(y_true, y_pred):
y_pred = (y_pred > 0).astype(int)
return {
"micro" : float(metrics.f1_score(y_true, y_pred, average="micro")),
"macro" : float(metrics.f1_score(y_true, y_pred, average="macro")),
}
@staticmethod
def classification(y_true, y_pred):
y_pred = np.argmax(y_pred, axis=1)
return {
"micro" : float(metrics.f1_score(y_true, y_pred, average="micro")),
"macro" : float(metrics.f1_score(y_true, y_pred, average="macro")),
}
# return (y_pred == y_true.squeeze()).mean()
@staticmethod
def regression_mae(y_true, y_pred):
return float(np.abs(y_true - y_pred).mean())
# --
# Problem definition
def parse_csr_matrix(x):
v, r, c = x
return csr_matrix((v, (r, c)))
class NodeProblem(object):
def __init__(self, problem_path, cuda=True):
print('NodeProblem: loading started')
f = h5py.File(problem_path)
self.task = f['task'].value
self.n_classes = f['n_classes'].value if 'n_classes' in f else 1 # !!
self.feats = f['feats'].value if 'feats' in f else None
self.folds = f['folds'].value
self.targets = f['targets'].value
if 'sparse' in f and f['sparse'].value:
self.adj = parse_csr_matrix(f['adj'].value)
self.train_adj = parse_csr_matrix(f['train_adj'].value)
else:
self.adj = f['adj'].value
self.train_adj = f['train_adj'].value
f.close()
self.feats_dim = self.feats.shape[1] if self.feats is not None else None
self.n_nodes = self.adj.shape[0]
self.cuda = cuda
self.__to_torch()
self.nodes = {
"train" : np.where(self.folds == 'train')[0],
"val" : np.where(self.folds == 'val')[0],
"test" : np.where(self.folds == 'test')[0],
}
self.loss_fn = getattr(ProblemLosses, self.task)
self.metric_fn = getattr(ProblemMetrics, self.task)
print('NodeProblem: loading finished')
def __to_torch(self):
if not sparse.issparse(self.adj):
self.adj = Variable(torch.LongTensor(self.adj))
self.train_adj = Variable(torch.LongTensor(self.train_adj))
if self.cuda:
self.adj = self.adj.cuda()
self.train_adj = self.train_adj.cuda()
if self.feats is not None:
self.feats = Variable(torch.FloatTensor(self.feats))
if self.cuda:
self.feats = self.feats.cuda()
def __batch_to_torch(self, mids, targets):
""" convert batch to torch """
mids = Variable(torch.LongTensor(mids))
if self.task == 'multilabel_classification':
targets = Variable(torch.FloatTensor(targets))
elif self.task == 'classification':
targets = Variable(torch.LongTensor(targets))
elif 'regression' in self.task:
targets = Variable(torch.FloatTensor(targets))
else:
raise Exception('NodeDataLoader: unknown task: %s' % self.task)
if self.cuda:
mids, targets = mids.cuda(), targets.cuda()
return mids, targets
def iterate(self, mode, batch_size=512, shuffle=False):
nodes = self.nodes[mode]
idx = np.arange(nodes.shape[0])
if shuffle:
idx = np.random.permutation(idx)
n_chunks = idx.shape[0] // batch_size + 1
for chunk_id, chunk in enumerate(np.array_split(idx, n_chunks)):
mids = nodes[chunk]
targets = self.targets[mids]
mids, targets = self.__batch_to_torch(mids, targets)
yield mids, targets, chunk_id / n_chunks