-
Notifications
You must be signed in to change notification settings - Fork 25
Expand file tree
/
Copy pathsnap.lua
More file actions
275 lines (228 loc) · 7.14 KB
/
Copy pathsnap.lua
File metadata and controls
275 lines (228 loc) · 7.14 KB
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
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
require 'nn'
require 'optim'
require 'nngraph'
local c = require 'trepl.colorize'
cmd = torch.CmdLine()
cmd:option('-batchSize',1, 'mini-batch size')
cmd:option('-maxepoch',24,'epochs')
cmd:option('-maxepochsize',2000,'epochs')
cmd:option('-maxtestsize',2000,'epochs')
cmd:option('-path','.', 'save episodes')
cmd:option('-graph','dblp', 'graph')
cmd:option('-gpunum',3)
cmd:option('-weightDecay',0)
cmd:option('-learningRate',0.001)
cmd:option('-learningRate_damping',0.75)
cmd:option('-momentum',0.9)
cmd:option('-learningRateDecay',0)
cmd:option('-epoch_step',1,'epoch step')
cmd:option('-type','cuda')
cmd:option('-optmethod','adamax')
cmd:option('-nclasses', 3)
cmd:option('-L',20000,'epoch size')
cmd:option('-layers',10,'input layers')
cmd:option('-nfeatures',10,'feature maps')
cmd:option('-J',3,'scale of the extrapolation')
cmd:option('-verbose',0)
cmd:option('-prefix','')
opt = cmd:parse(arg or {})
if opt.type == 'cuda' then
require 'cutorch'
require 'cunn'
cutorch.setDevice(opt.gpunum)
cutorch.manualSeed(os.time())
end
opt.datagraphpathroot='.' -- path to the folder where corresponding graph files are
opt.datagraphpath = opt.datagraphpathroot .. 'com-' .. opt.graph .. '.ungraph.txt'
opt.datacommpath = opt.datagraphpathroot .. 'com-' .. opt.graph .. '.top5000.cmty.txt'
function cast(t)
if opt.type == 'cuda' then
require 'cunn'
return t:cuda()
elseif opt.type == 'double' then
return t:double()
elseif opt.type == 'cl' then
require 'clnn'
return t:cl()
else
error('Unknown type '..opt.type)
end
end
function file_exists(name)
local f=io.open(name,"r")
if f~=nil then io.close(f) return true else return false end
end
--create model
model = paths.dofile('gnn_modular.lua')
model=cast(model)
if opt.type == 'cuda' then
require 'cudnn'
cudnn.convert(model, cudnn)
end
parameters,gradParameters = model:getParameters()
--create criterion
crit = cast(nn.CrossEntropyCriterion())
-- create directory
opt.dpath = opt.path .. 'bs_' .. opt.batchSize .. '_J_' .. opt.J .. '_' .. os.time()
os.execute('mkdir -p ' .. opt.dpath)
opt.pathbaselinetest = opt.datagraphpathroot .. opt.graph .. '_baseline/'
--load dataset
dofile('snapload.lua')
if file_exists(paths.concat(opt.pathbaselinetest,'traintestpartition.th')) == true then
local YY=torch.load(paths.concat(opt.pathbaselinetest,'traintestpartition.th'))
goodcross_train = YY["goodcross_train"]
goodcross_test = YY["goodcross_test"]
else
object={ goodcross_train=goodcross_train, goodcross_test = goodcross_test}
torch.save(paths.concat(opt.pathbaselinetest,'traintestpartition.th'),object)
end
trsize = tablelength(goodcross_train)
tesize = tablelength(goodcross_test)
print(trsize)
print(tesize)
optimState = {
learningRate = opt.learningRate,
weightDecay = opt.weightDecay,
momentum = opt.momentum,
learningRateDecay = opt.learningRateDecay,
}
--logging
if opt.nclasses == 2 then
classes = {'1', '2'}
else
classes = {'1', '2', '3'}
end
confusion = optim.ConfusionMatrix(classes)
accLogger = optim.Logger(paths.concat(opt.dpath,'accuracy_train.log'))
acctLogger = optim.Logger(paths.concat(opt.dpath,'accuracy_test.log'))
errLogger = optim.Logger(paths.concat(opt.dpath,'error.log'))
confusionbase = optim.ConfusionMatrix(classes)
function loadexample ( ind, J , test)
if test == 0 then
W, target = extract_subgraph(goodcross_train[ind])
else
W, target = extract_subgraph(goodcross_test[ind])
end
target = cast(target)
local d = W:sum(1)
local Dfwd = torch.diag(d:squeeze())
local QQ = W:clone()
local N = W:size(1)
local WW = cast(torch.Tensor(N, N, J+2)):fill(0)
WW:narrow(3,1,1):copy(torch.eye(N))
for j=1,J-1 do
WW:narrow(3,1+j,1):copy(QQ)
QQ = QQ * QQ;
end
WW:narrow(3,J+1,1):copy(Dfwd:view(N,N,1))
WW:narrow(3,J+2,1):fill(1/N)
WW=WW:view(1,N,N,J+2)
local inp = cast(d):view(1,1,N,1)
return WW, inp, target
end
local permuteprotect = nn.Index(2)
if opt.nclasses == 2 then
plate = torch.LongTensor({{1,2},{2,1}})
perms = 2
else
plate = torch.LongTensor({{1,2,3},{2,1,3}})
perms = 2
end
permuteprotect = cast(permuteprotect)
plate = cast(plate)
prho = 0.98 --running average factor (display purposes only)
running_avg = 0
running_avg_b = 0
local function train()
epoch = epoch or 1
-- drop learning rate every "epoch_step" epochs
if epoch % opt.epoch_step == 0 then
optimState.learningRate = optimState.learningRate * opt.learningRate_damping
end
shuffle = torch.randperm(trsize)
local totloss = 0
for l=1,math.min(trsize,opt.maxepochsize) do
ii={}
Wtmp, inp, target = loadexample( shuffle[l], opt.J, 0)
ii={inp, Wtmp}
local feval = function(x)
if x ~= parameters then parameters:copy(x) end
gradParameters:zero()
pred = model:forward(ii)
--eval predictions against permuted labels
losses=cast(torch.Tensor(perms))
predt = pred:clone()
local laball = cast(torch.Tensor(inp:size(3),perms)):zero()
for s=1, perms do
local critt = crit:clone()
local tper = permuteprotect:forward({target,plate[s]})
_,labtmp = torch.max(tper,2)
labtmp = labtmp:double()
labtmp = cast(labtmp)
losses[s] = critt:forward(predt, labtmp)
laball:narrow(2,s,1):copy(labtmp)
end
lmin, lpos = torch.min(losses,1)
running_avg = prho * running_avg + (1- prho)*lmin[1]
if l % 50 == 0 then
print(running_avg)
print(confusion)
end
fout = crit:forward(pred, laball:narrow(2,lpos[1],1))
df = crit:backward(pred, laball:narrow(2,lpos[1],1))
model:backward(ii,df)
confusion:batchAdd(pred,laball:narrow(2,lpos[1],1))
return fout, gradParameters
end
_, batchloss = optim[opt.optmethod](feval, parameters, optimState)
totloss = totloss + batchloss[1]
collectgarbage()
end
print(('Epoch[%d] Train loss ' ..c.cyan'%f '):format( epoch, totloss/opt.L))
print(confusion)
local trainAccuracy = confusion.totalValid * 100
confusion:zero()
epoch = epoch + 1
return trainAccuracy
end
local function test()
shuffle = torch.randperm(math.min(tesize,opt.maxtestsize))
local totloss = 0
for l=1,math.min(tesize,opt.maxtestsize) do
ii={}
Wtmp, inp, target = loadexample( shuffle[l], opt.J, 1)
ii={inp, Wtmp}
pred = model:forward(ii)
losses=cast(torch.Tensor(perms))
predt = pred:clone()
local laball = cast(torch.Tensor(inp:size(3),perms)):zero()
for s=1, perms do
local critt = crit:clone()
local tper = permuteprotect:forward({target,plate[s]})
_,labtmp = torch.max(tper,2)
labtmp = labtmp:double()
labtmp = cast(labtmp)
losses[s] = critt:forward(predt, labtmp)
laball:narrow(2,s,1):copy(labtmp)
end
lmin, lpos = torch.min(losses,1)
confusion:batchAdd(pred,laball:narrow(2,lpos[1],1))
totloss = totloss + lmin[1]
collectgarbage()
end
print(('Epoch[%d] Test loss ' ..c.cyan'%f '):format( epoch, totloss/tesize))
print(confusion)
local testAccuracy = confusion.totalValid * 100
confusion:zero()
return testAccuracy
end
for jj=1,opt.maxepoch do
train_acc = train()
accLogger:add{['% train accuracy'] = train_acc}
accLogger:style{['% train accuracy'] = '-'}
accLogger:plot()
test_acc = test()
acctLogger:add{['% test accuracy'] = test_acc}
acctLogger:style{['% test accuracy'] = '-'}
acctLogger:plot()
end