initial commit
This commit is contained in:
4
.gitignore
vendored
Executable file
4
.gitignore
vendored
Executable file
@@ -0,0 +1,4 @@
|
||||
build
|
||||
.cache
|
||||
subprojects/*
|
||||
!subprojects/catch2.wrap
|
||||
9
bin/main.cpp
Normal file
9
bin/main.cpp
Normal file
@@ -0,0 +1,9 @@
|
||||
#include <hack/logger/logger.hpp>
|
||||
#include "linear/linear.hpp"
|
||||
#include "matrix/matrix.hpp"
|
||||
|
||||
auto main(int argc, char *argv[]) -> int
|
||||
{
|
||||
// linear::run();
|
||||
matrix::run();
|
||||
}
|
||||
7
bin/meson.build
Executable file
7
bin/meson.build
Executable file
@@ -0,0 +1,7 @@
|
||||
executable(
|
||||
meson.project_name(),
|
||||
'main.cpp',
|
||||
dependencies : deps,
|
||||
cpp_args: args,
|
||||
include_directories : inc
|
||||
)
|
||||
48
meson.build
Executable file
48
meson.build
Executable file
@@ -0,0 +1,48 @@
|
||||
project(
|
||||
meson.current_source_dir().split('/').get(-1),
|
||||
'cpp',
|
||||
version : run_command('git', 'rev-parse', '--short', 'HEAD', check: false).stdout().strip(),
|
||||
default_options : [
|
||||
'warning_level=1',
|
||||
'optimization=3',
|
||||
'cpp_std=c++26'
|
||||
])
|
||||
|
||||
cc = meson.get_compiler('cpp')
|
||||
if cc.get_id() == 'gcc'
|
||||
add_project_arguments(
|
||||
'-Wpedantic',
|
||||
'-Wno-shadow',
|
||||
'-Wno-maybe-uninitialized',
|
||||
'-Wno-volatile',
|
||||
'-Wno-unused-header',
|
||||
language: 'cpp'
|
||||
)
|
||||
endif
|
||||
|
||||
# Общие флаги для GCC и Clang
|
||||
add_project_arguments(
|
||||
'-Wno-unused-but-set-variable',
|
||||
'-Wno-comment',
|
||||
'-Wno-unused-parameter',
|
||||
'-Wno-unused-value',
|
||||
'-Wno-missing-field-initializers',
|
||||
'-Wno-narrowing',
|
||||
'-Wno-deprecated-enum-enum-conversion',
|
||||
'-Wno-format-security',
|
||||
'-Wno-switch',
|
||||
'-Wno-ignored-attributes',
|
||||
'-Wno-unused-variable',
|
||||
'-Wno-unused-function',
|
||||
'-Wno-unknown-pragmas',
|
||||
language: 'cpp'
|
||||
)
|
||||
|
||||
args = []
|
||||
inc = []
|
||||
deps = [
|
||||
subproject('hack').get_variable('hack_dep')
|
||||
]
|
||||
|
||||
subdir('src')
|
||||
subdir('bin')
|
||||
300
src/linear/linear.hpp
Normal file
300
src/linear/linear.hpp
Normal file
@@ -0,0 +1,300 @@
|
||||
#pragma once
|
||||
|
||||
#include <hack/logger/logger.hpp>
|
||||
#include "utils.hpp"
|
||||
#include <math.h>
|
||||
|
||||
// Линейная форма - это прямой расчет прохода ошибки по математиченским формулам.
|
||||
// Т.е. прям в лоб, как это делается для понимания, но без прямого участия матриц.
|
||||
namespace linear
|
||||
{
|
||||
inline float lenear_combination(std::size_t neuron, utils::matrix_leaner W, std::vector<float> neurons_data)
|
||||
{
|
||||
float res = 0.0;
|
||||
|
||||
auto row = W[neuron];
|
||||
|
||||
for (std::size_t index = 0; index < neurons_data.size(); ++index)
|
||||
res += row[index] * neurons_data[index];
|
||||
|
||||
return res;
|
||||
};
|
||||
|
||||
inline float sigmoid(float data)
|
||||
{
|
||||
auto r = std::exp(-data);
|
||||
return 1.0 / (1 + r);
|
||||
}
|
||||
|
||||
inline void run()
|
||||
{
|
||||
std::vector<float> Inp = { 1.0, 2.0, 3.0 };
|
||||
std::vector<float> T = { 0.1, 0.2, 0.3 };
|
||||
|
||||
// Матрица весов слоя 1
|
||||
utils::matrix_leaner W_1 = {
|
||||
{ 0.1, 0.4, 0.7 },
|
||||
{ 0.2, 0.5, 0.8 },
|
||||
{ 0.3, 0.6, 0.9 }
|
||||
};
|
||||
|
||||
// Матрица весов слоя 2
|
||||
utils::matrix_leaner W_2= {
|
||||
{ 1.0, 1.3, 1.6 },
|
||||
{ 1.1, 1.4, 1.7 },
|
||||
{ 1.2, 1.5, 1.8 }
|
||||
};
|
||||
|
||||
// коеффициент обучения
|
||||
float learning_rate = 0.1;
|
||||
|
||||
// =================================================
|
||||
// Прямой проход (forward)
|
||||
// =================================================
|
||||
|
||||
// Слой 1. Линейная комбинация z_1
|
||||
float z_1_1 = lenear_combination(0, W_1, Inp);
|
||||
float z_1_2 = lenear_combination(1, W_1, Inp);
|
||||
float z_1_3 = lenear_combination(2, W_1, Inp);
|
||||
|
||||
hack::log()();
|
||||
hack::log()("=========================");
|
||||
hack::log()("ПРЯМОЙ ПРОХОД (forward)");
|
||||
hack::log()("=========================");
|
||||
hack::log()();
|
||||
hack::log()("Линейная комбинация z1");
|
||||
hack::log()("------------------------");
|
||||
hack::log()("z 1.1 =", z_1_1);
|
||||
hack::log()("z 1.2 =", z_1_2);
|
||||
hack::log()("z 1.3 =", z_1_3);
|
||||
|
||||
// Активация сигмоидой
|
||||
auto Int_1_2 = sigmoid(z_1_1);
|
||||
auto Int_2_2 = sigmoid(z_1_2);
|
||||
auto Int_3_2 = sigmoid(z_1_3);
|
||||
|
||||
hack::log()("Int 1.2 =", Int_1_2);
|
||||
hack::log()("Int 2.2 =", Int_2_2);
|
||||
hack::log()("Int 3.2 =", Int_3_2);
|
||||
|
||||
std::vector<float> Int = { Int_1_2, Int_2_2, Int_3_2 };
|
||||
|
||||
// Слой 1. Линейная комбинация z_2
|
||||
float z_2_1 = lenear_combination(0, W_2, Int);
|
||||
float z_2_2 = lenear_combination(1, W_2, Int);
|
||||
float z_2_3 = lenear_combination(2, W_2, Int);
|
||||
|
||||
hack::log()();
|
||||
hack::log()("Линейная комбинация z2");
|
||||
hack::log()("------------------------");
|
||||
hack::log()("z 2.1 =", z_2_1);
|
||||
hack::log()("z 2.2 =", z_2_2);
|
||||
hack::log()("z 2.3 =", z_2_3);
|
||||
|
||||
// Активация сигмоидой
|
||||
auto Out_1 = sigmoid(z_2_1);
|
||||
auto Out_2 = sigmoid(z_2_2);
|
||||
auto Out_3 = sigmoid(z_2_3);
|
||||
|
||||
hack::log()("Out 1 =", Out_1);
|
||||
hack::log()("Out 2 =", Out_2);
|
||||
hack::log()("Out 3 =", Out_3);
|
||||
|
||||
// Ошибка
|
||||
auto E_1 = std::pow((Out_1 - T[0]), 2);
|
||||
auto E_2 = std::pow((Out_2 - T[1]), 2);
|
||||
auto E_3 = std::pow((Out_3 - T[2]), 2);
|
||||
|
||||
hack::log()();
|
||||
hack::log()("Ошибка");
|
||||
hack::log()("------------------------");
|
||||
hack::log()("E 1 =", E_1);
|
||||
hack::log()("E 2 =", E_2);
|
||||
hack::log()("E 3 =", E_3);
|
||||
|
||||
// ОБРАТНЫЙ ПРОХОД (backward)
|
||||
// Вклад нейрона в ошибку (дельта)
|
||||
auto delta_1_2 = 2 * (Out_1 - T[0]) * Out_1 * (1 - Out_1);
|
||||
auto delta_2_2= 2 * (Out_2 - T[1]) * Out_2 * (1 - Out_2);
|
||||
auto delta_3_2 = 2 * (Out_3 - T[2]) * Out_3 * (1 - Out_3);
|
||||
|
||||
hack::log()();
|
||||
hack::log()("=========================");
|
||||
hack::log()("ОБРАТНЫЙ ПРОХОД (backward)");
|
||||
hack::log()("=========================");
|
||||
hack::log()();
|
||||
hack::log()("Вклад нейрона в ошибку");
|
||||
hack::log()("------------------------");
|
||||
hack::log()("delta 1 2 =", delta_1_2);
|
||||
hack::log()("delta 2 2 =", delta_2_2);
|
||||
hack::log()("delta 3 2 =", delta_3_2);
|
||||
|
||||
// Градиент для скрытого слоя
|
||||
// первый нейрон
|
||||
auto de_dw_1_1 = delta_1_2 * Int_1_2;
|
||||
auto de_dw_1_2 = delta_1_2 * Int_2_2;
|
||||
auto de_dw_1_3 = delta_1_2 * Int_3_2;
|
||||
|
||||
// второй нейрон
|
||||
auto de_dw_2_1 = delta_2_2 * Int_1_2;
|
||||
auto de_dw_2_2 = delta_2_2 * Int_2_2;
|
||||
auto de_dw_2_3 = delta_2_2 * Int_3_2;
|
||||
|
||||
// третий нейрон
|
||||
auto de_dw_3_1 = delta_3_2 * Int_1_2;
|
||||
auto de_dw_3_2 = delta_3_2 * Int_2_2;
|
||||
auto de_dw_3_3 = delta_3_2 * Int_3_2;
|
||||
|
||||
hack::log()();
|
||||
hack::log()("Градиент для скрытого слоя: первый нейрон");
|
||||
hack::log()("------------------------");
|
||||
hack::log()("dE/dW 1.1 =", de_dw_1_1);
|
||||
hack::log()("dE/dW 1.2 =", de_dw_1_2);
|
||||
hack::log()("dE/dW 1.3 =", de_dw_1_3);
|
||||
|
||||
hack::log()();
|
||||
hack::log()("Градиент для скрытого слоя: второй нейрон");
|
||||
hack::log()("------------------------");
|
||||
hack::log()("dE/dW 2.1 =", de_dw_2_1);
|
||||
hack::log()("dE/dW 2.2 =", de_dw_2_2);
|
||||
hack::log()("dE/dW 2.3 =", de_dw_2_3);
|
||||
|
||||
hack::log()();
|
||||
hack::log()("Градиент для скрытого слоя: тертий нейрон");
|
||||
hack::log()("------------------------");
|
||||
hack::log()("dE/dW 3.1 =", de_dw_3_1);
|
||||
hack::log()("dE/dW 3.2 =", de_dw_3_2);
|
||||
hack::log()("dE/dW 3.3 =", de_dw_3_3);
|
||||
|
||||
// Обновление весов для скрытого слоя
|
||||
auto w_new_1_1 = W_2[0][0] - learning_rate * de_dw_1_1;
|
||||
auto w_new_1_2 = W_2[0][1] - learning_rate * de_dw_1_2;
|
||||
auto w_new_1_3 = W_2[0][2] - learning_rate * de_dw_1_3;
|
||||
|
||||
auto w_new_2_1 = W_2[1][0] - learning_rate * de_dw_2_1;
|
||||
auto w_new_2_2 = W_2[1][1] - learning_rate * de_dw_2_2;
|
||||
auto w_new_2_3 = W_2[1][2] - learning_rate * de_dw_2_3;
|
||||
|
||||
auto w_new_3_1 = W_2[2][0] - learning_rate * de_dw_3_1;
|
||||
auto w_new_3_2 = W_2[2][1] - learning_rate * de_dw_3_2;
|
||||
auto w_new_3_3 = W_2[2][2] - learning_rate * de_dw_3_3;
|
||||
|
||||
hack::log()();
|
||||
hack::log()("Новые веса скрытого слоя");
|
||||
hack::log()("------------------------");
|
||||
hack::log()("W 1.1 =", w_new_1_1);
|
||||
hack::log()("W 1.2 =", w_new_1_2);
|
||||
hack::log()("W 1.3 =", w_new_1_3);
|
||||
hack::log()();
|
||||
hack::log()("W 2.1 =", w_new_2_1);
|
||||
hack::log()("W 2.2 =", w_new_2_2);
|
||||
hack::log()("W 2.3 =", w_new_2_3);
|
||||
hack::log()();
|
||||
hack::log()("W 3.1 =", w_new_3_1);
|
||||
hack::log()("W 3.2 =", w_new_3_2);
|
||||
hack::log()("W 3.3 =", w_new_3_3);
|
||||
|
||||
// Обновление весов Inp -> Int
|
||||
// Вклад нейрона в ошибку (дельта)
|
||||
auto delta_1_1 = (delta_1_2 * W_2[0][0] + delta_2_2 * W_2[1][0] + delta_3_2 * W_2[2][0]) * Int_1_2 * (1 - Int_1_2);
|
||||
auto delta_2_1 = (delta_1_2 * W_2[0][1] + delta_2_2 * W_2[1][1] + delta_3_2 * W_2[2][1]) * Int_2_2 * (1 - Int_2_2);
|
||||
auto delta_3_1 = (delta_1_2 * W_2[0][2] + delta_2_2 * W_2[1][2] + delta_3_2 * W_2[2][2]) * Int_3_2 * (1 - Int_3_2);
|
||||
|
||||
hack::log()();
|
||||
hack::log()("Вклад нейрона в ошибку");
|
||||
hack::log()("------------------------");
|
||||
hack::log()("delta 1 1 =", delta_1_1);
|
||||
hack::log()("delta 2 1 =", delta_2_1);
|
||||
hack::log()("delta 3 1 =", delta_3_1);
|
||||
|
||||
// Градиент для входного слоя -> скрытого слоя
|
||||
// первый нейрон
|
||||
auto de_dw_1_1_1 = delta_1_1 * Inp[0];
|
||||
auto de_dw_1_1_2 = delta_1_1 * Inp[1];
|
||||
auto de_dw_1_1_3 = delta_1_1 * Inp[2];
|
||||
|
||||
// второй нейрон
|
||||
auto de_dw_1_2_1 = delta_2_1 * Inp[0];
|
||||
auto de_dw_1_2_2 = delta_2_1 * Inp[1];
|
||||
auto de_dw_1_2_3 = delta_2_1 * Inp[2];
|
||||
|
||||
// третий нейрон
|
||||
auto de_dw_1_3_1 = delta_3_1 * Inp[0];
|
||||
auto de_dw_1_3_2 = delta_3_1 * Inp[1];
|
||||
auto de_dw_1_3_3 = delta_3_1 * Inp[2];
|
||||
|
||||
hack::log()();
|
||||
hack::log()("Градиент для входного слоя -> скрытого слоя: первый нейрон");
|
||||
hack::log()("------------------------");
|
||||
hack::log()("dE/dW 1 1.1 =", de_dw_1_1_1);
|
||||
hack::log()("dE/dW 1 1.2 =", de_dw_1_1_2);
|
||||
hack::log()("dE/dW 1 1.3 =", de_dw_1_1_3);
|
||||
|
||||
hack::log()();
|
||||
hack::log()("Градиент для входного слоя -> скрытого слоя: второй нейрон");
|
||||
hack::log()("------------------------");
|
||||
hack::log()("dE/dW 1 2.1 =", de_dw_1_2_1);
|
||||
hack::log()("dE/dW 1 2.2 =", de_dw_1_2_2);
|
||||
hack::log()("dE/dW 1 2.3 =", de_dw_1_2_3);
|
||||
|
||||
hack::log()();
|
||||
hack::log()("Градиент для входного слоя -> скрытого слоя: тертий нейрон");
|
||||
hack::log()("------------------------");
|
||||
hack::log()("dE/dW 1 3.1 =", de_dw_1_3_1);
|
||||
hack::log()("dE/dW 1 3.2 =", de_dw_1_3_2);
|
||||
hack::log()("dE/dW 1 3.3 =", de_dw_1_3_3);
|
||||
|
||||
// Обновление весов для скрытого слоя
|
||||
auto w_new_1_1_1 = W_1[0][0] - learning_rate * de_dw_1_1_1;
|
||||
auto w_new_1_1_2 = W_1[0][1] - learning_rate * de_dw_1_1_2;
|
||||
auto w_new_1_1_3 = W_1[0][2] - learning_rate * de_dw_1_1_3;
|
||||
|
||||
auto w_new_1_2_1 = W_1[1][0] - learning_rate * de_dw_1_2_1;
|
||||
auto w_new_1_2_2 = W_1[1][1] - learning_rate * de_dw_1_2_2;
|
||||
auto w_new_1_2_3 = W_1[1][2] - learning_rate * de_dw_1_2_3;
|
||||
|
||||
auto w_new_1_3_1 = W_1[2][0] - learning_rate * de_dw_1_3_1;
|
||||
auto w_new_1_3_2 = W_1[2][1] - learning_rate * de_dw_1_3_2;
|
||||
auto w_new_1_3_3 = W_1[2][2] - learning_rate * de_dw_1_3_3;
|
||||
|
||||
hack::log()();
|
||||
hack::log()("Новые веса скрытого слоя");
|
||||
hack::log()("------------------------");
|
||||
hack::log()("W 1 1.1 =", w_new_1_1_1);
|
||||
hack::log()("W 1 1.2 =", w_new_1_1_2);
|
||||
hack::log()("W 1 1.3 =", w_new_1_1_3);
|
||||
hack::log()();
|
||||
hack::log()("W 1 2.1 =", w_new_1_2_1);
|
||||
hack::log()("W 1 2.2 =", w_new_1_2_2);
|
||||
hack::log()("W 1 2.3 =", w_new_1_2_3);
|
||||
hack::log()();
|
||||
hack::log()("W 1 3.1 =", w_new_1_3_1);
|
||||
hack::log()("W 1 3.2 =", w_new_1_3_2);
|
||||
hack::log()("W 1 3.3 =", w_new_1_3_3);
|
||||
|
||||
|
||||
// Итого
|
||||
W_1 = {
|
||||
{ w_new_1_1_1, w_new_1_1_2, w_new_1_1_3 },
|
||||
{ w_new_1_2_1, w_new_1_2_2, w_new_1_2_3 },
|
||||
{ w_new_1_3_1, w_new_1_3_2, w_new_1_3_3 }
|
||||
};
|
||||
|
||||
W_2 = {
|
||||
{ w_new_1_1, w_new_1_2, w_new_1_3 },
|
||||
{ w_new_2_1, w_new_2_2, w_new_2_3 },
|
||||
{ w_new_3_1, w_new_3_2, w_new_3_3 }
|
||||
};
|
||||
|
||||
hack::log()();
|
||||
hack::log()("ИТОГО:");
|
||||
hack::log()("------------------------");
|
||||
hack::log()(W_1[0]);
|
||||
hack::log()(W_1[1]);
|
||||
hack::log()(W_1[2]);
|
||||
hack::log()();
|
||||
hack::log()(W_2[0]);
|
||||
hack::log()(W_2[1]);
|
||||
hack::log()(W_2[2]);
|
||||
}
|
||||
}
|
||||
32
src/linear/utils.hpp
Normal file
32
src/linear/utils.hpp
Normal file
@@ -0,0 +1,32 @@
|
||||
#pragma once
|
||||
|
||||
#include <vector>
|
||||
|
||||
namespace utils
|
||||
{
|
||||
// Это подобие, но не матрица...
|
||||
// применяется только к линейном расчете
|
||||
class matrix_leaner
|
||||
{
|
||||
public:
|
||||
matrix_leaner(std::initializer_list<std::initializer_list<float>> initializer_data)
|
||||
{
|
||||
m_data.reserve(initializer_data.size());
|
||||
for (auto& row : initializer_data) m_data.emplace_back(row);
|
||||
}
|
||||
|
||||
public:
|
||||
// row
|
||||
std::vector<float>& operator[](std::size_t i) { return m_data[i]; }
|
||||
const std::vector<float>& operator[](std::size_t i) const { return m_data[i]; }
|
||||
|
||||
// col
|
||||
float& operator()(std::size_t i, std::size_t j) { return m_data[i][j]; }
|
||||
const float& operator()(std::size_t i, std::size_t j) const { return m_data[i][j]; }
|
||||
|
||||
private:
|
||||
// плохой выбор для матриц (нет непрерывности, кэш-промахи). Лучше один std::vector
|
||||
// см. matrix/utils.hpp
|
||||
std::vector<std::vector<float>> m_data;
|
||||
};
|
||||
}
|
||||
103
src/matrix/matrix.hpp
Normal file
103
src/matrix/matrix.hpp
Normal file
@@ -0,0 +1,103 @@
|
||||
#pragma once
|
||||
|
||||
#include <hack/logger/logger.hpp>
|
||||
#include "utils.hpp"
|
||||
|
||||
// Линейная форма - это прямой расчет прохода ошибки по математиченским формулам.
|
||||
// Т.е. прям в лоб, как это делается для понимания, но без прямого участия матриц.
|
||||
namespace matrix
|
||||
{
|
||||
inline utils::matrix<3, 1> Inp = { { 1.0 }, { 2.0 }, { 3.0 } };
|
||||
inline utils::matrix<3, 1> T = { { 0.1 }, { 0.2 }, { 0.3 } };
|
||||
|
||||
// Матрица весов слоя 1
|
||||
inline utils::matrix<3, 3> W_1 = {
|
||||
{ 0.1, 0.4, 0.7 },
|
||||
{ 0.2, 0.5, 0.8 },
|
||||
{ 0.3, 0.6, 0.9 }
|
||||
};
|
||||
|
||||
// Матрица весов слоя 2
|
||||
inline utils::matrix<3, 3> W_2= {
|
||||
{ 1.0, 1.3, 1.6 },
|
||||
{ 1.1, 1.4, 1.7 },
|
||||
{ 1.2, 1.5, 1.8 }
|
||||
};
|
||||
|
||||
inline void run()
|
||||
{
|
||||
// =================================================
|
||||
// ПРЯМОЙ ПРОХОД (forward)
|
||||
// =================================================
|
||||
|
||||
auto Z_Int = W_1 * Inp;
|
||||
Z_Int.print("Z int");
|
||||
|
||||
auto Int = Z_Int.apply(utils::activations::sigmoid);
|
||||
Int.print("Int");
|
||||
|
||||
|
||||
auto Z_Out = W_2 * Int;
|
||||
Z_Out.print("Z Out");
|
||||
|
||||
auto Out = Z_Out.apply(utils::activations::sigmoid);
|
||||
Out.print("Out");
|
||||
|
||||
auto Err_1 = Out(0, 0) - T(0, 0);
|
||||
auto Err_2 = Out(1, 0) - T(1, 0);
|
||||
auto Err_3 = Out(2, 0) - T(2, 0);
|
||||
hack::log()("Error 1 = ", Err_1);
|
||||
hack::log()("Error 2 = ", Err_2);
|
||||
hack::log()("Error 3 = ", Err_3);
|
||||
|
||||
auto Err = 0.5 * (SQR(Err_1) + SQR(Err_2) + SQR(Err_3));
|
||||
hack::log()("ERROR = ", Err);
|
||||
|
||||
// =================================================
|
||||
// ОБРАТНЫЙ ПРОХОД (backward)
|
||||
// =================================================
|
||||
|
||||
// см. конспект шагов
|
||||
// 1
|
||||
utils::matrix<1, 3> dE_dOut = {{ Err_1, Err_2, Err_3 }};
|
||||
dE_dOut.print("dE/dOut");
|
||||
|
||||
// 2
|
||||
utils::matrix<3, 3> dOut_dZOut = {{ utils::derivative::sigmoid(Out(0, 0)), 0.f, 0.f },
|
||||
{ 0.f, utils::derivative::sigmoid(Out(1, 0)), 0.f },
|
||||
{ 0.f, 0.f, utils::derivative::sigmoid(Out(2, 0))}};
|
||||
dOut_dZOut.print("dOut/dZOut");
|
||||
|
||||
// 3
|
||||
// dZOut_dInt = W_2; см. конспект
|
||||
|
||||
// 4
|
||||
utils::matrix<3, 3> dInt_dZInt = {{ utils::derivative::sigmoid(Int(0, 0)), 0.f, 0.f },
|
||||
{ 0.f, utils::derivative::sigmoid(Int(1, 0)), 0.f },
|
||||
{ 0.f, 0.f, utils::derivative::sigmoid(Int(2, 0))}};
|
||||
// 5
|
||||
// dInt_dW_1 = Inp; см. конспект
|
||||
|
||||
// Собираем все вместе
|
||||
// согасно конспекту обозначим через проомежуточные переменнеы некоторые части выражения:
|
||||
// utils::matrix<3, 3> dE_dW_1 = (dE_dOut * dOut_dZOut * W_2 * dInt_dZInt).transpose() * Inp.transpose();
|
||||
auto delta_Out = dE_dOut * dOut_dZOut;
|
||||
auto delta_Int = delta_Out * W_2 * dInt_dZInt;
|
||||
utils::matrix<3, 3> dE_dW_1 = delta_Int.transpose() * Inp.transpose();
|
||||
dE_dW_1.print("dE/dW");
|
||||
|
||||
// =================================================
|
||||
// ОБНОВЛЕНИЕ ВЕСОВ
|
||||
// =================================================
|
||||
|
||||
// 1. Обновление весов первого слоя
|
||||
auto W_1_new = W_1 - dE_dW_1 * utils::LEARNING_RATE;
|
||||
W_1_new.print("W 1 new");
|
||||
|
||||
// 2. Обновление весов второго слоя
|
||||
// т.к. тут не получается в лоб по конспекту (не дает правило умножение матриц), то нужно транспонировать вычитаемое
|
||||
auto W_2_new = W_2 - delta_Out.transpose() * Int.transpose() * utils::LEARNING_RATE;
|
||||
W_2_new.print("W 2 new");
|
||||
|
||||
}
|
||||
}
|
||||
179
src/matrix/utils.hpp
Normal file
179
src/matrix/utils.hpp
Normal file
@@ -0,0 +1,179 @@
|
||||
#pragma once
|
||||
|
||||
#include <vector>
|
||||
#include <math.h>
|
||||
#include <initializer_list>
|
||||
#include <cassert>
|
||||
#include <stdexcept>
|
||||
#include <hack/logger/logger.hpp>
|
||||
|
||||
#define SQR(x) ((x)*(x))
|
||||
|
||||
namespace utils
|
||||
{
|
||||
// функции активации. можно добавить еще для поиграться
|
||||
namespace activations
|
||||
{
|
||||
inline auto sigmoid = [](auto x) -> float {
|
||||
return 1.f / (1.f + std::exp(-x));
|
||||
};
|
||||
}
|
||||
|
||||
namespace derivative
|
||||
{
|
||||
inline auto sigmoid = [](auto x) -> float {
|
||||
return x * (1 - x);
|
||||
};
|
||||
}
|
||||
|
||||
// коеффициент обучения
|
||||
const float LEARNING_RATE = 0.1;
|
||||
|
||||
// i, j - в матрице тут - это как m, n в матрицах в учебниках
|
||||
// т.е. строка и столбец соответственно
|
||||
template<std::size_t Rows, std::size_t Cols, typename Type = float>
|
||||
class matrix
|
||||
{
|
||||
static_assert(std::is_arithmetic_v<Type>, "matrix element type must be arithmetic");
|
||||
static_assert(Rows > 0 && Cols > 0, "matrix dimensions must be positive");
|
||||
|
||||
public:
|
||||
matrix() : m_data(Rows * Cols, Type{}) {}
|
||||
matrix(Type fill_value) : m_data(Rows * Cols, fill_value) {}
|
||||
matrix(std::initializer_list<std::initializer_list<float>> init)
|
||||
{
|
||||
if (init.size() != Rows) throw std::invalid_argument("matrix: row count mismatch");
|
||||
m_data.reserve(Rows * Cols);
|
||||
|
||||
for (const auto& row : init)
|
||||
{
|
||||
if (row.size() != Cols) throw std::invalid_argument("matrix: column count mismatch");
|
||||
m_data.insert(m_data.end(), row.begin(), row.end());
|
||||
}
|
||||
}
|
||||
|
||||
public:
|
||||
// получаем тут ссылку на элемент матрици
|
||||
// const или не const зависит от нашего контекста
|
||||
Type& operator()(std::size_t i, std::size_t j) { return m_data[i * Cols + j]; }
|
||||
const Type& operator()(std::size_t i, std::size_t j) const { return m_data[i * Cols + j]; }
|
||||
|
||||
public:
|
||||
// Применяем эти методы если не нужна старая матрица
|
||||
// т.е. нужно сохранить промежуточные результаты:
|
||||
|
||||
// Условие совместимости:
|
||||
// A (Rows × Cols) * B (R × C) = C (Rows × C)
|
||||
// столбцы A = строки B
|
||||
// т.е. входящая метрица на которую умножеем должна иметь Cols строк
|
||||
// rm: Cols × C
|
||||
// *this: Rows × Cols
|
||||
// result: Rows × C
|
||||
template<std::size_t C>
|
||||
matrix<Rows, C, Type> operator*(const matrix<Cols, C, Type>& rm) const
|
||||
{
|
||||
matrix<Rows, C, Type> result;
|
||||
|
||||
for (std::size_t i = 0; i < Rows; ++i)
|
||||
{
|
||||
for (std::size_t k = 0; k < Cols; ++k)
|
||||
{
|
||||
Type a = (*this)(i, k);
|
||||
for (std::size_t j = 0; j < C; ++j) result(i, j) += a * rm(k, j);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
// Умножение на скаляр
|
||||
matrix operator*(Type scalar) const
|
||||
{
|
||||
matrix result;
|
||||
for (std::size_t i = 0; i < Rows; ++i)
|
||||
for (std::size_t j = 0; j < Cols; ++j)
|
||||
result(i, j) = (*this)(i, j) * scalar;
|
||||
return result;
|
||||
}
|
||||
|
||||
// Вычитание матриц
|
||||
matrix operator-(const matrix& other) const
|
||||
{
|
||||
matrix result;
|
||||
for (std::size_t i = 0; i < Rows; ++i)
|
||||
for (std::size_t j = 0; j < Cols; ++j)
|
||||
result(i, j) = (*this)(i, j) - other(i, j);
|
||||
return result;
|
||||
}
|
||||
|
||||
// Применяем это если не нужна старая матрица
|
||||
template<typename Activation>
|
||||
matrix& apply(Activation func)
|
||||
{
|
||||
for (std::size_t i = 0; i < Rows; ++i)
|
||||
for (std::size_t j = 0; j < Cols; ++j)
|
||||
(*this)(i, j) = func((*this)(i, j));
|
||||
return *this;
|
||||
}
|
||||
|
||||
// Возвращает транспонированную матрицу: (Rows × Cols) -> (Cols × Rows)
|
||||
matrix<Cols, Rows, Type> transpose() const
|
||||
{
|
||||
matrix<Cols, Rows, Type> result;
|
||||
for (std::size_t i = 0; i < Rows; ++i)
|
||||
for (std::size_t j = 0; j < Cols; ++j)
|
||||
result(j, i) = (*this)(i, j);
|
||||
return result;
|
||||
}
|
||||
|
||||
public:
|
||||
void print(std::string name) const
|
||||
{
|
||||
std::cout << name << ":\n";
|
||||
for (std::size_t i = 0; i < Rows; ++i)
|
||||
{
|
||||
for (std::size_t j = 0; j < Cols; ++j)
|
||||
std::cout << std::fixed << std::setprecision(8) << (*this)(i, j) << ' ';
|
||||
std::cout << '\n';
|
||||
}
|
||||
std::cout << '\n';
|
||||
}
|
||||
private:
|
||||
std::vector<float> m_data;
|
||||
};
|
||||
|
||||
// применяем эта если нужно оставить промежуточные результаты
|
||||
// Условие совместимости:
|
||||
// A (Rows × Cols) * B (R × C) = C (Rows × C)
|
||||
// столбцы A = строки B
|
||||
// т.е. входящая метрица на которую умножеем должна иметь Cols строк
|
||||
// rm: Cols × C
|
||||
// *this: Rows × Cols
|
||||
// result: Rows × C
|
||||
template<std::size_t Rows, std::size_t Cols, std::size_t C, typename Type>
|
||||
inline matrix<Rows, C, Type> operator*(const matrix<Rows, Cols, Type>& a, const matrix<Cols, C, Type>& b)
|
||||
{
|
||||
matrix<Rows, C, Type> result;
|
||||
|
||||
for (std::size_t i = 0; i < Rows; ++i)
|
||||
{
|
||||
for (std::size_t k = 0; k < Cols; ++k)
|
||||
{
|
||||
Type aik = a(i, k);
|
||||
for (std::size_t j = 0; j < C; ++j) result(i, j) += aik * b(k, j);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
// применяем эта если нужно оставить промежуточные результаты
|
||||
template<std::size_t Rows, std::size_t Cols, typename Type, typename Activation>
|
||||
inline matrix<Rows, Cols, Type> apply(const matrix<Rows, Cols, Type>& m, Activation func)
|
||||
{
|
||||
matrix<Rows, Cols, Type> result;
|
||||
for (std::size_t i = 0; i < Rows; ++i)
|
||||
for (std::size_t j = 0; j < Cols; ++j)
|
||||
result(i, j) = func(m(i, j));
|
||||
|
||||
return result;
|
||||
}
|
||||
}
|
||||
8
src/meson.build
Executable file
8
src/meson.build
Executable file
@@ -0,0 +1,8 @@
|
||||
inc += include_directories('.')
|
||||
|
||||
headers = []
|
||||
|
||||
hack_dep = declare_dependency(
|
||||
include_directories: inc,
|
||||
dependencies: deps
|
||||
)
|
||||
Reference in New Issue
Block a user