initial commit
This commit is contained in:
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;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user