-
Notifications
You must be signed in to change notification settings - Fork 0
MyPR #1
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
IdLeR0
wants to merge
13
commits into
master
Choose a base branch
from
dev
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
MyPR #1
Changes from all commits
Commits
Show all changes
13 commits
Select commit
Hold shift + click to select a range
9ad4af1
activation_function
IdLeR0 a76e442
Sorry, I did not fix python-style in ActivationFunc and LossFunc. I w…
IdLeR0 faedbe7
Sorry, I did not fix python-style in ActivationFunc and LossFunc. I w…
IdLeR0 b84dae7
added adam_optimizer and layer
IdLeR0 8e1823e
added class net
IdLeR0 118b50b
test mnist in development...
IdLeR0 419932a
test mnist in development...
IdLeR0 26792ff
fixed some bugs
IdLeR0 3af6ba8
98% on mnist test
IdLeR0 7cb1fd0
updated code
IdLeR0 0915ac1
eigen 3.4.0
IdLeR0 09ed0cc
added readme
IdLeR0 e2cb266
make tests better
IdLeR0 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,82 @@ | ||
| Language: Cpp | ||
| BasedOnStyle: Google | ||
| IndentWidth: 4 | ||
| AccessModifierOffset: -4 | ||
| ColumnLimit: 100 | ||
| AllowShortFunctionsOnASingleLine: None | ||
| AllowShortIfStatementsOnASingleLine: false | ||
| AllowShortLoopsOnASingleLine: false | ||
| DerivePointerAlignment: true | ||
| KeepEmptyLinesAtTheStartOfBlocks: false | ||
| SortIncludes: Never | ||
| MaxEmptyLinesToKeep: 1 | ||
| InsertTrailingCommas: None | ||
| AlignAfterOpenBracket: Align | ||
| AlignConsecutiveAssignments: None | ||
| AlignOperands: Align | ||
| AllowAllArgumentsOnNextLine: true | ||
| AllowAllConstructorInitializersOnNextLine: true | ||
| AllowAllParametersOfDeclarationOnNextLine: false | ||
| AllowShortBlocksOnASingleLine: Empty | ||
| AllowShortCaseLabelsOnASingleLine: false | ||
| AllowShortLambdasOnASingleLine: Inline | ||
| AlwaysBreakAfterReturnType: None | ||
| AlwaysBreakTemplateDeclarations: Yes | ||
| BinPackArguments: true | ||
| BreakBeforeBraces: Attach | ||
| BraceWrapping: | ||
| AfterCaseLabel: false | ||
| AfterClass: false | ||
| AfterStruct: false | ||
| AfterControlStatement: Never | ||
| AfterEnum: false | ||
| AfterFunction: false | ||
| AfterNamespace: false | ||
| AfterUnion: false | ||
| AfterExternBlock: false | ||
| BeforeCatch: false | ||
| BeforeElse: false | ||
| BeforeLambdaBody: false | ||
| IndentBraces: false | ||
| SplitEmptyFunction: false | ||
| SplitEmptyRecord: false | ||
| SplitEmptyNamespace: false | ||
| BreakBeforeBinaryOperators: None | ||
| BreakBeforeTernaryOperators: true | ||
| BreakConstructorInitializers: BeforeColon | ||
| BreakInheritanceList: BeforeColon | ||
| CompactNamespaces: false | ||
| ContinuationIndentWidth: 4 | ||
| Cpp11BracedListStyle: true | ||
| EmptyLineBeforeAccessModifier: LogicalBlock | ||
| SpaceInEmptyBlock: false | ||
| FixNamespaceComments: true | ||
| IncludeBlocks: Regroup | ||
| IndentCaseLabels: true | ||
| IndentPPDirectives: None | ||
| NamespaceIndentation: None | ||
| ObjCSpaceAfterProperty: false | ||
| ObjCSpaceBeforeProtocolList: true | ||
| PointerAlignment: Left | ||
| ReflowComments: false | ||
| SeparateDefinitionBlocks: Always | ||
| SpaceAfterCStyleCast: false | ||
| SpaceAfterLogicalNot: false | ||
| SpaceAfterTemplateKeyword: false | ||
| SpaceBeforeAssignmentOperators: true | ||
| SpaceBeforeCpp11BracedList: false | ||
| SpaceBeforeCtorInitializerColon: true | ||
| SpaceBeforeInheritanceColon: true | ||
| SpaceBeforeParens: ControlStatements | ||
| SpaceBeforeRangeBasedForLoopColon: true | ||
| SpaceBeforeSquareBrackets: false | ||
| SpaceInEmptyParentheses: false | ||
| SpacesBeforeTrailingComments: 2 | ||
| SpacesInAngles: false | ||
| SpacesInCStyleCastParentheses: false | ||
| SpacesInContainerLiterals: false | ||
| SpacesInParentheses: false | ||
| SpacesInSquareBrackets: false | ||
| Standard: c++20 | ||
| TabWidth: 4 | ||
| UseTab: Never |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,39 @@ | ||
| --- | ||
| Checks: '-*,cppcoreguidelines-avoid-goto,cppcoreguidelines-pro-type-const-cast, google-readability-casting, modernize-replace-random-shuffle, readability-braces-around-statements, readability-container-size-empty, readability-redundant-control-flow, readability-redundant-string-init, modernize-use-nullptr, readability-identifier-naming, google-build-using-namespace' | ||
| HeaderFilterRegex: '\.h$' | ||
| WarningsAsErrors: '*' | ||
| CheckOptions: | ||
| - key: readability-identifier-naming.NamespaceCase | ||
| value: lower_case | ||
| - key: readability-identifier-naming.ClassCase | ||
| value: CamelCase | ||
| - key: readability-identifier-naming.TypedefCase | ||
| value: CamelCase | ||
| - key: readability-identifier-naming.TypeAliasCase | ||
| value: CamelCase | ||
| - key: readability-identifier-naming.PrivateMemberSuffix | ||
| value: '_' | ||
| - key: readability-identifier-naming.StructCase | ||
| value: CamelCase | ||
| - key: readability-identifier-naming.FunctionCase | ||
| value: CamelCase | ||
| - key: readability-identifier-naming.VariableCase | ||
| value: lower_case | ||
| - key: readability-identifier-naming.PrivateMemberCase | ||
| value: lower_case | ||
| - key: readability-identifier-naming.ParameterCase | ||
| value: lower_case | ||
| - key: readability-identifier-naming.GlobalConstantPrefix | ||
| value: k | ||
| - key: readability-identifier-naming.GlobalConstantCase | ||
| value: CamelCase | ||
| - key: readability-identifier-naming.StaticConstantPrefix | ||
| value: k | ||
| - key: readability-identifier-naming.StaticConstantCase | ||
| value: CamelCase | ||
| - key: readability-identifier-naming.ConstexprVariableCase | ||
| value: CamelCase | ||
| - key: readability-identifier-naming.ConstexprVariablePrefix | ||
| value: k | ||
| - key: google-runtime-int.TypeSuffix | ||
| value: _t | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,32 +1,33 @@ | ||
| # Prerequisites | ||
| *.d | ||
|
|
||
| # Compiled Object files | ||
| *.slo | ||
| *.lo | ||
| *.o | ||
| *.obj | ||
|
|
||
| # Precompiled Headers | ||
| *.gch | ||
| *.pch | ||
|
|
||
| # Compiled Dynamic libraries | ||
| *.so | ||
| *.dylib | ||
| *.dll | ||
|
|
||
| # Fortran module files | ||
| *.mod | ||
| *.smod | ||
|
|
||
| # Compiled Static libraries | ||
| *.lai | ||
| *.la | ||
| *.a | ||
| *.lib | ||
|
|
||
| # Executables | ||
| *.exe | ||
| *.out | ||
| *.app | ||
|
|
||
| compile_commands.json | ||
| .cache* | ||
| .vscode* | ||
| build* | ||
|
|
||
|
|
||
|
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,13 @@ | ||
|
|
||
| [submodule "libs/EigenRand"] | ||
| path = libs/EigenRand | ||
| url = https://github.com/bab2min/EigenRand | ||
| [submodule "libs/googletest"] | ||
| path = libs/googletest | ||
| url = https://github.com/google/googletest.git | ||
| [submodule "libs/mnist"] | ||
| path = libs/mnist | ||
| url = https://github.com/wichtounet/mnist.git | ||
| [submodule "libs/Eigen"] | ||
| path = libs/Eigen | ||
| url = https://gitlab.com/libeigen/eigen.git |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,26 @@ | ||
| cmake_minimum_required(VERSION 3.10) | ||
| project(NeuralNetwork LANGUAGES CXX) | ||
|
|
||
| set(CMAKE_CXX_STANDARD 20) | ||
| set(CMAKE_CXX_STANDARD_REQUIRED ON) | ||
|
|
||
| set(CMAKE_EXPORT_COMPILE_COMMANDS ON) | ||
|
|
||
| include_directories( | ||
| ${CMAKE_SOURCE_DIR}/libs/Eigen | ||
| ${CMAKE_SOURCE_DIR}/libs/EigenRand | ||
| ${CMAKE_SOURCE_DIR}/libs/googletest/googletest/include | ||
| ${CMAKE_SOURCE_DIR}/libs/mnist/include | ||
| ${CMAKE_SOURCE_DIR}/src | ||
| ) | ||
|
|
||
| add_subdirectory(${CMAKE_SOURCE_DIR}/libs/googletest) | ||
|
|
||
| add_executable(test_net tests/test_net.cpp src/adam_optimizer.cpp src/net.cpp src/loss_function.cpp src/activation_function.cpp src/dataloader.cpp src/layer.cpp src/random_params.cpp tests/mnist_utils.cpp) | ||
| target_link_libraries(test_net PRIVATE gtest gtest_main) | ||
|
|
||
| enable_testing() | ||
| add_test(NAME test_mnist COMMAND test_mnist) | ||
|
|
||
|
|
||
|
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1 +1,97 @@ | ||
| Это README для *нейросети с 0* | ||
| # Нейросеть с нуля | ||
| В этом проекте реализованы все основные компоненты нейросети на языке c++. | ||
| ## Функции активации | ||
| Проект поддерживает 5 функций активации: | ||
| 1. ```ActivationFunc::Name::Id``` - Id | ||
| 2. ```ActivationFunc::Name::ReLU``` - ReLU | ||
| 3. ```ActivationFunc::Name::Softmax``` - Softmax | ||
| 4. ```ActivationFunc::Name::Sigmoid``` - Sigmoid | ||
| 5. ```ActivationFunc::Name::Tanh``` - Tanh | ||
| ## Функции потерь | ||
| Проект поддерживает 3 функции потерь: | ||
| 1. ```LossFunc::Name::Mae``` - Mean Absolute Error. | ||
| 2. ```LossFunc::Name::Mse``` - Mean Squared Error. | ||
| 3. ```LossFunc::Name::CrossEntropy``` - Cross‑Entropy. | ||
| ## Можно генерировать случайные параметры слоев самому | ||
| Для этого необходимо создать объект класса ```RandomParams``` | ||
| 1. ```GenerateNormalMatrix``` - генерирует матрицу с нормальным распределением (по умолчанию ~ N(0, 1)); | ||
| 2. ```GenerateUniformMatrix``` - генерирует матрицу с равномерным распределением(по умолчанию с Uni(0, 1)); | ||
| 3. ```GenerateConstantMatrix``` - генерирует матрицу, все элементы которой заполнены одним и тем же числом (по умолчанию все элементы равны 0); | ||
| Есть также соответствующие аналоги для векторов (например,```GenerateNormalVector```). | ||
| ## FileReader/FileWriter - отвечают за запись и чтение нейросети с бинарного файла (см. пример ниже) | ||
|
|
||
| ## Процесс использование библиотеки | ||
| Взаимодействия пользователя с нейросетью можно разделить на 4 части: | ||
| построение нейросети, подготовка данных, обучение и тестирование. | ||
| ```cpp | ||
| #include <iostream> | ||
| #include "src/net.h" | ||
| using namespace network; | ||
|
|
||
| int main() { | ||
| // создание нейросети из 2х слоев | ||
| std::vector<Index> layer_sizes{784, 256, 10}; | ||
|
|
||
| // создаем свои параметры для слоев (необязательно) | ||
| RandomParams rnd(42); | ||
| LayerParams first_layer; | ||
| LayerParams second_layer; | ||
| first_layer.weights = rnd.GenerateNormalMatrix(256, 784, 2, 10); // ~N(2, 10); | ||
| first_layer.bias = rnd.GenerateConstantVector(256, 0.01); | ||
| second_layer.weights = rnd.GenerateUniformMatrix(10, 256, -1, 1); // ~Uni(-1, 1); | ||
| second_layer.bias = rnd.GenerateNormalVector(10); // ~ N(0, 1); | ||
| std::vector<LayerParams> layer_params = {first_layer, second_layer}; | ||
|
|
||
| std::vector<ActivationFunc::Name> activation_functions{ | ||
| ActivationFunc::Name::ReLU, ActivationFunc::Name::Softmax}; // Функции активации на слоях | ||
| Net my_model(layer_sizes, activation_functions, layer_params); | ||
|
|
||
| // подготовка данных | ||
| Data train_data; | ||
| Data test_data; | ||
| // чтение базы данных | ||
| // ... | ||
|
|
||
| DataLoader data_loader(std::move(train_data)); | ||
| LossFunc::Name loss_func = LossFunc::Name::CrossEntropy; | ||
| Index batch_size = 70; | ||
| Index num_epochs = 17; | ||
|
|
||
| // Параметры для алгоритма оптимизации Адам | ||
| DataType learning_rate = 3e-4; | ||
| DataType beta1 = 0.9; | ||
| DataType beta2 = 0.99; | ||
| Info print_info = Info::On; // хотим, чтобы при обучении выводилась информация в терминал | ||
|
|
||
| // обучение | ||
| my_model.Train(data_loader, loss_func, batch_size, num_epochs, print_info, learning_rate, beta1, | ||
| beta2); | ||
|
|
||
| // Вычисляем результат на тестовой выборки | ||
| Matrix prediction = my_model.Evaluate(test_data.input); | ||
|
|
||
| // сравниваем prediction по какому-то правилу с test.output | ||
| // ... | ||
|
|
||
| ////////////////////////////////////////////////////////////////// | ||
|
|
||
| //хотим сохранить нейросеть | ||
| FileWriter w("net.bin"); | ||
| w << my_model; | ||
|
|
||
| // хотим выгрузить нейросеть | ||
| Net read_model; | ||
| FileReader r("net.bin"); | ||
| r >> read_model; | ||
| // read_model == my_model | ||
| } | ||
|
|
||
| ``` | ||
|
|
||
|
|
||
|
|
||
|
|
||
|
|
||
|
|
||
|
|
||
|
|
Submodule Eigen
added at
314739
Submodule googletest
added at
4902ea
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.