-
-
Notifications
You must be signed in to change notification settings - Fork 51
Expand file tree
/
Copy pathmean_square_error.cpp
More file actions
64 lines (55 loc) · 1.83 KB
/
Copy pathmean_square_error.cpp
File metadata and controls
64 lines (55 loc) · 1.83 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
/**
* @file mean_square_error.cpp
* @brief Program untuk menghitung
* Mean Squared Error (MSE) dari 2 array
* dengan panjang yang sama.
*/
#include <iostream>
#include <vector>
#include <exception>
#include <cmath>
#include <cassert> // assert()
/**
* @brief Fungsi untuk menghitung Mean Squared Error (MSE)
* dari dua array dengan panjang yang sama. Jika panjang kedua array
* tidak sama maka throw invalid_argument exception
* @param arr1 predicted values
* @param arr2 actual values
* @throw invalid_argument The length of both arrays must be the same
* @return Mean Squared Error dari kedua array
*/
double mse(const std::vector<double>& arr1, const std::vector<double>& arr2) {
if (arr1.size() != arr2.size()) {
// throw Error jika panjang kedua array tidak sama.
throw std::invalid_argument("The length of both arrays must be the same.");
}
// variable untuk menampung jumlah squared error
double error_sum = 0.0;
// traverse semua element di kedua array
// dan hitung error nya
for (size_t i = 0UL; i < arr1.size(); i++) {
double error = (arr1.at(i) - arr2.at(i));
double squared_error = (error * error);
error_sum += squared_error;
}
// cast panjang array menjadi double
double n = static_cast<double>(arr1.size());
// hitung mean dari squared error sum dan return hasil nya
double mean_squared_error = error_sum / n;
return mean_squared_error;
}
int main() {
std::vector<double> predict{};
std::vector<double> actual{};
predict = {1.5, 5.1, 7.3, 7.7, 8.0, 3.9};
actual = {2.5, 3.4, 7.0, 7.4, 7.8, 3.9};
std::cout << "MSE: " << mse(predict, actual) << '\n';
// test to throw an exception
try {
predict = {7.5, 4.5, 3.2};
actual = {7.1, 5.5};
std::cout << "MSE: " << mse(predict, actual) << '\n';
} catch (const std::exception& e) {
std::cerr << e.what() << '\n';
}
}