-
Notifications
You must be signed in to change notification settings - Fork 0
/
Program.cs
718 lines (678 loc) · 30.3 KB
/
Program.cs
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
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
using System.ComponentModel;
namespace Backend
{
internal class Program
{
static void Main(string[] args)
{
Landing();
}
// Generic option chooser utility function that returns the index of the chosen option.
static int ChooseOption(List<string> options, string promptText = "Choose option:")
{
for (int i = 0; i < options.Count; i++)
{
Console.WriteLine($"({i}) {options[i]}");
}
int chosenOption = -1;
do
{
Console.WriteLine(promptText);
try
{
chosenOption = int.Parse(Console.ReadLine());
}
catch
{
Console.WriteLine("Invalid value.");
}
}
// Keeps loop ongoing while a valid choice hasn't been made.
while (!Enumerable.Range(0, options.Count).ToList().Contains(chosenOption));
return chosenOption;
}
static void Landing()
{
Console.WriteLine("Welcome to Cheesecake! A programming environment for AI model building in C#.");
List<string> modelType = new List<string>() { "Linear model (training)", "Non-linear model (demonstration)"};
int modelTypeChoice = ChooseOption(modelType, "Choose model type:");
switch (modelTypeChoice)
{
case 0:
LinearModelBuilder();
break;
case 1:
NonLinearModelBuilder();
break;
default:
// Default should never be executed because of the data validation in ChooseOption(), but a default for switch-case is good practise.
LinearModelBuilder();
break;
}
}
// Allows the user to build a linear model.
// Relatively self-documenting/explanatory code.
static void LinearModelBuilder()
{
LinearModel model = new LinearModel();
List<Layer> layers = new List<Layer>();
int inputSize = 0;
do
{
Console.WriteLine("Enter model input size:");
try
{
inputSize = int.Parse(Console.ReadLine());
}
catch
{
Console.WriteLine("Invalid value.");
}
}
while (inputSize < 1);
InputLayer layer = new InputLayer(inputSize);
layers.Add(layer);
model.AddLayer(layer);
bool addMoreLayers = true;
while (addMoreLayers == true)
{
int units = -1;
do
{
Console.WriteLine("Enter dense layer units:");
try
{
units = int.Parse(Console.ReadLine());
}
catch
{
Console.WriteLine("Invalid value.");
}
}
while (units < 1);
Activation? activation = null;
do
{
int activationChoice = ChooseOption(new List<String>() { "ReLU", "Sigmoid", "Tanh", "SiLU", "None" },
"Choose activation function:");
switch (activationChoice)
{
case 0:
activation = Activation.ReLU;
break;
case 1:
activation = Activation.Sigmoid;
break;
case 2:
activation = Activation.Tanh;
break;
case 3:
activation = Activation.SiLU;
break;
case 4:
activation = Activation.None;
break;
default:
// Should never occur, but having a default case is good C# practice for switch-case.
activation = Activation.None;
break;
}
}
while (activation == null);
WeightInitialisation? weightInitialisation = null;
do
{
int weightInitialisationChoice = ChooseOption(new List<String>() { "Zeroes", "Ones", "Random", "Xavier"},
"Choose weight initialisation function:");
switch (weightInitialisationChoice)
{
case 0:
weightInitialisation = WeightInitialisation.Zeroes;
break;
case 1:
weightInitialisation = WeightInitialisation.Ones;
break;
case 2:
weightInitialisation = WeightInitialisation.Random;
break;
case 3:
weightInitialisation = WeightInitialisation.Xavier;
break;
default:
// Should never occur, but having a default case is good C# practice for switch-case.
weightInitialisation = WeightInitialisation.Xavier;
break;
}
}
while (weightInitialisation == null);
BiasInitialisation? biasInitialisation = null;
do
{
int biasInitialisationChoice = ChooseOption(new List<String>() { "Zeroes", "Ones", "Random", "Xavier" },
"Choose bias initialisation function:");
switch (biasInitialisationChoice)
{
case 0:
biasInitialisation = BiasInitialisation.Zeroes;
break;
case 1:
biasInitialisation = BiasInitialisation.Ones;
break;
case 2:
biasInitialisation = BiasInitialisation.Random;
break;
case 3:
biasInitialisation = BiasInitialisation.Xavier;
break;
default:
// Should never occur, but having a default case is good C# practice for switch-case.
biasInitialisation = BiasInitialisation.Xavier;
break;
}
}
while (biasInitialisation == null);
// Explicit casts needed as activation, weight initialisation, and bias initialisation are nullable.
DenseLayer newLayer = new DenseLayer(units, (Activation)activation,
(WeightInitialisation)weightInitialisation, (BiasInitialisation)biasInitialisation, layers.Last());
layers.Add(newLayer);
model.AddLayer(newLayer);
Console.WriteLine("Add more layers? (Y/N)");
string response = Console.ReadLine();
if (response.ToLower() == "y")
{
continue;
}
else
{
addMoreLayers = false;
}
}
Console.WriteLine("Would you like to load layer parameters from a text file? (Y/N)");
string loadLayerParametersResponse = Console.ReadLine();
while (loadLayerParametersResponse.ToLower() == "y")
{
Console.WriteLine("What is the index of the layer you would like to load layer parameters into?");
int index = -1;
do
{
try
{
index = int.Parse(Console.ReadLine());
if (!Enumerable.Range(0, layers.Count).ToList().Contains(index))
{
// For input integers which aren't in the correct range.
Console.WriteLine("Invalid number.");
}
}
catch
{
// For inputs which are of invalid type.
Console.WriteLine("Invalid number.");
}
}
while (!Enumerable.Range(0, layers.Count).ToList().Contains(index));
Console.WriteLine("What is the file name of the parameters file?");
string parametersFileName = Console.ReadLine();
try
{
((DenseLayer)layers[index]).LoadWeightsAndBias(parametersFileName);
}
catch
{
Console.WriteLine("Incompatible file.");
}
Console.WriteLine("Would you like to load layer parameters into another layer? (Y/N)");
loadLayerParametersResponse = Console.ReadLine();
}
CostFunction? costFunction = null;
do
{
int costFunctionChoice = ChooseOption(new List<String>() { "MSE", "MAE" },
"Choose cost function:");
switch (costFunctionChoice)
{
case 0:
costFunction = CostFunction.MSE;
break;
case 1:
costFunction = CostFunction.MAE;
break;
default:
// Should never occur, but having a default case is good C# practice for switch-case.
costFunction = CostFunction.MSE;
break;
}
}
while (costFunction == null);
model.Compile((CostFunction)costFunction);
int epochs = -1;
do
{
Console.WriteLine("Enter number of epochs to train for:");
try
{
epochs = int.Parse(Console.ReadLine());
}
catch
{
Console.WriteLine("Invalid value.");
}
}
while (epochs < 1);
float learningRate = -1;
do
{
Console.WriteLine("Enter learning rate:");
try
{
learningRate = float.Parse(Console.ReadLine());
}
catch
{
Console.WriteLine("Invalid value.");
}
}
while (learningRate <= 0);
int batchSize = -1;
do
{
Console.WriteLine("Enter batch size:");
try
{
batchSize = int.Parse(Console.ReadLine());
}
catch
{
Console.WriteLine("Invalid value.");
}
}
while (batchSize < 1);
Console.WriteLine("Enter dataset filename:");
string datasetFileName = Console.ReadLine();
if (!datasetFileName.EndsWith(".txt"))
{
datasetFileName += ".txt";
}
Tuple<List<float[]>, List<float[]>>? dataset = null;
while (dataset == null)
{
try
{
dataset = Data.ExtractDataset(datasetFileName, layers[0].GetOutputSize(), layers.Last().GetOutputSize());
}
catch
{
Console.WriteLine("Invalid dataset. Enter dataset filename:");
datasetFileName = Console.ReadLine();
}
}
try
{
model.Train(datasetFileName, epochs, learningRate, batchSize);
}
catch
{
Console.WriteLine("Invalid dataset and/or parameters.");
}
Console.WriteLine("Would you like to save layer parameters to a text file? (Y/N)");
string saveLayerParametersResponse = Console.ReadLine();
while (saveLayerParametersResponse.ToLower() == "y")
{
Console.WriteLine("What is the index of the layer you would like to save layer parameters from?");
int index = -1;
do
{
try
{
index = int.Parse(Console.ReadLine());
if (!Enumerable.Range(0, layers.Count).ToList().Contains(index))
{
// For input integers which aren't in the correct range.
Console.WriteLine("Invalid number.");
}
}
catch
{
// For inputs which are of invalid type.
Console.WriteLine("Invalid number.");
}
}
while (!Enumerable.Range(0, layers.Count).ToList().Contains(index));
Console.WriteLine("Enter filename to save parameters into:");
string file = Console.ReadLine();
try
{
((DenseLayer)model.GetLayers()[index]).SaveWeightsAndBias(file);
Console.WriteLine("Parameters successfully saved.");
}
catch
{
Console.WriteLine("Invalid filename.");
}
Console.WriteLine("Would you like to load layer parameters into another layer? (Y/N)");
saveLayerParametersResponse = Console.ReadLine();
}
}
// Allows the user to build a non-linear model and run it in inference on vectors.
static void NonLinearModelBuilder()
{
ComplexModel model = new ComplexModel();
List<Layer> layers = new List<Layer>();
int inputSize = 0;
do
{
Console.WriteLine("Enter model input size:");
try
{
inputSize = int.Parse(Console.ReadLine());
}
catch
{
Console.WriteLine("Invalid value.");
}
}
while (inputSize < 1);
InputLayer inputLayer = new InputLayer(inputSize);
layers.Add(inputLayer);
model.AddInputLayer(inputLayer);
bool addMoreLayers = true;
while (addMoreLayers == true)
{
int units = -1;
do
{
Console.WriteLine("Enter dense layer units:");
try
{
units = int.Parse(Console.ReadLine());
}
catch
{
Console.WriteLine("Invalid value.");
}
}
while (units < 1);
Activation? activation = null;
do
{
int activationChoice = ChooseOption(new List<String>() { "ReLU", "Sigmoid", "Tanh", "SiLU", "None" },
"Choose activation function:");
switch (activationChoice)
{
case 0:
activation = Activation.ReLU;
break;
case 1:
activation = Activation.Sigmoid;
break;
case 2:
activation = Activation.Tanh;
break;
case 3:
activation = Activation.SiLU;
break;
case 4:
activation = Activation.None;
break;
default:
// Should never occur, but having a default case is good C# practice for switch-case.
activation = Activation.None;
break;
}
}
while (activation == null);
WeightInitialisation? weightInitialisation = null;
do
{
int weightInitialisationChoice = ChooseOption(new List<String>() { "Zeroes", "Ones", "Random", "Xavier" },
"Choose weight initialisation function:");
switch (weightInitialisationChoice)
{
case 0:
weightInitialisation = WeightInitialisation.Zeroes;
break;
case 1:
weightInitialisation = WeightInitialisation.Ones;
break;
case 2:
weightInitialisation = WeightInitialisation.Random;
break;
case 3:
weightInitialisation = WeightInitialisation.Xavier;
break;
default:
// Should never occur, but having a default case is good C# practice for switch-case.
weightInitialisation = WeightInitialisation.Xavier;
break;
}
}
while (weightInitialisation == null);
BiasInitialisation? biasInitialisation = null;
do
{
int biasInitialisationChoice = ChooseOption(new List<String>() { "Zeroes", "Ones", "Random", "Xavier" },
"Choose bias initialisation function:");
switch (biasInitialisationChoice)
{
case 0:
biasInitialisation = BiasInitialisation.Zeroes;
break;
case 1:
biasInitialisation = BiasInitialisation.Ones;
break;
case 2:
biasInitialisation = BiasInitialisation.Random;
break;
case 3:
biasInitialisation = BiasInitialisation.Xavier;
break;
default:
// Should never occur, but having a default case is good C# practice for switch-case.
biasInitialisation = BiasInitialisation.Xavier;
break;
}
}
while (biasInitialisation == null);
Console.WriteLine("Does this layer connect directly and *only* from the immediately previous layer?");
string directConnectionReponse = Console.ReadLine();
if (directConnectionReponse.ToLower() == "y")
{
DenseLayer newLayer = new DenseLayer(units, (Activation)activation,
(WeightInitialisation)weightInitialisation, (BiasInitialisation)biasInitialisation, layers.Last());
model.AddLayer(layers.Last(), newLayer);
layers.Add(newLayer);
}
else
{
int singleOrMultipleIndices = ChooseOption(new List<string>() { "One previous layer",
"Merges multiple previous layers"}, "Does this layer connect from one previous layer or does it merge outputs from multiple previous layers?");
switch (singleOrMultipleIndices)
{
case 0:
// Case for just one previous layer.
Console.WriteLine("Enter index of the previous layer.");
int index = -1;
do
{
try
{
index = int.Parse(Console.ReadLine());
if (!Enumerable.Range(0, layers.Count).ToList().Contains(index))
{
// For input integers which aren't in the correct range.
Console.WriteLine("Invalid number.");
}
}
catch
{
// For inputs which are of invalid type.
Console.WriteLine("Invalid number.");
}
}
while (!Enumerable.Range(0, layers.Count).ToList().Contains(index));
DenseLayer newLayer = new DenseLayer(units, (Activation)activation,
(WeightInitialisation)weightInitialisation, (BiasInitialisation)biasInitialisation, layers[index]);
layers.Add(newLayer);
model.AddLayer(layers[index], newLayer);
break;
case 1:
// Case for multiple previous layers.
Console.WriteLine("How many previous layers is this layer merging?");
int previousLayersNumber = -1;
do
{
try
{
previousLayersNumber = int.Parse(Console.ReadLine());
// This is because a layer *can* have just one input layer, but then control flow shouldn't pass to this method.
// One previous layer should be handled as standard in the above code.
if (previousLayersNumber < 2)
{
Console.WriteLine("Invalid number of input layers.");
}
}
catch
{
Console.WriteLine("Invalid input.");
}
}
while (previousLayersNumber < 2);
int[] layerIndices = new int[previousLayersNumber];
for (int i = 0; i < previousLayersNumber; i++)
{
Console.WriteLine($"Index of layer {i}:");
int layerIndex = -1;
do
{
try
{
layerIndex = int.Parse(Console.ReadLine());
if (layerIndex < 0)
{
Console.WriteLine("Invalid layer index.");
}
}
catch
{
Console.WriteLine("Invalid input.");
}
}
while (!Enumerable.Range(0, layers.Count).ToList().Contains(layerIndex));
layerIndices[i] = layerIndex;
}
if (layerIndices.Distinct().Count() == layerIndices.Count())
{
List<Layer> inputLayers = new List<Layer>();
for (int i = 0; i < layerIndices.Count(); i++)
{
inputLayers.Add(layers[layerIndices[i]]);
}
int mergeTypeChoice = ChooseOption(new List<string>() { "Concatenate", "Add " }, "Choose merge type:");
if (mergeTypeChoice == 0)
{
DenseLayer newMergeLayer = new DenseLayer(units, (Activation)activation,
(WeightInitialisation)weightInitialisation, (BiasInitialisation)biasInitialisation,
previousLayers: inputLayers, mergeType: MergeType.Concatenate);
layers.Add(newMergeLayer);
for (int i = 0; i < layerIndices.Length; i++)
{
model.AddLayer(layers[layerIndices[i]], newMergeLayer);
}
}
else
{
try
{
DenseLayer newMergeLayer = new DenseLayer(units, (Activation)activation,
(WeightInitialisation)weightInitialisation, (BiasInitialisation)biasInitialisation,
previousLayers: inputLayers, mergeType: MergeType.Add);
layers.Add(newMergeLayer);
for (int i = 0; i < layerIndices.Length; i++)
{
model.AddLayer(layers[layerIndices[i]], newMergeLayer);
}
}
catch
{
Console.WriteLine("Invalid merge type selected. Concatenate has been selected instead.");
DenseLayer newMergeLayer = new DenseLayer(units, (Activation)activation,
(WeightInitialisation)weightInitialisation, (BiasInitialisation)biasInitialisation,
previousLayers: inputLayers, mergeType: MergeType.Concatenate);
layers.Add(newMergeLayer);
for (int i = 0; i < layerIndices.Length; i++)
{
model.AddLayer(layers[layerIndices[i]], newMergeLayer);
}
}
}
}
else
{
Console.WriteLine("Invalid layer configuration. Multiple edges are not permitted between two layers.");
Console.WriteLine("Did you input the same index twice?");
}
break;
}
}
Console.WriteLine("Add more layers? (Y/N)");
string response = Console.ReadLine();
if (response.ToLower() == "y")
{
continue;
}
else
{
addMoreLayers = false;
}
}
// Cost function is redundant in this implementation as we are running in inference as a demonstration.
// Holdover from the Model abstract base class.
try
{
model.Compile(CostFunction.MSE);
Console.WriteLine($"The input size of this model is {layers[0].GetOutputSize()}");
float[,] inferenceInput = new float[layers[0].GetOutputSize(), 1];
bool doInference = true;
while (doInference == true)
{
for (int i = 0; i < inferenceInput.GetLength(0); i++)
{
Console.WriteLine($"Enter component {i} of the input vector:");
try
{
float component = float.Parse(Console.ReadLine());
inferenceInput[i, 0] = component;
}
catch
{
Console.WriteLine("Invalid input. Component has been set to 0.");
float component = 0;
inferenceInput[i, 0] = component;
}
}
float[,] inferenceOutput = model.ForwardPropagate(inferenceInput);
Console.WriteLine("Output vector:");
for (int i = 0; i < inferenceOutput.GetLength(0); i++)
{
Console.WriteLine(inferenceOutput[i, 0]);
}
Console.WriteLine("Would you like to continue inference on examples? (Y/N)");
string inferenceResponse = Console.ReadLine();
if (inferenceResponse.ToLower() == "y")
{
doInference = true;
}
else
{
doInference = false;
}
}
}
catch
{
Console.WriteLine("Multiple outputs exposed in model - unsuitable for inference.");
Console.WriteLine("Please try again!");
}
}
}
}