-
Notifications
You must be signed in to change notification settings - Fork 0
/
nn.cpp
82 lines (63 loc) · 1.69 KB
/
nn.cpp
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
#include <iostream>
#include "Tensor.h"
#include "Operations.h"
#include "nn.h"
/*
Neural network operations
*/
namespace nn{
Module::Module(int in_size, int out_size, bool use_bias)
: in_size(in_size)
, out_size(out_size)
, use_bias(use_bias){}
Module::Module() = default;
Tensor Module::forward(Tensor&){
throw std::runtime_error("Module::forward() -- Not implemented");
}
Tensor Module::operator()(Tensor& x){
return forward(x);
}
std::vector<Tensor*> Module::parameters(){
return {};
}
Module::~Module() = default;
// ---------------------- Linear -------------------------
/** Initialise a linear/dense/fully-connected layer
*
*/
Linear::Linear(int in_size, int out_size, bool use_bias_)
: in_size(in_size)
, out_size(out_size)
, use_bias(use_bias_)
, Module(in_size, out_size, use_bias_)
{
weight = std::make_shared<Tensor>(Tensor::Uniform(Shape{in_size, out_size}));
weight->requires_grad(true);
if( use_bias ){
//bias = std::make_shared<Tensor> (Shape{out_size});
bias = std::make_shared<Tensor>(Tensor::Uniform(Shape{out_size}));
bias->requires_grad(true);
}
}
Tensor Linear::forward(Tensor& x){
/*
Compute the dot product between input x and this->weight
y = xW^T + b
Input: [n, m]
Weight: [m, p]
Out: [n, p]
*/
Tensor ret = x.dot(*weight);
if( use_bias ){
Tensor ret2 = ret + *bias;
return ret2;
}
return ret;
};
Tensor Linear::operator()(Tensor& x){
return forward(x);
}
std::vector<Tensor*> Linear::parameters(){
return {weight.get(), bias.get()};
}
}