-
Notifications
You must be signed in to change notification settings - Fork 0
/
neural_network.hpp
405 lines (348 loc) · 10.3 KB
/
neural_network.hpp
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
#ifndef FILE_NEURAL_NETWORK_SEEN
#define FILE_NEURAL_NETWORK_SEEN
#include <format>
#include <iomanip>
#include <iostream>
#include <math.h>
#include <ostream>
#include <stdexcept>
#include <stdlib.h>
#include <string>
#include <typeinfo>
#include <unordered_map>
#include <vector>
using namespace std;
namespace NN {
template <typename T> class Generator {
public:
Generator(int Seed);
void normal(T L, T R, vector<T>& Data);
};
template <typename D> class Tensor {
public:
Tensor(int Rows, int Cols, Generator<D>& G, int N = 1);
Tensor(float* Data, int Rows, int Cols, int N = 1);
Tensor(int Rows, int Cols, int N = 1);
Tensor(Tensor<D>& T);
void mmul(Tensor<D>& R, Tensor<D>& O);
friend Tensor<D>& operator*(Tensor<D>& L, Tensor<D>& R) {
Tensor<D>* O = new Tensor<D>(L.NRows, R.NCols);
L.mmul(R, *O);
return *O;
};
// TODO: implement elementwise division of tensors (broadcasting)
friend Tensor<D>& operator/(Tensor<D>& L, Tensor<D>& R) {
Tensor<D>* O = new Tensor<D>(L.NRows, R.NCols);
L.mmul(R, *O);
return *O;
};
Tensor<D>& t();
D& operator[](int Index);
Tensor<D>& operator+=(Tensor<D>& R);
Tensor<D>& operator-=(Tensor<D>& R);
Tensor<D>& operator+(Tensor<D>& R);
Tensor<D>& operator-(Tensor<D>& R);
Tensor<D>& tanH();
Tensor<D>& sum();
ostream& streamOut(ostream& OStream);
friend ostream& operator<<(ostream& OStream, Tensor<D>& T) {
return T.streamOut(OStream);
}
int len();
int size();
int rows();
int cols();
const vector<D> data();
private:
vector<D>* Data;
int NCols;
int NRows;
int Dim3;
int Length;
size_t TSize;
};
template <typename T> class IComponent {
public:
virtual Tensor<T>& forward(Tensor<T>&) = 0;
virtual void backward() = 0;
};
template <typename T> class Component : public IComponent<T> {
public:
Component() {}
string name();
// TODO: every component should have a print operator override.
};
template <typename T> class Layer : public Component<T> {
public:
Layer() {}
virtual Tensor<T>& w();
virtual Tensor<T>& b();
ostream& streamOut(ostream& OStream);
friend ostream& operator<<(ostream& OStream, Layer<T>& L) {
return L.streamOut(OStream);
}
protected:
Tensor<T>* W;
Tensor<T>* B;
};
template <typename T> class NeuralNetwork : public Component<T> {
public:
NeuralNetwork() {}
Layer<T>& layer(string LayerName);
protected:
unordered_map<string, Layer<T>*> Layers;
};
template <typename T> class Loss : public Component<T> {
public:
Loss() {}
Tensor<T>& targets();
protected:
Tensor<T>* Targets;
};
template <typename T> Tensor<T>& Loss<T>::targets() { return *Targets; }
template <typename T> class MSE : public Loss<T> {
public:
MSE() {}
Tensor<T>& forward(Tensor<T>& A);
void backward();
};
template <typename T> class LinearLayer : public Layer<T> {
public:
LinearLayer(int SIn, int SOut, Generator<T>& G);
LinearLayer(NN::Layer<T> Comp);
Tensor<T>& forward(Tensor<T>& X);
void backward();
};
template <typename T> class TanH : public Layer<T> {
public:
TanH() {};
Tensor<T>& forward(Tensor<T>& X);
void backward();
};
template <typename T> Generator<T>::Generator(int Seed) { srand(Seed); }
// TODO: improve random number generation quality
template <typename T> void Generator<T>::normal(T L, T R, vector<T>& Data) {
if ((long long)(L - R) - (L - R) != 0) {
throw invalid_argument(
"the range must have an integer length, e.g. 1.5 - .5 = 1");
}
for (int I = 0; I < Data.size(); I++) {
Data[I] = L + (rand() % (int)(R - L)) + (rand() / (T)RAND_MAX);
}
}
template <typename D>
Tensor<D>::Tensor(int Rows, int Cols, Generator<D>& G, int N) {
NCols = Cols;
NRows = Rows;
Dim3 = N;
Length = Cols * Rows * N;
TSize = Length * sizeof(D);
Data = new vector<D>(Length);
G.normal(-1, 1, *Data);
}
template <typename D>
Tensor<D>::Tensor(float* Data, int Rows, int Cols, int N) {
NRows = Rows;
NCols = Cols;
Dim3 = N;
Length = Cols * Rows * N;
TSize = Length * sizeof(D);
Data = new vector<D>(Data, Data + Length);
}
template <typename D> Tensor<D>::Tensor(int Rows, int Cols, int N) {
NRows = Rows;
NCols = Cols;
Dim3 = N;
Length = Cols * Rows * N;
TSize = Length * sizeof(D);
Data = new vector<D>(Length);
}
template <typename D> Tensor<D>::Tensor(Tensor<D>& T) {
NRows = T.rows();
NCols = T.cols();
Dim3 = T.Dim3;
Length = T.cols() * T.rows() * T.Dim3;
TSize = T.Length * sizeof(D);
Data = new vector<D>(T.data());
}
template <typename T> int Tensor<T>::len() { return Length; }
template <typename T> int Tensor<T>::size() { return TSize; }
template <typename T> int Tensor<T>::rows() { return NRows; }
template <typename T> int Tensor<T>::cols() { return NCols; }
// adapt to handle 3D tensors (later ndim tensors)
template <typename D> void Tensor<D>::mmul(Tensor<D>& RS, Tensor<D>& O) {
Tensor<D> LS = *this;
if (LS.cols() != RS.rows())
throw invalid_argument("Inner dimension of input tensors does not match.");
if (O.rows() != LS.rows() && O.cols() != RS.cols())
throw invalid_argument("Provided output tensor is not the correct size.");
for (int R = 0; R < LS.rows(); R++) {
for (int C = 0; C < RS.cols(); C++) {
for (int I = 0; I < LS.cols(); I++) {
O[R * RS.cols() + C] += LS[R * LS.cols() + I] * RS[C + RS.cols() * I];
}
}
}
}
// TODO: everywhere we create a heap variable, free or delete needs to happen
// down the line - destructor?
template <typename D> Tensor<D>& Tensor<D>::t() {
Tensor<D> T = *this;
Tensor<D> Transpose = *(new Tensor<D>(NCols, NRows));
for (int R = 0; R < NRows; R++) {
for (int C = 0; C < NCols; C++) {
Transpose[C * NCols + R] = T[C + R * NCols];
}
}
return &Transpose;
}
template <typename D> D& Tensor<D>::operator[](int Index) {
if (Index >= Length) {
throw invalid_argument("Tensor array index out of bounds.");
}
return (*Data)[Index];
}
template <typename D> Tensor<D>& Tensor<D>::operator+(Tensor<D>& R) {
Tensor<D>& LS = *(new Tensor<D>(*this));
LS += R;
return LS;
};
template <typename D> Tensor<D>& Tensor<D>::operator-(Tensor<D>& RS) {
Tensor<D>& LS = *(new Tensor<D>(*this));
LS -= RS;
return LS;
};
template <typename D> Tensor<D>& Tensor<D>::tanH() {
Tensor<D>& T = *(new Tensor<D>(*this));
for (int R = 0; R < T.rows(); R++) {
for (int C = 0; C < T.cols(); C++) {
T[R * T.cols() + C] = tanh(T[R * T.cols() + C]);
}
}
return T;
};
template <typename D> Tensor<D>& Tensor<D>::sum() {
Tensor<D>& T = *this;
Tensor<D> Sum(1, 1);
for (int R = 0; R < T.rows(); R++) {
for (int C = 0; C < T.cols(); C++) {
Sum[0] += T[R * T.cols() + C];
}
}
return Sum;
}
template <typename D> Tensor<D>& Tensor<D>::operator+=(Tensor<D>& RS) {
Tensor<D>& LS = *this;
if (LS.rows() == RS.rows() && LS.cols() == RS.cols()) {
for (int R = 0; R < LS.rows(); R++) {
for (int C = 0; C < LS.cols(); C++) {
LS[R * LS.cols() + C] += RS[R * LS.cols() + C];
}
}
} else if (LS.cols() == RS.cols()) {
for (int R = 0; R < LS.rows(); R++) {
for (int C = 0; C < LS.cols(); C++) {
LS[R * LS.cols() + C] += RS[C];
}
}
} else if (LS.rows() == RS.rows()) {
for (int R = 0; R < LS.rows(); R++) {
for (int C = 0; C < LS.cols(); C++) {
LS[R * LS.cols() + C] += RS[R];
}
}
} else {
// TODO: improve all error messages to include detailed information
throw invalid_argument(
"Dimensions of input tensors do not match & are not broadcastable.");
}
return LS;
}
template <typename D> Tensor<D>& Tensor<D>::operator-=(Tensor<D>& RS) {
Tensor<D>& LS = *this;
if (LS.rows() == RS.rows() && LS.cols() == RS.cols()) {
for (int R = 0; R < LS.rows(); R++) {
for (int C = 0; C < LS.cols(); C++) {
LS[R * LS.cols() + C] -= RS[R * LS.cols() + C];
}
}
} else if (LS.cols() == RS.cols()) {
for (int R = 0; R < LS.rows(); R++) {
for (int C = 0; C < LS.cols(); C++) {
LS[R * LS.cols() + C] -= RS[C];
}
}
} else if (LS.rows() == RS.rows()) {
for (int R = 0; R < LS.rows(); R++) {
for (int C = 0; C < LS.cols(); C++) {
LS[R * LS.cols() + C] -= RS[R];
}
}
} else {
// TODO: improve all error messages to include detailed information
throw invalid_argument(
"Dimensions of input tensors do not match & are not broadcastable.");
}
return LS;
}
template <typename D> const vector<D> Tensor<D>::data() {
return vector<D>(*Data);
}
template <typename D> ostream& Tensor<D>::streamOut(ostream& OStream) {
Tensor<D>& T = *this;
OStream << "\n";
for (int I = 0; I < T.len(); I++) {
OStream << setw(8) << format("{:.4f}", T.data()[I]) << ' ';
if (I % T.cols() == T.cols() - 1) {
OStream << "\n";
}
}
return OStream;
}
template <typename T> string Component<T>::name() {
return typeid(*this).name();
}
template <typename T> Tensor<T>& Layer<T>::w() { return *W; }
template <typename T> Tensor<T>& Layer<T>::b() { return *B; }
template <typename D> ostream& Layer<D>::streamOut(ostream& OStream) {
Layer<D>& L = *this;
OStream << "-----------------------" << endl;
OStream << L.name() << ": forward\n" << endl;
OStream << "weights: " << L.w() << endl;
OStream << "bias: " << L.b() << endl;
OStream << "-----------------------" << endl;
return OStream;
}
template <typename T> Layer<T>& NeuralNetwork<T>::layer(string LayerName) {
return *this->layers[LayerName];
}
template <typename T> Tensor<T>& MSE<T>::forward(Tensor<T>& A) {
// Tensor<T> Loss = (A - this->Targets).sum() / A.size();
// return A;
return (A - this->targets()).sum() / A.len();
}
template <typename T> void MSE<T>::backward() {
cout << this->name() << ": backward" << endl;
};
template <typename T>
LinearLayer<T>::LinearLayer(int SIn, int SOut, Generator<T>& G) {
this->W = new Tensor<T>(SOut, SIn, G);
this->B = new Tensor<T>(SOut, 1, G);
}
template <typename T> Tensor<T>& LinearLayer<T>::forward(Tensor<T>& X) {
return this->w() * X + this->b();
// Tensor<T>& Logits = this->w() * X;
// Logits += this->b();
// return Logits;
}
template <typename T> void LinearLayer<T>::backward() {
cout << this->name() << ": backward" << endl;
}
template <typename T> Tensor<T>& TanH<T>::forward(Tensor<T>& X) {
return X.tanH();
}
template <typename T> void TanH<T>::backward() {
cout << this->name() << ": backward" << endl;
}
} // namespace NN
#endif /* !FILE_NEURAL_NETWORK_SEEN*/