-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathProblem.pas
607 lines (532 loc) · 17.4 KB
/
Problem.pas
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
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
{
Copyright (c) Peter Karpov 2010 - 2017.
Usage of the works is permitted provided that this instrument is retained with
the works, so that any entity that uses the works is notified of this instrument.
DISCLAIMER: THE WORKS ARE WITHOUT WARRANTY.
}
{$IFDEF FPC} {$MODE DELPHI} {$ENDIF}
unit Problem; ///////////////////////////////////////////////////////////////////////
{
>> Description
VALIS problem definition unit for real-valued classification problems.
>> Author
Peter Karpov
Email : [email protected]
Homepage : inversed.ru
GitHub : inversed-ru
Twitter : @inversed_ru
>> ToDo
- Examine various crossover and mutation operators employed in real coded GAs
- Initialization option: apply crossover to the training data
? Covariance matrix adaptation
>> Changelog
1.4 : 2017.12.16 ~ InvLibs compatibility
~ Cleanup
1.3 : 2017.02.09 + Intermediate and midpoint crossovers
~ Modified initialization to exclude duplicates
* AssignAntibody not copying some attributes
+ Various radius initialization methods
1.2 : 2017.01.03 * Incorrect metric inheritance during crossover
1.1 : 2016.12.16 * Incorrect mutation
1.0 : 2016.12.15 ~ Rewritten from scratch
0.0 : 2009.05.21 + Initial version
Notation: + added, - removed, * fixed, ~ changed
}
interface ///////////////////////////////////////////////////////////////////////////
uses
Arrays;
type
TCrossoverType = (ctBinary, ctIntermediate, ctMidpoint);
TRadiusInit =
( riMean, riMeanUniform, riMeanTriangle, riMeanExp,
riDistToNearest, riDistToRandom
);
const
AdaptRadius = True;
AdaptDimWeights = False;
AdaptMetric = False;
RandInit = False;
RadiusInit = riDistToRandom;
CrossoverType = ctBinary;
type
TAntigen =
record
x : TRealArray;
Class_ : Integer;
end;
TAntigens =
record
_ : array of TAntiGen;
N, NVars,
NClasses : Integer;
end;
TClassDistr = TRealArray;
TAntibody =
record
// Generic fields
SumW,
SumWCorrect,
Accuracy,
KShare,
Fitness : Real;
MajorityClass : Integer;
ClassDistr : TRealArray;
// Problem-specific fields
// #TODO should be a separate type?
x, DimWeight : TRealArray;
Radius,
Metric : Real;
end;
TAntibodies =
record
_ : array of TAntibody;
OrderFitness,
OrderSumW : TIntArray;
Accuracy,
Coverage : Real;
N : Integer;
end;
{-----------------------<< Antigens >>----------------------------------------------}
// Create a new empty array of Antigens
procedure InitAntigens(
var Antigens : TAntigens);
overload;
// Create a new empty array of antigens, set the number of variables and classes
procedure InitAntigens(
var Antigens : TAntigens;
NVars,
NClasses : Integer);
overload;
// Append an Antigen to the Antigens
procedure AppendAntigen(
var Antigens : TAntigens;
const Antigen : TAntigen);
// Load the Data from Path
procedure LoadData(
var Data : TAntigens;
const Path : AnsiString);
{-----------------------<< Antibodies >>--------------------------------------------}
// ABTo := ABFrom
procedure AssignAntibody(
var ABTo : TAntibody;
const ABFrom : TAntibody);
// ABsTo := ABsFrom
procedure CopyAntibodies(
var ABsTo : TAntibodies;
const ABsFrom : TAntibodies);
// Return the distance between the Antigen and the Antibody
function Distance(
const Antigen : TAntigen;
const Antibody : TAntibody
) : Real;
// Create a Child by crossing over ParentA and ParentB
procedure Crossover(
var Child : TAntibody;
const ParentA,
ParentB : TAntibody);
// Mutate the Antibody using a given mutation Rate
procedure Mutate(
var Antibody : TAntibody;
Rate : Real);
// Return the Order of Antigens sorted by distance to x
// #HACK should not be in the problem unit
procedure SortByDistance(
var Order : TIntArray;
const Antigens : TAntigens;
const x : TRealArray);
// Create a population of N Antibodies based on Antigens
procedure InitAntibodies(
var Antibodies : TAntibodies;
N : Integer;
const Antigens : TAntigens);
// Save antibody parameters to Path
procedure SaveAntibodiesStats(
const Path : AnsiString;
const Antibodies : TAntibodies);
// Save antibody parameters required for visualization to Path
procedure SaveAntibodiesVis(
const Path : AnsiString;
const Antibodies : TAntibodies;
const Antigens : TAntigens);
implementation //////////////////////////////////////////////////////////////////////
uses
InvSys,
Math,
ExtraMath,
Statistics,
StringUtils,
RandVars,
Sorting;
{-----------------------<< Antigens >>----------------------------------------------}
// AGTo := AGFrom
procedure Assign(
var AGTo : TAntigen;
const AGFrom : TAntigen);
begin
AGTo.Class_ := AGFrom.Class_;
AGTo.x := Copy(AGFrom.x);
end;
// Create a new empty array of Antigens
procedure InitAntigens(
var Antigens : TAntigens);
overload;
begin
SetLength(Antigens._, 0);
Antigens.N := 0;
end;
// Create a new empty array of antigens, set the number of variables and classes
procedure InitAntigens(
var Antigens : TAntigens;
NVars,
NClasses : Integer);
overload;
begin
InitAntigens(Antigens);
Antigens.NVars := NVars;
Antigens.NClasses := NClasses;
end;
// Append an Antigen to the Antigens
procedure AppendAntigen(
var Antigens : TAntigens;
const Antigen : TAntigen);
begin
with Antigens do
begin
Inc(N);
if N > Length(Antigens._) then
SetLength(Antigens._, 2 * Antigens.N);
Assign(Antigens._[N - 1], Antigen);
end;
end;
// Load the Data from Path
procedure LoadData(
var Data : TAntigens;
const Path : AnsiString);
var
i : Integer;
S : AnsiString;
Antigen : TAntigen;
FileData : Text;
begin
with Data do
begin
// Read the header
OpenRead(FileData, Path);
ReadLn(FileData, S);
NVars := SubstrCount(S, Tab);
// Read the data
InitAntigens(Data);
NClasses := 1;
SetLength(Antigen.x, NVars);
repeat
for i := 0 to NVars - 1 do
Read(FileData, Antigen.x[i]);
ReadLn(FileData, Antigen.Class_);
if Antigen.Class_ >= NClasses then
Inc(NClasses);
AppendAntigen(Data, Antigen);
until EoF(FileData);
Close(FileData);
end;
end;
{-----------------------<< Antibodies >>--------------------------------------------}
// ABTo := ABFrom
procedure AssignAntibody(
var ABTo : TAntibody;
const ABFrom : TAntibody);
begin
// Problem-specific fields
ABTo.x := Copy(ABFrom.x);
ABTo.DimWeight := Copy(ABFrom.DimWeight);
ABTo.Radius := ABFrom.Radius;
ABTo.Metric := ABFrom.Metric;
// Generic fields
ABTo.SumW := ABFrom.SumW;
ABTo.SumWCorrect := ABFrom.SumWCorrect;
ABTo.Accuracy := ABFrom.Accuracy;
ABTo.KShare := ABFrom.KShare;
ABTo.Fitness := ABFrom.Fitness;
ABTo.MajorityClass := ABFrom.MajorityClass;
ABTo.ClassDistr := Copy(ABFrom.ClassDistr);
end;
// ABsTo := ABsFrom
procedure CopyAntibodies(
var ABsTo : TAntibodies;
const ABsFrom : TAntibodies);
var
i : Integer;
begin
ABsTo.N := ABsFrom.N;
ABsTo.Accuracy := ABsFrom.Accuracy;
ABsTo.Coverage := ABsFrom.Coverage;
ABsTo.OrderFitness := Copy(ABsFrom.OrderFitness);
ABsTo.OrderSumW := Copy(ABsFrom.OrderSumW);
SetLength(ABsTo._, ABsTo.N);
for i := 0 to ABsTo.N - 1 do
AssignAntibody(ABsTo._[i], ABsFrom._[i]);
end;
// Root mean square based measure of distance between A and B
function DistanceRMS(
const A, B : TRealArray
) : Real;
var
i : Integer;
Sum : Real;
begin
Sum := 0;
for i := 0 to Length(A) - 1 do
Sum := Sum + Sqr(A[i] - B[i]);
Result := Sqrt(Sum / Length(A));
end;
// Return the distance between the Antigen and the Antibody
function Distance(
const Antigen : TAntigen;
const Antibody : TAntibody
) : Real;
var
i, NVars : Integer;
d : TRealArray;
begin
NVars := Length(Antibody.x);
SetLength(d, NVars);
for i := 0 to NVars - 1 do
d[i] := Power(Abs(Antigen.x[i] - Antibody.x[i]), Antibody.Metric);
Result := Power(WeightedAverage(d, Antibody.DimWeight), 1 / Antibody.Metric);
end;
// Return a random blending factor depending on CrossoverType
function RandCrossAlpha : Real;
begin
case CrossoverType of
ctBinary : Result := Random(2);
ctIntermediate : Result := Random;
ctMidpoint : Result := 1 / 2;
else Result := 1 / 2;
Assert(False);
end;
end;
// Create a Child by crossing over ParentA and ParentB
// #HACK need a parameter iterator?
procedure Crossover(
var Child : TAntibody;
const ParentA,
ParentB : TAntibody);
var
i, NVars : Integer;
begin
// Center coordinates
NVars := Length(ParentA.x);
SetLength(Child.x, NVars);
for i := 0 to NVars - 1 do
Child.x[i] := Blend(ParentA.x[i], ParentB.x[i], RandCrossAlpha);
// Dimension weights
SetLength(Child.DimWeight, NVars);
for i := 0 to NVars - 1 do
Child.DimWeight[i] := Blend(ParentA.DimWeight[i], ParentB.DimWeight[i], RandCrossAlpha);
Normalize(Child.DimWeight, normUnitSum);
// Radius and metric
Child.Radius := Blend(ParentA.Radius, ParentB.Radius, RandCrossAlpha);
Child.Metric := Blend(ParentA.Metric, ParentB.Metric, RandCrossAlpha);
end;
// Mutate the Antibody using a given mutation Rate
// #HACK need a parameter iterator?
procedure Mutate(
var Antibody : TAntibody;
Rate : Real);
var
i, NVars : Integer;
Changed,
DimWChanged : Boolean;
const
MinStep = 1 / 256;
MaxStep = 1;
RScale = 1 / 4;
begin
Changed := False;
DimWChanged := False;
NVars := Length(Antibody.x);
repeat
// Center coordinates
for i := 0 to NVars - 1 do
if Random < Rate then
begin
Changed := True;
Antibody.x[i] := Antibody.x[i] + RandSign * LogBlend(MinStep, MaxStep, Random);
end;
// Dimension weights
if AdaptDimWeights then
for i := 0 to NVars - 1 do
if Random < Rate then
begin
Changed := True;
DimWChanged := True;
Antibody.DimWeight[i] := Antibody.DimWeight[i] * Exp(RScale * RandGauss);
end;
if DimWChanged then
Normalize(Antibody.DimWeight, normUnitSum);
// Radius
if (Random < Rate) and AdaptRadius then
begin
Changed := True;
Antibody.Radius := Antibody.Radius * Exp(RScale * RandGauss);
end;
// Metric
if (Random < Rate) and AdaptMetric then
begin
Changed := True;
Antibody.Metric := Exp(Sqrt(Ln(2) / 2) * RandGauss + Ln(2));
end;
until Changed;
end;
// Return the Order of Antigens sorted by L2 distance to x
// #HACK should not be in the problem unit
procedure SortByDistance(
var Order : TIntArray;
const Antigens : TAntigens;
const x : TRealArray);
var
i : Integer;
D : TRealArray;
begin
SetLength(D, Antigens.N);
for i := 0 to Antigens.N - 1 do
D[i] := DistanceRMS(Antigens._[i].x, x);
OrderRealArray(Order, D, soAScending);
end;
// Create a population of N Antibodies based on Antigens
procedure InitAntibodies(
var Antibodies : TAntibodies;
N : Integer;
const Antigens : TAntigens);
var
i, j,
NVars : Integer;
Order,
DistOrder : TIntArray;
MeanDist : Real;
begin
Antibodies.N := N;
SetLength(Antibodies._, N);
NVars := Antigens.NVars;
RandPerm(Order, Antigens.N, {Base:} 0);
// Calculate the mean pairwise antigen distance if necessary
if RadiusInit in [riMean, riMeanUniform, riMeanTriangle, riMeanExp] then
begin
MeanDist := 0;
for i := 0 to Antigens.N - 1 do
for j := 0 to i - 1 do
MeanDist := MeanDist + DistanceRMS(Antigens._[i].x, Antigens._[j].x);
MeanDist := MeanDist / NPairs(Antigens.N);
end;
// Initialize the antobodies
for i := 0 to N - 1 do
with Antibodies._[i] do
begin
if RandInit then
begin
SetLength(x, NVars);
for j := 0 to NVars - 1 do
x[j] := RandGauss;
end
else
x := Copy(Antigens._[Order[i mod Antigens.N]].x);
case RadiusInit of
riMean:
Radius := MeanDist;
riMeanUniform:
Radius := MeanDist * Random * 2;
riMeanTriangle:
Radius := MeanDist * (Random + Random);
riMeanExp:
Radius := MeanDist * RandExp;
riDistToNearest:
begin
SortByDistance(DistOrder, Antigens, x);
j := 1;
Radius := 0;
while Radius = 0 do
begin
Radius := DistanceRMS(x, Antigens._[DistOrder[j]].x);
Inc(j);
end;
end;
riDistToRandom:
begin
Radius := 0;
while Radius = 0 do
Radius := DistanceRMS(x, Antigens._[Random(Antigens.N)].x);
end;
else
Radius := 0;
Assert(False);
end;
// #TODO Randomize DimWeights and Metric if adaptive?
Metric := 2;
SetLength(DimWeight, NVars);
for j := 0 to NVars - 1 do
DimWeight[j] := 1;
end;
end;
// Save antibody parameters to Path
procedure SaveAntibodiesStats(
const Path : AnsiString;
const Antibodies : TAntibodies);
var
i, j : Integer;
FileAntibodies : Text;
begin
OpenWrite(FileAntibodies, Path);
WriteLn(FileAntibodies,
'Id' , Tab,
'Fitness' , Tab,
//'Accuracy' , Tab,
//'NShare ' , Tab,
'NBound' , Tab,
'Radius' , Tab,
'Shape' );
for i := 0 to Antibodies.N - 1 do
begin
j := Antibodies.OrderFitness[Antibodies.N - 1 - i];
WriteLn(FileAntibodies,
i , Tab,
Antibodies._[j].Fitness , Tab,
//Antibodies._[j].Accuracy , Tab,
//1 / Antibodies._[j].KShare , Tab,
Antibodies._[j].SumW , Tab,
Antibodies._[j].Radius , Tab,
Antibodies._[j].Metric );
end;
Close(FileAntibodies);
end;
// Save antibody parameters required for visualization to Path
procedure SaveAntibodiesVis(
const Path : AnsiString;
const Antibodies : TAntibodies;
const Antigens : TAntigens);
var
i, j : Integer;
FileAntibodies : Text;
begin
OpenWrite(FileAntibodies, Path);
for i := 0 to Antibodies.N - 1 do
begin
// Coordinates
for j := 0 to High(Antibodies._[i].x) do
Write(FileAntibodies, Antibodies._[i].x[j], Tab);
// Class distribution
for j := 0 to High(Antibodies._[i].ClassDistr) do
Write(FileAntibodies, Antibodies._[i].ClassDistr[j], Tab);
// Radius
Write(FileAntibodies, Antibodies._[i].Radius);
// Indices of bound antigens
for j := 0 to Antigens.N - 1 do
begin
Write(FileAntibodies, Tab);
if (Distance(Antigens._[j], Antibodies._[i]) /
Antibodies._[i].Radius) <= 1 then
Write(FileAntibodies, 1 + j);
end;
WriteLn(FileAntibodies);
end;
Close(FileAntibodies);
end;
end.