Repository navigation
Expand file tree
/
Copy pathCSparsePpa.cpp
More file actions
464 lines (425 loc) · 14 KB
/
Copy pathCSparsePpa.cpp
File metadata and controls
464 lines (425 loc) · 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
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
#include "CSparsePpa.h"
#include "ndlstrutil.h"
#include <fstream>
#include <iomanip>
namespace {
void allocSiteStorage(CSparsePpa& m, int numData, int numTarget)
{
m.f.resize(numData, numTarget);
m.fBar.resize(numData, numTarget);
m.fPost.resize(numData, numTarget);
m.g.resize(numData, numTarget);
m.nu.resize(numData, numTarget);
m.gamma.resize(numData, numTarget);
m.ff.resize(numData, numTarget);
m.f.zeros();
m.fBar.zeros();
m.fPost.zeros();
m.g.zeros();
m.nu.zeros();
m.gamma.zeros();
m.ff.zeros();
}
} // namespace
void CSparsePpa::constructGp(bool runInitEstep)
{
if(approxType == CGp::FTC)
{
approxType = CGp::DTC;
if(actSetSize == 0)
actSetSize = static_cast<unsigned int>(numData);
}
if(actSetSize == 0)
throw ndlexceptions::Error("CSparsePpa: sparse approx needs actSetSize > 0");
allocSiteStorage(*this, numData, numTarget);
pInnerNoise = new CGaussianNoise(&f);
for(unsigned int j = 0; j < pInnerNoise->getOutputDim(); j++)
pInnerNoise->setBiasVal(0.0, j);
pInnerNoise->setParam(1e-12, pInnerNoise->getNumParams() - 1);
pGp = new CGp(static_cast<unsigned int>(X.getCols()),
static_cast<unsigned int>(numTarget),
&X, &f, &kern, pInnerNoise,
approxType, actSetSize, verbosity);
pGp->setBetaVal(betaVal);
pGp->fixBeta(true);
pGp->setOutputScaleLearnt(false);
if(pGp->isSparseApproximation())
{
pGp->setInducingFixed(true);
if(actSetSize == static_cast<unsigned int>(numData))
setInducingToX();
}
outerNoise.setVerbosity(verbosity);
siteWorkspace.resize(static_cast<unsigned int>(numData),
static_cast<unsigned int>(numTarget));
siteWorkspace.zeros();
outerNoise.attachSiteWorkspace(&siteWorkspace);
if(runInitEstep)
init();
}
CSparsePpa::CSparsePpa(const CMatrix& inData, const CMatrix& targetData,
CKern& kernel, CNoise& outer,
int approx, unsigned int actSize,
double beta, int verbos)
: X(inData), y(targetData), kern(kernel), outerNoise(outer),
pInnerNoise(nullptr), pGp(nullptr),
betaVal(beta), approxType(approx), actSetSize(actSize),
verbosity(verbos),
numData(static_cast<int>(targetData.getRows())),
numTarget(static_cast<int>(targetData.getCols()))
{
DIMENSIONMATCH(X.getRows() == y.getRows());
constructGp(true);
}
CSparsePpa::CSparsePpa(const CMatrix& inData, const CMatrix& targetData,
CKern& kernel, CNoise& outer,
int approx, unsigned int actSize,
double beta, int verbos, CSparsePpaLoadedTag)
: X(inData), y(targetData), kern(kernel), outerNoise(outer),
pInnerNoise(nullptr), pGp(nullptr),
betaVal(beta), approxType(approx), actSetSize(actSize),
verbosity(verbos),
numData(static_cast<int>(targetData.getRows())),
numTarget(static_cast<int>(targetData.getCols()))
{
DIMENSIONMATCH(X.getRows() == y.getRows());
constructGp(false);
}
CSparsePpa::~CSparsePpa()
{
delete pGp;
delete pInnerNoise;
}
void CSparsePpa::setInducingToX()
{
if(!pGp->isSparseApproximation())
throw ndlexceptions::Error("setInducingToX requires a sparse approximation");
if(actSetSize != static_cast<unsigned int>(numData))
throw ndlexceptions::Error("setInducingToX requires actSetSize == N");
pGp->setInducingVals(X);
pGp->setInducingFixed(true);
pGp->invalidateCache();
}
void CSparsePpa::fixInducing(bool val)
{
pGp->setInducingFixed(val);
}
void CSparsePpa::setSiteState(const CMatrix& fBarIn, const CMatrix& fIn)
{
DIMENSIONMATCH(fBarIn.dimensionsMatch(fBar));
DIMENSIONMATCH(fIn.dimensionsMatch(f));
fBar.deepCopy(fBarIn);
f.deepCopy(fIn);
fPost.deepCopy(fIn);
syncGpTargets();
}
void CSparsePpa::syncGpTargets()
{
pGp->setTargetVals(f);
pGp->invalidateCache();
}
void CSparsePpa::updateNuG()
{
for(int i = 0; i < numData; i++)
outerNoise.getNuG(g, nu, i);
}
void CSparsePpa::init()
{
outerNoise.setMus(0.0);
for(int i = 0; i < numData; i++)
{
const double dk = kern.diagComputeElement(X, i);
for(int j = 0; j < numTarget; j++)
outerNoise.setVarSigma(dk, i, j);
}
f.zeros();
fBar.zeros();
eStep();
}
void CSparsePpa::eStep()
{
syncGpTargets();
pGp->posteriorMean(fBar, X);
// Bound / q(u) must use the ⟨f⟩ that produced fBar (MATLAB fBarfBar timing).
fPost.deepCopy(f);
outerNoise.setMus(fBar);
for(int i = 0; i < numData; i++)
for(int j = 0; j < numTarget; j++)
outerNoise.setVarSigma(1.0 / betaVal, i, j);
updateNuG();
for(int i = 0; i < numData; i++)
for(int j = 0; j < numTarget; j++)
{
const double gVal = g.getVal(i, j);
gamma.setVal((gVal * gVal - nu.getVal(i, j)) / 2.0, i, j);
f.setVal(fBar.getVal(i, j) + gVal / betaVal, i, j);
}
for(int j = 0; j < numTarget; j++)
{
const double b2 = betaVal * betaVal;
for(int i = 0; i < numData; i++)
{
const double mVal = fBar.getVal(i, j);
const double ffVal = 2.0 / b2 * gamma.getVal(i, j) + 1.0 / betaVal
+ 2.0 * mVal * f.getVal(i, j) - mVal * mVal;
ff.setVal(ffVal, i, j);
}
}
}
void CSparsePpa::mStep(int kernIters)
{
if(kern.getNumParams() == 0 || kernIters <= 0)
return;
syncGpTargets();
const int oldVerb = pGp->getVerbosity();
pGp->setVerbosity(0);
pGp->setMaxIters(static_cast<unsigned int>(kernIters));
pGp->runDefaultOptimiser();
pGp->setVerbosity(oldVerb);
pGp->invalidateCache();
}
double CSparsePpa::ppaBound() const
{
// CIP-0026 full q(u) ELBO (DTC / DTCVAR):
// L = -KL(q(u)||p(u)) - ½β tr(Cov_f̄) [+ DTCVAR K−Q site] + kern prior
// + E[log p(y | f̄)] with site variance 1/β
// Matches dense CPpa::approxLogLikelihood when M=N, Xu=X, no white.
// GP terms use fPost (⟨f⟩ that produced fBar), not post-E-step f.
// FITC/PITC keep the interim monitor (CGp approx LML + outer noise LL).
CSparsePpa* self = const_cast<CSparsePpa*>(this);
CMatrix fSave(f);
self->f.deepCopy(fPost);
self->syncGpTargets();
CMatrix vs(numData, numTarget);
vs.setVals(1.0 / betaVal);
const double noiseLL = outerNoise.logLikelihood(fBar, vs, y);
double L = 0.0;
const int approx = pGp->getApproximationType();
if(approx == CGp::DTC || approx == CGp::DTCVAR)
L = pGp->sparsePpaElboGpTerms() + noiseLL;
else
L = pGp->logLikelihood() + noiseLL;
self->f.deepCopy(fSave);
self->syncGpTargets();
return L;
}
void CSparsePpa::latentMeanVar(CMatrix& mu, CMatrix& varSigma,
const CMatrix& Xin) const
{
const_cast<CSparsePpa*>(this)->syncGpTargets();
pGp->latentMeanVar(mu, varSigma, Xin);
}
void CSparsePpa::predictiveMeanVar(CMatrix& mu, CMatrix& varSigma,
const CMatrix& Xin) const
{
const_cast<CSparsePpa*>(this)->syncGpTargets();
pGp->predictiveMeanVar(mu, varSigma, Xin);
}
void CSparsePpa::posteriorMeanVar(CMatrix& mu, CMatrix& varSigma,
const CMatrix& Xin) const
{
// CIP-0031: deprecated alias — sparse PPA via CGp historically returned predictive.
predictiveMeanVar(mu, varSigma, Xin);
}
void CSparsePpa::out(CMatrix& yPred, const CMatrix& Xin) const
{
CMatrix mu(Xin.getRows(), numTarget);
CMatrix vs(Xin.getRows(), numTarget);
// CIP-0031: latent into outer noise so observation noise is counted once.
latentMeanVar(mu, vs, Xin);
outerNoise.out(yPred, mu, vs);
}
void CSparsePpa::display(ostream& os) const
{
os << "Sparse PPA: approx=" << pGp->getApproximationStr()
<< " M=" << actSetSize
<< " N=" << numData
<< " beta=" << betaVal
<< " inducingFixed=" << (pGp->isInducingFixed() ? "true" : "false")
<< endl;
os << "Kernel:" << endl;
kern.display(os);
os << "Outer noise: " << outerNoise.getName() << endl;
}
void CSparsePpa::optimise(int maxIters, int kernIters)
{
if(verbosity > 0)
{
cout << "Initial sparse PPA:" << endl;
display(cout);
}
double oldBound = ppaBound();
for(int counter = 0; counter < maxIters; counter++)
{
mStep(kernIters);
eStep();
const double bound = ppaBound();
if(verbosity > 0)
{
cout << "CSparsePpa iter " << (counter + 1)
<< " ppaBound " << bound
<< " (delta " << (bound - oldBound) << ")" << endl;
}
// Soft signal only — mean-field M-step need not be monotone.
oldBound = bound;
}
if(verbosity > 0)
{
cout << "Final sparse PPA:" << endl;
display(cout);
}
}
void writeSparsePpaToStream(const CSparsePpa& model, ostream& out)
{
out << "ppaVersion=" << SPARSE_PPAVERSION << endl;
out << "approx=" << model.gp().getApproximationStr() << endl;
out << "numActive=" << model.getNumActive() << endl;
out << "numTrainData=" << model.X.getRows() << endl;
out << "numProcesses=" << model.y.getCols() << endl;
out << "numFeatures=" << model.X.getCols() << endl;
out << "beta=" << model.getBeta() << endl;
out << "inducingFixed=" << (model.gp().isInducingFixed() ? 1 : 0) << endl;
writeKernToStream(*model.gp().getKernel(), out);
writeNoiseToStream(model.getOuterNoise(), out);
// Inducing points X_u (numActive x numFeatures).
const CMatrix& Xu = model.gp().X_u;
for(unsigned int i = 0; i < Xu.getRows(); i++)
{
for(unsigned int j = 0; j < Xu.getCols(); j++)
{
out << Xu.getVal(i, j);
if(j + 1 < Xu.getCols())
out << " ";
}
out << endl;
}
// Dense blocks: y, fBar, f, X (row-major text).
const unsigned int N = model.X.getRows();
const unsigned int P = model.y.getCols();
const unsigned int Q = model.X.getCols();
for(unsigned int i = 0; i < N; i++)
{
for(unsigned int j = 0; j < P; j++)
out << model.y.getVal(i, j) << (j + 1 < P ? " " : "");
out << endl;
}
for(unsigned int i = 0; i < N; i++)
{
for(unsigned int j = 0; j < P; j++)
out << model.fBar.getVal(i, j) << (j + 1 < P ? " " : "");
out << endl;
}
for(unsigned int i = 0; i < N; i++)
{
for(unsigned int j = 0; j < P; j++)
out << model.f.getVal(i, j) << (j + 1 < P ? " " : "");
out << endl;
}
for(unsigned int i = 0; i < N; i++)
{
for(unsigned int j = 0; j < Q; j++)
out << model.X.getVal(i, j) << (j + 1 < Q ? " " : "");
out << endl;
}
}
void writeSparsePpaToFile(const CSparsePpa& model, const string& modelFileName,
const string& comment)
{
ofstream out(modelFileName.c_str());
if(!out)
throw ndlexceptions::FileWriteError(modelFileName);
out << setiosflags(ios::scientific);
out << setprecision(17);
if(comment.size() > 0)
out << "# " << comment << endl;
writeSparsePpaToStream(model, out);
out.close();
}
static string readKeyedLine(istream& in, const string& key)
{
string line;
vector<string> tokens;
ndlstrutil::getline(in, line);
while(line.size() > 0 && line[0] == '#')
{
tokens.clear();
ndlstrutil::getline(in, line);
}
ndlstrutil::tokenise(tokens, line, "=");
if(tokens.size() != 2 || tokens[0] != key)
throw ndlexceptions::FileFormatError();
return tokens[1];
}
CSparsePpa* readSparsePpaFromStream(istream& in, int verbosity)
{
if(readKeyedLine(in, "ppaVersion") != SPARSE_PPAVERSION)
throw ndlexceptions::FileFormatError();
const string approxStr = readKeyedLine(in, "approx");
const unsigned int numActive = static_cast<unsigned int>(atoi(readKeyedLine(in, "numActive").c_str()));
const int numTrainData = atoi(readKeyedLine(in, "numTrainData").c_str());
const int numProcesses = atoi(readKeyedLine(in, "numProcesses").c_str());
const int numFeatures = atoi(readKeyedLine(in, "numFeatures").c_str());
const double beta = atof(readKeyedLine(in, "beta").c_str());
const bool inducingFixed = (atoi(readKeyedLine(in, "inducingFixed").c_str()) != 0);
int approxType = CGp::DTC;
if(approxStr == "dtc")
approxType = CGp::DTC;
else if(approxStr == "dtcvar")
approxType = CGp::DTCVAR;
else if(approxStr == "fitc")
approxType = CGp::FITC;
else if(approxStr == "pitc")
approxType = CGp::PITC;
else
throw ndlexceptions::FileFormatError();
CKern* pkern = readKernFromStream(in);
CNoise* pnoise = readNoiseFromStream(in);
CMatrix Xu(numActive, numFeatures);
for(unsigned int i = 0; i < numActive; i++)
{
string line;
vector<string> tokens;
ndlstrutil::getline(in, line);
ndlstrutil::tokenise(tokens, line, " ");
if(tokens.size() != numFeatures)
throw ndlexceptions::FileFormatError();
for(unsigned int j = 0; j < numFeatures; j++)
Xu.setVal(atof(tokens[j].c_str()), i, j);
}
CMatrix* pX = new CMatrix(numTrainData, numFeatures, 0.0);
CMatrix* py = new CMatrix(numTrainData, numProcesses);
CMatrix fBar(numTrainData, numProcesses);
CMatrix f(numTrainData, numProcesses);
auto readBlock = [&](CMatrix& A, int rows, int cols) {
for(int i = 0; i < rows; i++)
{
string line;
vector<string> tokens;
ndlstrutil::getline(in, line);
ndlstrutil::tokenise(tokens, line, " ");
if(static_cast<int>(tokens.size()) != cols)
throw ndlexceptions::FileFormatError();
for(int j = 0; j < cols; j++)
A.setVal(atof(tokens[j].c_str()), i, j);
}
};
readBlock(*py, numTrainData, numProcesses);
readBlock(fBar, numTrainData, numProcesses);
readBlock(f, numTrainData, numProcesses);
readBlock(*pX, numTrainData, numFeatures);
pnoise->setTarget(py);
CSparsePpa* model = new CSparsePpa(*pX, *py, *pkern, *pnoise,
approxType, numActive, beta, verbosity,
CSparsePpaLoadedTag());
model->gp().setInducingVals(Xu);
model->gp().setInducingFixed(inducingFixed);
model->setSiteState(fBar, f);
return model;
}
CSparsePpa* readSparsePpaFromFile(const string& modelFileName, int verbosity)
{
ifstream in(modelFileName.c_str());
if(!in)
throw ndlexceptions::FileReadError(modelFileName);
return readSparsePpaFromStream(in, verbosity);
}