-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfunctions.cpp
More file actions
70 lines (59 loc) · 1.5 KB
/
Copy pathfunctions.cpp
File metadata and controls
70 lines (59 loc) · 1.5 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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#include<iostream>
#include<vector>
#include<cmath>
#include<algorithm>
#include<cmath>
double relu(double x)
{
return std::max(0.0,x);
}
double relu_derivative(double x)
{
return x > 0 ? 1.0 : 0.0;
}
std::vector<std::vector<double>> softmax(const std::vector<std::vector<double>>& z)
{
std::vector<std::vector<double>> output = z;
// Find max element for numerical stability
double max_val = -std::numeric_limits<double>::infinity();
for (int i = 0; i < z.size(); i++)
{
for (int k = 0; k < z[0].size(); k++)
{
if (z[i][k] > max_val)
max_val = z[i][k];
}
}
// Compute sum of exp(x - max_val)
double sum = 0.0;
for (int i = 0; i < z.size(); i++)
{
for (int k = 0; k < z[0].size(); k++)
{
output[i][k] = std::exp(z[i][k] - max_val);
sum += output[i][k];
}
}
// Normalize
for (int i = 0; i < z.size(); i++)
{
for (int k = 0; k < z[0].size(); k++)
{
output[i][k] /= sum;
}
}
return output;
}
std::vector<std::vector<double>> relu_derivative_of_matrix(const std::vector<std::vector<double>> &matrix)
{
std::vector<std::vector<double>> result = matrix;
for (int i = 0; i < matrix.size(); i++)
{
for (int j = 0; j < matrix[0].size(); j++)
{
result[i][j] = (matrix[i][j] > 0.0) ? 1.0 : 0.0;
}
}
return result;
}
//implementing the cross entropy function