fix error 0.5 and add math pdf

This commit is contained in:
2026-11-25 12:18:18 +03:00
parent 0efd4bb8b1
commit 72f0b2c837
6 changed files with 124 additions and 10 deletions

BIN
math/Рашид.pdf Normal file

Binary file not shown.

View File

@@ -46,3 +46,4 @@ deps = [
subdir('src') subdir('src')
subdir('bin') subdir('bin')
subdir('tests')

View File

@@ -2,6 +2,7 @@
#include <hack/logger/logger.hpp> #include <hack/logger/logger.hpp>
#include "utils.hpp" #include "utils.hpp"
#include <array>
#include <math.h> #include <math.h>
// Линейная форма - это прямой расчет прохода ошибки по математиченским формулам. // Линейная форма - это прямой расчет прохода ошибки по математиченским формулам.
@@ -26,7 +27,16 @@ namespace linear
return 1.0 / (1 + r); return 1.0 / (1 + r);
} }
inline void run() // Результат одного шага: новые веса, ошибка и выход сети.
struct result
{
utils::matrix_leaner W_1;
utils::matrix_leaner W_2;
float error;
std::array<float, 3> out;
};
inline result run()
{ {
std::vector<float> Inp = { 1.0, 2.0, 3.0 }; std::vector<float> Inp = { 1.0, 2.0, 3.0 };
std::vector<float> T = { 0.1, 0.2, 0.3 }; std::vector<float> T = { 0.1, 0.2, 0.3 };
@@ -100,10 +110,11 @@ namespace linear
hack::log()("Out 2 =", Out_2); hack::log()("Out 2 =", Out_2);
hack::log()("Out 3 =", Out_3); hack::log()("Out 3 =", Out_3);
// Ошибка // Ошибка: E = (1/2) * sum((Out_j - T_j)^2), как в конспекте.
auto E_1 = std::pow((Out_1 - T[0]), 2); const float E_1 = 0.5f * (Out_1 - T[0]) * (Out_1 - T[0]);
auto E_2 = std::pow((Out_2 - T[1]), 2); const float E_2 = 0.5f * (Out_2 - T[1]) * (Out_2 - T[1]);
auto E_3 = std::pow((Out_3 - T[2]), 2); const float E_3 = 0.5f * (Out_3 - T[2]) * (Out_3 - T[2]);
const float E = E_1 + E_2 + E_3;
hack::log()(); hack::log()();
hack::log()("Ошибка"); hack::log()("Ошибка");
@@ -111,12 +122,13 @@ namespace linear
hack::log()("E 1 =", E_1); hack::log()("E 1 =", E_1);
hack::log()("E 2 =", E_2); hack::log()("E 2 =", E_2);
hack::log()("E 3 =", E_3); hack::log()("E 3 =", E_3);
hack::log()("E =", E);
// ОБРАТНЫЙ ПРОХОД (backward) // ОБРАТНЫЙ ПРОХОД (backward)
// Вклад нейрона в ошибку (дельта) // Вклад нейрона в ошибку (дельта)
auto delta_1_2 = 2 * (Out_1 - T[0]) * Out_1 * (1 - Out_1); const float delta_1_2 = (Out_1 - T[0]) * Out_1 * (1.0f - Out_1);
auto delta_2_2= 2 * (Out_2 - T[1]) * Out_2 * (1 - Out_2); const float delta_2_2 = (Out_2 - T[1]) * Out_2 * (1.0f - Out_2);
auto delta_3_2 = 2 * (Out_3 - T[2]) * Out_3 * (1 - Out_3); const float delta_3_2 = (Out_3 - T[2]) * Out_3 * (1.0f - Out_3);
hack::log()(); hack::log()();
hack::log()("========================="); hack::log()("=========================");
@@ -296,5 +308,7 @@ namespace linear
hack::log()(W_2[0]); hack::log()(W_2[0]);
hack::log()(W_2[1]); hack::log()(W_2[1]);
hack::log()(W_2[2]); hack::log()(W_2[2]);
return { W_1, W_2, E, { Out_1, Out_2, Out_3 } };
} }
} }

View File

@@ -24,7 +24,16 @@ namespace matrix
{ 1.2, 1.5, 1.8 } { 1.2, 1.5, 1.8 }
}; };
inline void run() // Результат одного шага: новые веса, ошибка и выход сети.
struct result
{
utils::matrix<3, 3> W_1;
utils::matrix<3, 3> W_2;
float error;
utils::matrix<3, 1> out;
};
inline result run()
{ {
// ================================================= // =================================================
// ПРЯМОЙ ПРОХОД (forward) // ПРЯМОЙ ПРОХОД (forward)
@@ -50,7 +59,7 @@ namespace matrix
hack::log()("Error 2 = ", Err_2); hack::log()("Error 2 = ", Err_2);
hack::log()("Error 3 = ", Err_3); hack::log()("Error 3 = ", Err_3);
auto Err = 0.5 * (SQR(Err_1) + SQR(Err_2) + SQR(Err_3)); const float Err = 0.5f * (SQR(Err_1) + SQR(Err_2) + SQR(Err_3));
hack::log()("ERROR = ", Err); hack::log()("ERROR = ", Err);
// ================================================= // =================================================
@@ -99,5 +108,6 @@ namespace matrix
auto W_2_new = W_2 - delta_Out.transpose() * Int.transpose() * utils::LEARNING_RATE; auto W_2_new = W_2 - delta_Out.transpose() * Int.transpose() * utils::LEARNING_RATE;
W_2_new.print("W 2 new"); W_2_new.print("W 2 new");
return { W_1_new, W_2_new, Err, Out };
} }
} }

View File

@@ -0,0 +1,81 @@
// Сверка двух реализаций одного шага обучения:
// linear (развёрнутые скалярные формулы) и matrix (матричные операции).
// Обе реализации должны давать одинаковые веса, ошибку и выход.
#include "linear/linear.hpp"
#include "matrix/matrix.hpp"
#include <algorithm>
#include <cmath>
#include <cstddef>
#include <iostream>
#include <sstream>
namespace
{
bool close(float a, float b, float eps = 1e-5f)
{
const float scale = std::max(1.0f, std::max(std::fabs(a), std::fabs(b)));
return std::fabs(a - b) <= eps * scale;
}
int check(float a, float b, const char* name, std::size_t i, std::size_t j)
{
if (close(a, b)) return 0;
std::cerr << name << "[" << i << "][" << j << "]: scalar=" << a
<< ", matrix=" << b << '\n';
return 1;
}
}
int main()
{
// run() обеих реализаций печатает промежуточные значения; для теста
// отправляем этот вывод в буфер, чтобы в лог попадал только результат.
std::ostringstream sink;
auto* old_buf = std::cout.rdbuf(sink.rdbuf());
const auto scalar = linear::run();
const auto matrix = matrix::run();
std::cout.rdbuf(old_buf);
int failures = 0;
for (std::size_t i = 0; i < 3; ++i)
{
for (std::size_t j = 0; j < 3; ++j)
{
failures += check(scalar.W_1[i][j], matrix.W_1(i, j), "W1", i, j);
failures += check(scalar.W_2[i][j], matrix.W_2(i, j), "W2", i, j);
}
}
if (!close(scalar.error, matrix.error))
{
std::cerr << "error: scalar=" << scalar.error
<< ", matrix=" << matrix.error << '\n';
++failures;
}
for (std::size_t j = 0; j < 3; ++j)
{
if (!close(scalar.out[j], matrix.out(j, 0)))
{
std::cerr << "out[" << j << "]: scalar=" << scalar.out[j]
<< ", matrix=" << matrix.out(j, 0) << '\n';
++failures;
}
}
if (failures != 0)
{
std::cerr << "--- captured run output ---\n" << sink.str() << "\n";
std::cerr << failures << " mismatches\n";
return 1;
}
std::cout << "scalar vs matrix: OK\n";
return 0;
}

8
tests/meson.build Normal file
View File

@@ -0,0 +1,8 @@
compare_scalar_matrix = executable(
'compare_scalar_matrix',
'compare_scalar_matrix.cpp',
dependencies : deps,
include_directories : inc,
)
test('compare_scalar_matrix', compare_scalar_matrix)