forked from prajjwalmehta123/Lenet5
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathactivation.cpp
More file actions
54 lines (46 loc) · 1.55 KB
/
activation.cpp
File metadata and controls
54 lines (46 loc) · 1.55 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
#include <iostream>
#include <vector>
#include <functional>
#include <cmath>
#include <omp.h>
#include "activation.h"
// Constructor: Initialize any required data
Activation::Activation() {
#ifdef USE_CUDA
gpuImplementation = std::make_unique<ActivationGPU>();
#endif
// No specific initialization needed for ReLU
}
// Forward Propagation
std::vector<std::vector<float>> Activation::forwardProp(const std::vector<std::vector<float>>& input) {
#ifdef USE_CUDA
return gpuImplementation->forward(input);
#endif
size_t batch_size = input.size();
size_t feature_size = input[0].size();
inputImage = input; // Cache input for backpropagation
std::vector<std::vector<float>> output(batch_size, std::vector<float>(feature_size));
#pragma omp parallel for collapse(2)
for (size_t b = 0; b < batch_size; ++b) {
for (size_t f = 0; f < feature_size; ++f) {
output[b][f] = relu(input[b][f]);
}
}
return output;
}
// Backward Propagation
std::vector<std::vector<float>> Activation::backProp(const std::vector<std::vector<float>>& dZ) {
#ifdef USE_CUDA
return gpuImplementation->backward(dZ);
#endif
size_t batch_size = dZ.size();
size_t feature_size = dZ[0].size();
std::vector<std::vector<float>> dA(batch_size, std::vector<float>(feature_size));
#pragma omp parallel for collapse(2)
for (size_t b = 0; b < batch_size; ++b) {
for (size_t f = 0; f < feature_size; ++f) {
dA[b][f] = dZ[b][f] * d_relu(inputImage[b][f]);
}
}
return dA;
}