Compare commits
46 commits
Refactorin
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
aa58f99045 | ||
|
|
ac35897396 | ||
|
|
746f4cf3bd | ||
|
|
754d170616 | ||
|
|
8b4f2e2ccd | ||
|
|
1cfdf93f7c | ||
|
|
e821afdbd5 | ||
|
|
a681833712 | ||
|
|
77b67aa949 | ||
|
|
38fafa672c | ||
|
|
b9c3e93564 | ||
|
|
8ba83737f5 | ||
|
|
2d7fe49598 | ||
|
|
7bf2b88902 | ||
|
|
eec607f7dd | ||
|
|
61339556c7 | ||
|
|
2019d56122 | ||
|
|
e9881ed2b3 | ||
|
|
a282601751 | ||
|
|
b9dba1a92b | ||
|
|
f13d3950b0 | ||
|
|
dce3e264d9 | ||
|
|
411e4db3db | ||
|
|
accb195dd9 | ||
|
|
45f39130c1 | ||
|
|
66ed7afb9f | ||
|
|
2cf75cc1ac | ||
|
|
19f5a77845 | ||
|
|
3557c28392 | ||
|
|
abd888e2f8 | ||
|
|
0140ef3f37 | ||
|
|
37fbaa2e26 | ||
|
|
c87a3da88a | ||
|
|
6557fbadfc | ||
|
|
cb88b2a397 | ||
|
|
26dc807a07 | ||
|
|
8ebb1f7640 | ||
|
|
4682ec6c97 | ||
|
|
ab97604bda | ||
|
|
3349ce7a43 | ||
|
|
0e2c972d0f | ||
|
|
06b87520b5 | ||
|
|
a9992bc8e0 | ||
|
|
2cfa7f708e | ||
|
|
ca242edaf3 | ||
|
|
01c599603f |
12 changed files with 108747 additions and 472 deletions
56
.gitlab-ci.yml
Normal file
56
.gitlab-ci.yml
Normal file
|
|
@ -0,0 +1,56 @@
|
|||
# This file is a template, and might need editing before it works on your project.
|
||||
# You can copy and paste this template into a new `.gitlab-ci.yml` file.
|
||||
# You should not add this template to an existing `.gitlab-ci.yml` file by using the `include:` keyword.
|
||||
#
|
||||
# To contribute improvements to CI/CD templates, please follow the Development guide at:
|
||||
# https://docs.gitlab.com/ee/development/cicd/templates.html
|
||||
# This specific template is located at:
|
||||
# https://gitlab.com/gitlab-org/gitlab/-/blob/master/lib/gitlab/ci/templates/C++.gitlab-ci.yml
|
||||
|
||||
# use the official gcc image, based on debian
|
||||
# can use versions as well, like gcc:5.2
|
||||
# see https://hub.docker.com/_/gcc/
|
||||
|
||||
image: gcc
|
||||
stages:
|
||||
- build
|
||||
- release
|
||||
|
||||
build:
|
||||
stage: build
|
||||
# instead of calling g++ directly you can also use some build toolkit like make
|
||||
# install the necessary build tools when needed
|
||||
before_script:
|
||||
- apt update && apt -y install cmake
|
||||
script:
|
||||
- echo BUILD_JOB_ID=$CI_JOB_ID >> CI_JOB_ID.env
|
||||
- echo "Compiling the code..."
|
||||
- cmake .
|
||||
- cmake --build .
|
||||
|
||||
artifacts:
|
||||
paths:
|
||||
- c_net
|
||||
reports:
|
||||
dotenv: CI_JOB_ID.env
|
||||
|
||||
|
||||
|
||||
release:
|
||||
image: registry.gitlab.com/gitlab-org/release-cli:latest
|
||||
stage: release
|
||||
needs:
|
||||
- job: build
|
||||
|
||||
release:
|
||||
tag_name: $CI_COMMIT_SHORT_SHA'
|
||||
description: "latest"
|
||||
|
||||
assets:
|
||||
links:
|
||||
- name: c_net linux download (precompiled)
|
||||
url: '${CI_PROJECT_URL}/-/jobs/${BUILD_JOB_ID}/artifacts/file/c_net'
|
||||
|
||||
script: echo "Define your deployment script!"
|
||||
|
||||
|
||||
8
.idea/.gitignore
generated
vendored
Normal file
8
.idea/.gitignore
generated
vendored
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
# Default ignored files
|
||||
/shelf/
|
||||
/workspace.xml
|
||||
# Editor-based HTTP Client requests
|
||||
/httpRequests/
|
||||
# Datasource local storage ignored files
|
||||
/dataSources/
|
||||
/dataSources.local.xml
|
||||
104
README.md
104
README.md
|
|
@ -1,92 +1,36 @@
|
|||
# C-net ඞ
|
||||
|
||||
|
||||
|
||||
## Getting started
|
||||
|
||||
To make it easy for you to get started with GitLab, here's a list of recommended next steps.
|
||||
|
||||
Already a pro? Just edit this README.md and make it your own. Want to make it easy? [Use the template at the bottom](#editing-this-readme)!
|
||||
|
||||
## Add your files
|
||||
|
||||
- [ ] [Create](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#create-a-file) or [upload](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#upload-a-file) files
|
||||
- [ ] [Add files using the command line](https://docs.gitlab.com/ee/gitlab-basics/add-file.html#add-a-file-using-the-command-line) or push an existing Git repository with the following command:
|
||||
|
||||
```
|
||||
cd existing_repo
|
||||
git remote add origin https://git-ainf.aau.at/jastornig/c-net.git
|
||||
git branch -M main
|
||||
git push -uf origin main
|
||||
```
|
||||
|
||||
## Integrate with your tools
|
||||
|
||||
- [ ] [Set up project integrations](https://git-ainf.aau.at/jastornig/c-net/-/settings/integrations)
|
||||
|
||||
## Collaborate with your team
|
||||
|
||||
- [ ] [Invite team members and collaborators](https://docs.gitlab.com/ee/user/project/members/)
|
||||
- [ ] [Create a new merge request](https://docs.gitlab.com/ee/user/project/merge_requests/creating_merge_requests.html)
|
||||
- [ ] [Automatically close issues from merge requests](https://docs.gitlab.com/ee/user/project/issues/managing_issues.html#closing-issues-automatically)
|
||||
- [ ] [Enable merge request approvals](https://docs.gitlab.com/ee/user/project/merge_requests/approvals/)
|
||||
- [ ] [Set auto-merge](https://docs.gitlab.com/ee/user/project/merge_requests/merge_when_pipeline_succeeds.html)
|
||||
|
||||
## Test and Deploy
|
||||
|
||||
Use the built-in continuous integration in GitLab.
|
||||
|
||||
- [ ] [Get started with GitLab CI/CD](https://docs.gitlab.com/ee/ci/quick_start/index.html)
|
||||
- [ ] [Analyze your code for known vulnerabilities with Static Application Security Testing(SAST)](https://docs.gitlab.com/ee/user/application_security/sast/)
|
||||
- [ ] [Deploy to Kubernetes, Amazon EC2, or Amazon ECS using Auto Deploy](https://docs.gitlab.com/ee/topics/autodevops/requirements.html)
|
||||
- [ ] [Use pull-based deployments for improved Kubernetes management](https://docs.gitlab.com/ee/user/clusters/agent/)
|
||||
- [ ] [Set up protected environments](https://docs.gitlab.com/ee/ci/environments/protected_environments.html)
|
||||
|
||||
***
|
||||
|
||||
# Editing this README
|
||||
|
||||
When you're ready to make this README your own, just edit this file and use the handy template below (or feel free to structure it however you want - this is just a starting point!). Thank you to [makeareadme.com](https://www.makeareadme.com/) for this template.
|
||||
|
||||
## Suggestions for a good README
|
||||
Every project is different, so consider which of these sections apply to yours. The sections used in the template are suggestions for most open source projects. Also keep in mind that while a README can be too long and detailed, too long is better than too short. If you think your README is too long, consider utilizing another form of documentation rather than cutting out information.
|
||||
|
||||
## Name
|
||||
Choose a self-explaining name for your project.
|
||||
|
||||
## Description
|
||||
Let people know what your project can do specifically. Provide context and add a link to any reference visitors might be unfamiliar with. A list of Features or a Background subsection can also be added here. If there are alternatives to your project, this is a good place to list differentiating factors.
|
||||
|
||||
## Badges
|
||||
On some READMEs, you may see small images that convey metadata, such as whether or not all the tests are passing for the project. You can use Shields to add some to your README. Many services also have instructions for adding a badge.
|
||||
C-net ඞ is a C project designed to read and predict numbers from the MNIST dataset using neural networks.
|
||||
|
||||
## Visuals
|
||||
Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method.
|
||||
|
||||
## Installation
|
||||
Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection.
|
||||
|
||||
## Usage
|
||||
Use examples liberally, and show the expected output if you can. It's helpful to have inline the smallest example of usage that you can demonstrate, while providing links to more sophisticated examples if they are too long to reasonably include in the README.
|
||||
|
||||
## Support
|
||||
Tell people where they can go to for help. It can be any combination of an issue tracker, a chat room, an email address, etc.
|
||||

|
||||
|
||||
## Roadmap
|
||||
If you have ideas for releases in the future, it is a good idea to list them in the README.
|
||||
|
||||
## Contributing
|
||||
State if you are open to contributions and what your requirements are for accepting them.
|
||||
- [x] Implemented an Image Loader for MNIST dataset.
|
||||
- [x] Created a prediction function for recognizing handwritten digits.
|
||||
- [x] Developed matrix calculation methods to support neural network operations.
|
||||
- [x] Added functionality to load and save neural network models.
|
||||
- [x] Successfully trained the network on MNIST images.
|
||||
- [x] Achieved an accuracy rate with a confidence level above 90%.
|
||||
- [ ] Ongoing optimization and code refinement.
|
||||
|
||||
For people who want to make changes to your project, it's helpful to have some documentation on how to get started. Perhaps there is a script that they should run or some environment variables that they need to set. Make these steps explicit. These instructions could also be useful to your future self.
|
||||
## Authors and Acknowledgments
|
||||
This project was brought to you by the following contributors:
|
||||
- Stornig, Jakob
|
||||
- Schleicher, Thomas
|
||||
- Dworski, Daniel
|
||||
- Walcher, Raphael
|
||||
|
||||
You can also document commands to lint the code or run tests. These steps help to ensure high code quality and reduce the likelihood that the changes inadvertently break something. Having instructions for running tests is especially helpful if it requires external setup, such as starting a Selenium server for testing in a browser.
|
||||
We would like to express our gratitude to the following sources, which served as an inspiration and reference:
|
||||
- [MNIST from Scratch](https://github.com/markkraay/mnist-from-scratch) by markkraay
|
||||
- [Neural Network Framework in C](https://medium.com/analytics-vidhya/building-neural-network-framework-in-c-using-backpropagation-8ad589a0752d)
|
||||
- [Simple Neural Network Implementation in C](https://towardsdatascience.com/simple-neural-network-implementation-in-c-663f51447547)
|
||||
- [3Blue1Brown Neural Network Series](https://www.youtube.com/watch?v=aircAruvnKk&list=PLZHQObOWTQDNU6R1_67000Dx_ZCJB-3pi)
|
||||
- [Brotcrunsher's YouTube Videos](https://www.youtube.com/watch?v=oCPT87SvkPM&pp=ygUbYnJvdCBjcnVzaGVyIG5ldXJhbCBuZXp3ZXJr), [Video 2](https://www.youtube.com/watch?v=YIqYBxpv53A&pp=ygUbYnJvdCBjcnVzaGVyIG5ldXJhbCBuZXp3ZXJr), [Video 3](https://youtu.be/EAtQCut6Qno)
|
||||
|
||||
## Authors and acknowledgment
|
||||
Show your appreciation to those who have contributed to the project.
|
||||
## Project Status
|
||||
The project is considered finished, but ongoing optimizations and improvements may still be in progress.
|
||||
|
||||
## License
|
||||
For open source projects, say how it is licensed.
|
||||
|
||||
## Project status
|
||||
If you have run out of energy or time for your project, put a note at the top of the README saying that development has slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or owner, allowing your project to keep going. You can also make an explicit request for maintainers.
|
||||

|
||||
26
image.c
26
image.c
|
|
@ -14,23 +14,27 @@ void big_endian_to_c_uint(const char * bytes, void * target, int size) {
|
|||
|
||||
void read_until_space_or_newline(char * buff, int maxCount, FILE * fptr){
|
||||
int bufferOffset = 0;
|
||||
char c = -1;
|
||||
char c;
|
||||
int counter = 0;
|
||||
do{
|
||||
c = (char)getc(fptr);
|
||||
buff[bufferOffset++] = c;
|
||||
|
||||
}while(!feof(fptr) && c != 0 && c != ' ' && c !='\n');
|
||||
}while(!feof(fptr) && c != 0 && c != ' ' && c !='\n' && counter++ < maxCount);
|
||||
buff[bufferOffset-1] = 0;
|
||||
}
|
||||
|
||||
Image * load_pgm_image(char * image_file_string){
|
||||
FILE * fptr = fopen(image_file_string, "r");
|
||||
if(!fptr){
|
||||
printf("could not open image file. exit\n");
|
||||
exit(1);
|
||||
}
|
||||
Image *image = malloc(sizeof(Image));
|
||||
image->label = -1;
|
||||
|
||||
|
||||
char buffer[100];
|
||||
int magic_number = 0;
|
||||
char buffer[2048];
|
||||
fgets(buffer, 4, fptr);
|
||||
if(buffer[0] != 'P' || buffer[1] != '5'){
|
||||
printf("Wrong file Format");
|
||||
|
|
@ -40,17 +44,16 @@ Image * load_pgm_image(char * image_file_string){
|
|||
fgets(buffer, 1024, fptr);
|
||||
}
|
||||
|
||||
int image_width, image_height, image_length, image_white ;
|
||||
int image_width, image_height, image_white ;
|
||||
read_until_space_or_newline(buffer, 10, fptr);
|
||||
image_width = strtol(buffer, NULL, 10);
|
||||
image_width = (int)strtol(buffer, NULL, 10);
|
||||
|
||||
read_until_space_or_newline(buffer, 10, fptr);
|
||||
image_height = strtol(buffer, NULL, 10);
|
||||
image_height = (int)strtol(buffer, NULL, 10);
|
||||
|
||||
read_until_space_or_newline(buffer, 10, fptr);
|
||||
image_white = strtol(buffer, NULL, 10);
|
||||
image_white = (int)strtol(buffer, NULL, 10);
|
||||
|
||||
image_length = image_width * image_height;
|
||||
|
||||
image->pixel_values = matrix_create(image_height, image_width);
|
||||
for(int i = 0; i < image_height; i++){
|
||||
|
|
@ -68,8 +71,8 @@ Image * load_pgm_image(char * image_file_string){
|
|||
Image** import_images(char* image_file_string, char* label_file_string, int* _number_imported, int count) {
|
||||
printf("Loading Images\n");
|
||||
// create file pointer for the image and label data
|
||||
FILE* image_file = fopen(image_file_string, "r");
|
||||
FILE* label_file = fopen(label_file_string, "r");
|
||||
FILE* image_file = fopen(image_file_string, "rb");
|
||||
FILE* label_file = fopen(label_file_string, "rb");
|
||||
|
||||
// check if the file could be opened
|
||||
if(image_file == NULL || label_file == NULL) {
|
||||
|
|
@ -90,7 +93,6 @@ Image** import_images(char* image_file_string, char* label_file_string, int* _nu
|
|||
fread(word_buffer, 4, 1, label_file);
|
||||
big_endian_to_c_uint(word_buffer, &label_count, buffer_size);
|
||||
|
||||
|
||||
//Read description of file
|
||||
fread(word_buffer, 4, 1, image_file);
|
||||
big_endian_to_c_uint(word_buffer, &magic_number_images, buffer_size);
|
||||
|
|
|
|||
120
main.c
120
main.c
|
|
@ -1,26 +1,122 @@
|
|||
#include <stdio.h>
|
||||
|
||||
#include "matrix.h"
|
||||
#include "image.h"
|
||||
#include "neuronal_network.h"
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <errno.h>
|
||||
#include "util.h"
|
||||
|
||||
int main() {
|
||||
Image** images = import_images("../data/train-images.idx3-ubyte", "../data/train-labels.idx1-ubyte", NULL, 60000);
|
||||
// img_visualize(images[4]);
|
||||
void parsingErrorPrintHelp(){
|
||||
printf("Syntax: c_net [train | predict]\n");
|
||||
printf("commands:\n");
|
||||
printf("train\t train the network\n");
|
||||
printf("predict\t load a pgm image and predict_demo the number\n");
|
||||
exit(1);
|
||||
}
|
||||
|
||||
Neural_Network* nn = new_network(28*28, 16, 10, 0.5);
|
||||
randomize_network(nn, 20);
|
||||
// save_network(nn);
|
||||
void parsingErrorTrain(){
|
||||
printf("invalid syntax\n");
|
||||
printf("Syntax: c_net train [path_to_train-images.idx3-ubyte] [path_to_train-labels.idx1-ubyte] [hidden_layer_count] [neurons_per_layer] [epochs] [learning_rate] [path_to_save_network]\n");
|
||||
exit(1);
|
||||
}
|
||||
|
||||
// Neural_Network* nn = load_network("../networks/test1.txt");
|
||||
void parsingErrorDetect(){
|
||||
printf("invalid syntax\n");
|
||||
printf("Syntax: c_net predict_demo [path_to_network] [image_file]\n");
|
||||
}
|
||||
|
||||
void predict_demo(int argc, char** arguments){
|
||||
if(argc != 2) parsingErrorDetect();
|
||||
char * network_file = arguments[0];
|
||||
char * image_file = arguments[1];
|
||||
|
||||
for (int i = 0; i < 10000; ++i) {
|
||||
Neural_Network * nn = load_network(network_file);
|
||||
Image * image = load_pgm_image(image_file);
|
||||
Matrix * result = predict_image(nn, image);
|
||||
int predicted = matrix_argmax(result);
|
||||
printf("prediction result %d\n", predicted);
|
||||
matrix_print(result);
|
||||
matrix_free(result);
|
||||
}
|
||||
|
||||
void train(int argc, char** arguments) {
|
||||
if (argc != 7) parsingErrorTrain();
|
||||
char *image_file = arguments[0];
|
||||
char *label_file = arguments[1];
|
||||
int hidden_count = (int) strtol(arguments[2], NULL, 10);
|
||||
int neurons_per_layer = (int) strtol(arguments[3], NULL, 10);
|
||||
int epochs = (int) strtol(arguments[4], NULL, 10);
|
||||
if (errno != 0) {
|
||||
printf("hidden_count, neurons_per_layer or epochs could not be parsed!\n");
|
||||
exit(1);
|
||||
}
|
||||
double learning_rate = strtod(arguments[5], NULL);
|
||||
if (errno != 0) {
|
||||
printf("learning_rate could not be parsed!\n");
|
||||
exit(1);
|
||||
}
|
||||
char *save_path = arguments[6];
|
||||
int imported = 0;
|
||||
Image ** images = import_images(image_file, label_file, &imported, 60000);
|
||||
Image ** evaluation_images = images+50000;
|
||||
|
||||
int training_image_count = 50000;
|
||||
int testing_image_count = 10000;
|
||||
|
||||
Neural_Network *nn = new_network(28 * 28, neurons_per_layer, hidden_count, 10, learning_rate);
|
||||
randomize_network(nn, 1);
|
||||
printf("training_network\n");
|
||||
for(int epoch = 1; epoch <= epochs; epoch++){
|
||||
printf("epoch %d\n", epoch);
|
||||
for (int i = 0; i < training_image_count; i++) {
|
||||
if (i % 1000 == 0) {
|
||||
updateBar(i * 100 / imported);
|
||||
}
|
||||
train_network(nn, images[i], images[i]->label);
|
||||
}
|
||||
updateBar(100);
|
||||
printf("\n");
|
||||
printf("accuracy %lf\n", measure_network_accuracy(nn, evaluation_images, testing_image_count));
|
||||
}
|
||||
printf("done training!\n");
|
||||
save_network(nn, save_path);
|
||||
}
|
||||
|
||||
measure_network_accuracy(nn, images, 100);
|
||||
|
||||
|
||||
int main(int argc, char** argv) {
|
||||
// Image** images = import_images("../data/train-images.idx3-ubyte", "../data/train-labels.idx1-ubyte", NULL, 60000);
|
||||
//// img_visualize(images[0]);
|
||||
//// img_visualize(images[1]);
|
||||
//
|
||||
//// matrix_print(images[0]->pixel_values);
|
||||
//// matrix_print(images[1]->pixel_values);
|
||||
//
|
||||
// Neural_Network* nn = new_network(28*28, 40, 5, 10, 0.08);
|
||||
// randomize_network(nn, 1);
|
||||
//// Neural_Network* nn = load_network("../networks/newest_network.txt");
|
||||
//// printf("Done loading!\n");
|
||||
//
|
||||
//// batch_train(nn, images, 20000, 20);
|
||||
//
|
||||
// for (int i = 0; i < 30000; ++i) {
|
||||
// train_network(nn, images[i], images[i]->label);
|
||||
// }
|
||||
//
|
||||
// save_network(nn);
|
||||
//
|
||||
// printf("%lf\n", measure_network_accuracy(nn, images, 10000));
|
||||
if(argc < 2){
|
||||
parsingErrorPrintHelp();
|
||||
exit(1);
|
||||
}
|
||||
if(strcmp(argv[1], "train") == 0){
|
||||
train(argc-2, argv+2);
|
||||
return 0;
|
||||
}
|
||||
if(strcmp(argv[1], "predict") == 0){
|
||||
predict_demo(argc - 2, argv + 2);
|
||||
return 0;
|
||||
}
|
||||
parsingErrorPrintHelp();
|
||||
|
||||
}
|
||||
43
matrix.c
43
matrix.c
|
|
@ -216,21 +216,6 @@ Matrix* scale(Matrix* matrix, double value) {
|
|||
return result_matrix;
|
||||
}
|
||||
|
||||
Matrix* addScalar(Matrix* matrix, double value) {
|
||||
|
||||
// create a copy of the original matrix
|
||||
Matrix* result_matrix = matrix_copy(matrix);
|
||||
|
||||
// iterate over all numbers in the matrix and add the scalar value
|
||||
for (int i = 0; i < result_matrix->rows; i++) {
|
||||
for (int j = 0; j < result_matrix->columns; j++) {
|
||||
result_matrix->numbers[i][j] += value;
|
||||
}
|
||||
}
|
||||
|
||||
// return the copy
|
||||
return result_matrix;
|
||||
}
|
||||
|
||||
Matrix* transpose(Matrix* matrix) {
|
||||
|
||||
|
|
@ -249,16 +234,6 @@ Matrix* transpose(Matrix* matrix) {
|
|||
|
||||
}
|
||||
|
||||
double matrix_sum(Matrix* matrix) {
|
||||
double sum = 0;
|
||||
for (int i = 0; i < matrix->rows; i++) {
|
||||
for (int j = 0; j < matrix->columns; j++) {
|
||||
sum += matrix->numbers[i][j];
|
||||
}
|
||||
}
|
||||
return sum;
|
||||
}
|
||||
|
||||
void matrix_save(Matrix* matrix, char* file_string){
|
||||
|
||||
// open the file in append mode
|
||||
|
|
@ -349,8 +324,10 @@ int matrix_argmax(Matrix* matrix) {
|
|||
printf("ERROR: Matrix is not Mx1 (matrix_argmax)");
|
||||
exit(EXIT_FAILURE);
|
||||
}
|
||||
|
||||
double max_value = 0;
|
||||
int max_index = 0;
|
||||
|
||||
for (int i = 0; i < matrix->rows; i++) {
|
||||
if (matrix->numbers[i][0] > max_value) {
|
||||
max_value = matrix->numbers[i][0];
|
||||
|
|
@ -382,3 +359,19 @@ void matrix_randomize(Matrix* matrix, int n) {
|
|||
}
|
||||
}
|
||||
}
|
||||
|
||||
Matrix* matrix_add_bias(Matrix* matrix) {
|
||||
if(matrix->columns != 1) {
|
||||
printf("ERROR: The size of the matrix does not match an input matrix! (matrix_add_bias)");
|
||||
exit(1);
|
||||
}
|
||||
|
||||
Matrix* result = matrix_create(matrix->rows + 1, matrix->columns);
|
||||
|
||||
result->numbers[0][0] = 1.0;
|
||||
for (int i = 0; i < matrix->rows; ++i) {
|
||||
result->numbers[i + 1][0] = matrix->numbers[i][0];
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
6
matrix.h
6
matrix.h
|
|
@ -21,6 +21,7 @@ Matrix* load_next_matrix(FILE * save_file);
|
|||
void matrix_randomize(Matrix* matrix, int n); // don't understand the usage of the n
|
||||
int matrix_argmax(Matrix* matrix);
|
||||
Matrix* matrix_flatten(Matrix* matrix, int axis);
|
||||
Matrix* matrix_add_bias(Matrix* matrix);
|
||||
|
||||
/*
|
||||
* These methods won't change or free the input matrix.
|
||||
|
|
@ -35,9 +36,4 @@ Matrix* subtract(Matrix* matrix1, Matrix* matrix2);
|
|||
Matrix* dot(Matrix* matrix1, Matrix* matrix2);
|
||||
Matrix* apply(double (*function)(double), Matrix* matrix);
|
||||
Matrix* scale(Matrix* matrix, double value);
|
||||
Matrix* addScalar(Matrix* matrix, double value);
|
||||
Matrix* transpose(Matrix* matrix);
|
||||
double matrix_sum(Matrix* matrix);
|
||||
|
||||
|
||||
|
||||
|
|
|
|||
44872
networks/89.txt
Normal file
44872
networks/89.txt
Normal file
File diff suppressed because it is too large
Load diff
63384
networks/90.txt
Normal file
63384
networks/90.txt
Normal file
File diff suppressed because it is too large
Load diff
|
|
@ -1,45 +0,0 @@
|
|||
4
|
||||
2
|
||||
3
|
||||
2
|
||||
1
|
||||
-0.2195067977
|
||||
-0.1657067977
|
||||
2
|
||||
4
|
||||
0.0297932023
|
||||
0.0289932023
|
||||
-0.2106067977
|
||||
-0.0132067977
|
||||
-0.1003067977
|
||||
-0.0923067977
|
||||
-0.1315067977
|
||||
0.1174932023
|
||||
2
|
||||
1
|
||||
-0.0374067977
|
||||
0.1903932023
|
||||
2
|
||||
2
|
||||
-0.1219067977
|
||||
-0.1745067977
|
||||
0.0758932023
|
||||
0.0761932023
|
||||
2
|
||||
1
|
||||
-0.0955067977
|
||||
0.0071932023
|
||||
2
|
||||
2
|
||||
-0.1881067977
|
||||
-0.1272067977
|
||||
-0.1149067977
|
||||
-0.1048067977
|
||||
3
|
||||
2
|
||||
0.1665932023
|
||||
-0.2083067977
|
||||
-0.1944067977
|
||||
0.1201932023
|
||||
0.1768932023
|
||||
-0.1408067977
|
||||
|
|
@ -1,67 +1,52 @@
|
|||
#include <stdlib.h>
|
||||
#include "neuronal_network.h"
|
||||
#include <stdio.h>
|
||||
#include <time.h>
|
||||
#include <math.h>
|
||||
#include "util.h"
|
||||
|
||||
double sigmoid(double input);
|
||||
double sigmoid_derivative(double x);
|
||||
Matrix* predict(Neural_Network* network, Matrix* image_data);
|
||||
Matrix* sigmoid_derivative(Matrix* matrix);
|
||||
Matrix *calculate_weights_delta(Matrix *previous_layer_output, Matrix *delta_matrix, double learning_rate);
|
||||
void apply_weights(Neural_Network* network, Matrix* delta_weights_matrix, int index);
|
||||
Matrix* calculate_delta_hidden(Matrix* next_layer_delta, Matrix* weights, Matrix* current_layer_output);
|
||||
|
||||
Matrix* softmax(Matrix* matrix);
|
||||
double square(double input);
|
||||
Neural_Network* new_network(int input_size, int hidden_size, int hidden_amount, int output_size, double learning_rate){
|
||||
Neural_Network* network = malloc(sizeof(Neural_Network));
|
||||
|
||||
double loss_function(Matrix* output_matrix, int image_label);
|
||||
|
||||
Matrix * backPropagation(double learning_rate, Matrix* weights, Matrix* biases, Matrix* current_layer_activation, Matrix* previous_layer_activation, Matrix* sigma_old);
|
||||
|
||||
Neural_Network* new_network(int input_size, int hidden_size, int output_size, double learning_rate){
|
||||
Neural_Network *network = malloc(sizeof(Neural_Network));
|
||||
// initialize networks variables
|
||||
network->hidden_size = hidden_size;
|
||||
network->input_size = input_size;
|
||||
network->hidden_size = hidden_size;
|
||||
network->hidden_amount = hidden_amount;
|
||||
network->output_size = output_size;
|
||||
network->learning_rate = learning_rate;
|
||||
|
||||
network->weights_1 = matrix_create(hidden_size, input_size);
|
||||
network->weights_2 = matrix_create(hidden_size, hidden_size);
|
||||
network->weights_3 = matrix_create(hidden_size, hidden_size);
|
||||
network->weights_output = matrix_create(output_size, hidden_size);
|
||||
network->bias_1 = matrix_create(hidden_size, 1);
|
||||
network->bias_2 = matrix_create(hidden_size, 1);
|
||||
network->bias_3 = matrix_create(hidden_size, 1);
|
||||
network->bias_output = matrix_create(output_size, 1);
|
||||
Matrix** weights = malloc(sizeof(Matrix*) * (hidden_amount + 1));
|
||||
network->weights = weights;
|
||||
|
||||
network->weights[0] = matrix_create(hidden_size, input_size + 1);
|
||||
for(int i=1;i<hidden_amount;i++){
|
||||
network->weights[i] = matrix_create(hidden_size, hidden_size + 1);
|
||||
}
|
||||
network->weights[hidden_amount] = matrix_create(output_size, hidden_size + 1);
|
||||
|
||||
return network;
|
||||
}
|
||||
|
||||
void randomize_network(Neural_Network* network, int scope){
|
||||
matrix_randomize(network->weights_1, scope);
|
||||
matrix_randomize(network->weights_2, scope);
|
||||
matrix_randomize(network->weights_3, scope);
|
||||
matrix_randomize(network->weights_output, scope);
|
||||
matrix_randomize(network->bias_1, scope);
|
||||
matrix_randomize(network->bias_2, scope);
|
||||
matrix_randomize(network->bias_3, scope);
|
||||
matrix_randomize(network->bias_output, scope);
|
||||
for (int i = 0; i < network->hidden_amount + 1; i++) {
|
||||
matrix_randomize(network->weights[i], scope);
|
||||
}
|
||||
}
|
||||
|
||||
//void print_network(Neural_Network* network){};
|
||||
|
||||
void free_network(Neural_Network* network){
|
||||
matrix_free(network->weights_1);
|
||||
matrix_free(network->weights_2);
|
||||
matrix_free(network->weights_3);
|
||||
matrix_free(network->weights_output);
|
||||
matrix_free(network->bias_1);
|
||||
matrix_free(network->bias_2);
|
||||
matrix_free(network->bias_3);
|
||||
matrix_free(network->bias_output);
|
||||
for (int i = 0; i < network->hidden_amount + 1; i++) {
|
||||
matrix_free(network->weights[i]);
|
||||
}
|
||||
free(network->weights);
|
||||
free(network);
|
||||
}
|
||||
|
||||
void save_network(Neural_Network* network) {
|
||||
|
||||
char* file_name = "../networks/newest_network.txt";
|
||||
void save_network(Neural_Network* network, char * file_name) {
|
||||
|
||||
// create file
|
||||
FILE* save_file = fopen(file_name, "w");
|
||||
|
|
@ -75,28 +60,17 @@ void save_network(Neural_Network* network) {
|
|||
// save network size to first line of the file
|
||||
fprintf(save_file, "%d\n", network->input_size);
|
||||
fprintf(save_file, "%d\n", network->hidden_size);
|
||||
fprintf(save_file, "%d\n", network->hidden_amount);
|
||||
fprintf(save_file, "%d\n", network->output_size);
|
||||
|
||||
// close the file
|
||||
fclose(save_file);
|
||||
|
||||
// save first layer
|
||||
matrix_save(network->bias_1, file_name);
|
||||
matrix_save(network->weights_1, file_name);
|
||||
for (int i = 0; i < network->hidden_amount + 1; ++i) {
|
||||
matrix_save(network->weights[i], file_name);
|
||||
}
|
||||
|
||||
// save second layer
|
||||
matrix_save(network->bias_2, file_name);
|
||||
matrix_save(network->weights_2, file_name);
|
||||
|
||||
// save third layer
|
||||
matrix_save(network->bias_3, file_name);
|
||||
matrix_save(network->weights_3, file_name);
|
||||
|
||||
// save output weights
|
||||
matrix_save(network->bias_output, file_name);
|
||||
matrix_save(network->weights_output, file_name);
|
||||
|
||||
printf("Network Saved!");
|
||||
printf("Network Saved!\n");
|
||||
}
|
||||
|
||||
Neural_Network* load_network(char* file) {
|
||||
|
|
@ -117,36 +91,48 @@ Neural_Network* load_network(char* file) {
|
|||
fgets(buffer, MAX_BYTES, save_file);
|
||||
int hidden_size = (int) strtol(buffer, NULL, 10);
|
||||
fgets(buffer, MAX_BYTES, save_file);
|
||||
int hidden_amount = (int) strtol(buffer, NULL, 10);
|
||||
fgets(buffer, MAX_BYTES, save_file);
|
||||
int output_size = (int) strtol(buffer, NULL, 10);
|
||||
|
||||
// create a new network to fill with the saved data
|
||||
Neural_Network* saved_network = new_network(input_size, hidden_size, output_size, 0);
|
||||
Neural_Network* saved_network = new_network(input_size, hidden_size, hidden_amount, output_size, 0);
|
||||
|
||||
// load matrices from file into struct
|
||||
saved_network->bias_1 = load_next_matrix(save_file);
|
||||
saved_network->weights_1 = load_next_matrix(save_file);
|
||||
saved_network->bias_2 = load_next_matrix(save_file);
|
||||
saved_network->weights_2 = load_next_matrix(save_file);
|
||||
saved_network->bias_3 = load_next_matrix(save_file);
|
||||
saved_network->weights_3 = load_next_matrix(save_file);
|
||||
saved_network->bias_output = load_next_matrix(save_file);
|
||||
saved_network->weights_output = load_next_matrix(save_file);
|
||||
for (int i = 0; i < saved_network->hidden_amount + 1; ++i) {
|
||||
saved_network->weights[i] = load_next_matrix(save_file);
|
||||
}
|
||||
|
||||
// return saved network
|
||||
fclose(save_file);
|
||||
return saved_network;
|
||||
}
|
||||
|
||||
void print_network(Neural_Network* network) {
|
||||
for (int i = 0; i < network->hidden_amount; ++i) {
|
||||
matrix_print(network->weights[i]);
|
||||
}
|
||||
}
|
||||
|
||||
double measure_network_accuracy(Neural_Network* network, Image** images, int amount) {
|
||||
int num_correct = 0;
|
||||
|
||||
printf("evaluating network\n");
|
||||
if(amount > 10000) amount = 10000;
|
||||
for (int i = 0; i < amount; i++) {
|
||||
updateBar(i*100/amount);
|
||||
Matrix* prediction = predict_image(network, images[i]);
|
||||
if (matrix_argmax(prediction) == images[i]->label) {
|
||||
|
||||
int guess = matrix_argmax(prediction);
|
||||
int answer = (unsigned char) images[i]->label;
|
||||
|
||||
if (guess == answer) {
|
||||
num_correct++;
|
||||
}
|
||||
|
||||
matrix_free(prediction);
|
||||
}
|
||||
return 1.0 * num_correct / amount;
|
||||
updateBar(100);
|
||||
return ((double) num_correct) / amount;
|
||||
}
|
||||
|
||||
Matrix* predict_image(Neural_Network* network, Image* image){
|
||||
|
|
@ -157,228 +143,221 @@ Matrix* predict_image(Neural_Network* network, Image* image){
|
|||
}
|
||||
|
||||
Matrix* predict(Neural_Network* network, Matrix* image_data) {
|
||||
Matrix* h1_dot = dot(network->weights_1, image_data);
|
||||
Matrix* h1_add = add(h1_dot, network->bias_1);
|
||||
Matrix* h1_outputs = apply(sigmoid, h1_add);
|
||||
|
||||
Matrix* h2_dot = dot(network->weights_2, h1_outputs);
|
||||
Matrix* h2_add = add(h2_dot, network->bias_2);
|
||||
Matrix* h2_outputs = apply(sigmoid, h2_add);
|
||||
Matrix* input = matrix_add_bias(image_data);
|
||||
|
||||
Matrix* h3_dot = dot(network->weights_3, h2_outputs);
|
||||
Matrix* h3_add = add(h3_dot, network->bias_3);
|
||||
Matrix* h3_outputs = apply(sigmoid, h3_add);
|
||||
Matrix* output[network->hidden_amount + 1];
|
||||
for (int i = 0; i < network->hidden_amount + 1; ++i) {
|
||||
Matrix* neuron_input = dot(network->weights[i], input);
|
||||
Matrix* neuron_activation = apply(sigmoid, neuron_input);
|
||||
|
||||
Matrix* final_dot = dot(network->weights_output, h3_outputs);
|
||||
Matrix* final_add = add(final_dot, network->bias_output);
|
||||
Matrix* final_outputs = apply(sigmoid, final_add);
|
||||
output[i] = neuron_activation;
|
||||
|
||||
Matrix* result = softmax(final_outputs);
|
||||
matrix_free(neuron_input);
|
||||
matrix_free(input);
|
||||
|
||||
matrix_free(h1_dot);
|
||||
matrix_free(h1_add);
|
||||
matrix_free(h1_outputs);
|
||||
input = matrix_add_bias(neuron_activation);
|
||||
}
|
||||
|
||||
matrix_free(h2_dot);
|
||||
matrix_free(h2_add);
|
||||
matrix_free(h2_outputs);
|
||||
for (int i = 0; i < network->hidden_amount; ++i) {
|
||||
matrix_free(output[i]);
|
||||
}
|
||||
|
||||
matrix_free(h3_dot);
|
||||
matrix_free(h3_add);
|
||||
matrix_free(h3_outputs);
|
||||
matrix_free(input);
|
||||
|
||||
matrix_free(final_dot);
|
||||
matrix_free(final_add);
|
||||
matrix_free(final_outputs);
|
||||
return output[network->hidden_amount];
|
||||
}
|
||||
|
||||
//void batch_train(Neural_Network* network, Image** images, int amount, int batch_size) {
|
||||
//
|
||||
// for (int i = 0; i < amount; ++i) {
|
||||
//
|
||||
// if(amount % 1000 == 0) {
|
||||
// printf("1k pics!\n");
|
||||
// }
|
||||
//
|
||||
// Matrix* batch_weights[network->hidden_amount + 1];
|
||||
//
|
||||
// for (int j = 0; j < batch_size; ++j) {
|
||||
// Matrix** delta_weights = train_network(network, images[i], images[i]->label);
|
||||
//
|
||||
// for (int k = 0; k < network->hidden_amount + 1; k++) {
|
||||
// if(j == 0) {
|
||||
// batch_weights[k] = delta_weights[k];
|
||||
// continue;
|
||||
// }
|
||||
//
|
||||
// Matrix* temp_result = add(batch_weights[k], delta_weights[k]);
|
||||
//
|
||||
// matrix_free(batch_weights[k]);
|
||||
// matrix_free(delta_weights[k]);
|
||||
//
|
||||
// batch_weights[k] = temp_result;
|
||||
// }
|
||||
//
|
||||
// free(delta_weights);
|
||||
// }
|
||||
//
|
||||
// for (int j = 0; j < network->hidden_amount + 1; ++j) {
|
||||
// Matrix* average_delta_weight = scale(batch_weights[j], (1.0 / batch_size));
|
||||
// apply_weights(network, average_delta_weight, j);
|
||||
//
|
||||
// matrix_free(average_delta_weight);
|
||||
// matrix_free(batch_weights[j]);
|
||||
// }
|
||||
// }
|
||||
//}
|
||||
|
||||
void train_network(Neural_Network* network, Image *image, int label) {
|
||||
|
||||
Matrix* image_data = matrix_flatten(image->pixel_values, 0);
|
||||
Matrix* input = matrix_add_bias(image_data);
|
||||
|
||||
Matrix* output[network->hidden_amount + 1];
|
||||
for (int i = 0; i < network->hidden_amount + 1; ++i) {
|
||||
Matrix* neuron_input = dot(network->weights[i], input);
|
||||
Matrix* neuron_activation = apply(sigmoid, neuron_input);
|
||||
|
||||
output[i] = neuron_activation;
|
||||
|
||||
matrix_free(neuron_input);
|
||||
matrix_free(input);
|
||||
|
||||
input = matrix_add_bias(neuron_activation);
|
||||
}
|
||||
|
||||
// back propagation
|
||||
|
||||
//list to store the new weights
|
||||
Matrix** delta_weights = malloc(sizeof(Matrix*) * (network->hidden_amount + 1));
|
||||
|
||||
// calculate the derivative of the sigmoid function of the input of the result layer
|
||||
Matrix* sigmoid_prime = sigmoid_derivative(output[network->hidden_amount]);
|
||||
|
||||
// create wanted out-put matrix, calculate the difference and delta values (output layer only)
|
||||
Matrix* wanted_output = matrix_create(output[network->hidden_amount]->rows, output[network->hidden_amount]->columns);
|
||||
matrix_fill(wanted_output, 0);
|
||||
wanted_output->numbers[label][0] = 1;
|
||||
Matrix* error = subtract(wanted_output, output[network->hidden_amount]);
|
||||
Matrix* delta = multiply(sigmoid_prime, error);
|
||||
|
||||
//calculate and apply the delta for all weights in out-put layer
|
||||
delta_weights[network->hidden_amount] = calculate_weights_delta(output[network->hidden_amount - 1], delta, network->learning_rate);
|
||||
|
||||
//hidden layers
|
||||
Matrix* previous_delta = delta;
|
||||
for (int i = network->hidden_amount; i > 1; i--) {
|
||||
delta = calculate_delta_hidden(previous_delta, network->weights[i], output[i - 1]);
|
||||
delta_weights[i - 1] = calculate_weights_delta(output[i - 2], delta, network->learning_rate);
|
||||
|
||||
matrix_free(previous_delta);
|
||||
previous_delta = delta;
|
||||
}
|
||||
|
||||
// Input Layer
|
||||
delta = calculate_delta_hidden(previous_delta, network->weights[1], output[0]);
|
||||
delta_weights[0] = calculate_weights_delta(image_data, delta, network->learning_rate);
|
||||
|
||||
for (int i = 0; i < network->hidden_amount + 1; ++i) {
|
||||
apply_weights(network, delta_weights[i], i);
|
||||
}
|
||||
|
||||
// De-allocate stuff
|
||||
matrix_free(image_data);
|
||||
matrix_free(input);
|
||||
|
||||
for (int i = 0; i < network->hidden_amount + 1; ++i) {
|
||||
matrix_free(output[i]);
|
||||
}
|
||||
|
||||
for (int i = 0; i < network->hidden_amount + 1; ++i) {
|
||||
matrix_free(delta_weights[i]);
|
||||
}
|
||||
|
||||
matrix_free(sigmoid_prime);
|
||||
matrix_free(wanted_output);
|
||||
matrix_free(error);
|
||||
matrix_free(delta);
|
||||
matrix_free(previous_delta);
|
||||
|
||||
// return delta_weights;
|
||||
}
|
||||
|
||||
Matrix* calculate_delta_hidden(Matrix* next_layer_delta, Matrix* weights, Matrix* current_layer_output) {
|
||||
|
||||
// remove bias weights from weights
|
||||
Matrix* weights_without_biases = matrix_create(weights->rows, weights->columns - 1);
|
||||
for (int i = 0; i < weights->rows; ++i) {
|
||||
for (int j = 0; j < weights->columns - 1; ++j) {
|
||||
weights_without_biases->numbers[i][j] = weights->numbers[i][j + 1];
|
||||
}
|
||||
}
|
||||
|
||||
// transpose the new weights and multiply with deltas
|
||||
Matrix* transposed_weight_without_biases = transpose(weights_without_biases);
|
||||
Matrix* sum_delta_weights = dot(transposed_weight_without_biases, next_layer_delta);
|
||||
|
||||
//multiply with derivative of current layer output
|
||||
Matrix* sigmoid_prime = sigmoid_derivative(current_layer_output);
|
||||
|
||||
// multiply to find deltas for current layer
|
||||
Matrix* new_deltas = multiply(sigmoid_prime, sum_delta_weights);
|
||||
|
||||
matrix_free(weights_without_biases);
|
||||
matrix_free(transposed_weight_without_biases);
|
||||
matrix_free(sum_delta_weights);
|
||||
matrix_free(sigmoid_prime);
|
||||
|
||||
return new_deltas;
|
||||
}
|
||||
|
||||
void apply_weights(Neural_Network* network, Matrix* delta_weights_matrix, int index) {
|
||||
|
||||
if(index > network->hidden_amount || index < 0) {
|
||||
printf("ERROR: Index out of range! (apply_weights)");
|
||||
exit(1);
|
||||
}
|
||||
if(delta_weights_matrix->rows != network->weights[index]->rows ||
|
||||
delta_weights_matrix->columns != network->weights[index]->columns) {
|
||||
printf("ERROR: Size of weight matrices do not match! (apply_weights)");
|
||||
exit(1);
|
||||
}
|
||||
|
||||
for (int i = 0; i < delta_weights_matrix->rows; i++) {
|
||||
for (int j = 0; j < delta_weights_matrix->columns; j++) {
|
||||
network->weights[index]->numbers[i][j] += delta_weights_matrix->numbers[i][j]; // multiply delta_weights_matrix with learning rate AND - instead of + because soll-ist
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Matrix *calculate_weights_delta(Matrix *previous_layer_output, Matrix *delta_matrix, double learning_rate) {
|
||||
|
||||
Matrix* previous_out_with_one = matrix_add_bias(previous_layer_output);
|
||||
Matrix* transposed_previous_out_with_bias = transpose(previous_out_with_one);
|
||||
Matrix* weights_delta_matrix = dot(delta_matrix, transposed_previous_out_with_bias);
|
||||
|
||||
// scale by learning rate
|
||||
Matrix* result = scale(weights_delta_matrix, learning_rate);
|
||||
|
||||
matrix_free(previous_out_with_one);
|
||||
matrix_free(transposed_previous_out_with_bias);
|
||||
matrix_free(weights_delta_matrix);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
double cost_function(Matrix* calculated, int expected){
|
||||
calculated->numbers[expected] -= 1;
|
||||
apply(square, calculated);
|
||||
Matrix* sigmoid_derivative(Matrix* matrix) {
|
||||
Matrix* ones = matrix_create(matrix->rows, matrix->columns);
|
||||
matrix_fill(ones, 1);
|
||||
Matrix* ones_minus_out = subtract(ones, matrix);
|
||||
Matrix* sigmoid_derivative = multiply(matrix, ones_minus_out);
|
||||
|
||||
// double loss = 0.5 * (target - output) * (target - output);
|
||||
matrix_free(ones);
|
||||
matrix_free(ones_minus_out);
|
||||
|
||||
return 0;
|
||||
return sigmoid_derivative;
|
||||
}
|
||||
|
||||
void train_network(Neural_Network* network, Image *image, int label) {
|
||||
|
||||
// Flatten the image into matrix
|
||||
Matrix* input = matrix_flatten(image->pixel_values, 0);
|
||||
|
||||
// Perform forward propagation
|
||||
Matrix* h1_dot = dot(network->weights_1, input);
|
||||
Matrix* h1_add = add(h1_dot, network->bias_1);
|
||||
Matrix* h1_outputs = apply(sigmoid, h1_add);
|
||||
|
||||
Matrix* h2_dot = dot(network->weights_2, h1_outputs);
|
||||
Matrix* h2_add = add(h2_dot, network->bias_2);
|
||||
Matrix* h2_outputs = apply(sigmoid, h2_add);
|
||||
|
||||
Matrix* h3_dot = dot(network->weights_3, h2_outputs);
|
||||
Matrix* h3_add = add(h3_dot, network->bias_3);
|
||||
Matrix* h3_outputs = apply(sigmoid, h3_add);
|
||||
|
||||
Matrix* final_dot = dot(network->weights_output, h3_outputs);
|
||||
Matrix* final_add = add(final_dot, network->bias_output);
|
||||
Matrix* final_outputs = apply(sigmoid, final_add);
|
||||
|
||||
// begin backpropagation
|
||||
Matrix* sigma1 = matrix_create(final_outputs->rows, 1);
|
||||
matrix_fill(sigma1, 1);
|
||||
Matrix* temp1 = subtract(sigma1, final_outputs);
|
||||
Matrix* temp2 = multiply(temp1, final_outputs); // * soll-ist
|
||||
Matrix* temp3 = matrix_create(final_outputs->rows, final_outputs->columns);
|
||||
matrix_fill(temp3, 0);
|
||||
temp3->numbers[label][0] = 1;
|
||||
Matrix* temp4 = subtract(temp3, final_outputs);
|
||||
sigma1 = multiply(temp2, temp4);
|
||||
|
||||
Matrix* temp5 = transpose(h3_outputs);
|
||||
Matrix* temp6 = dot(sigma1, temp5);
|
||||
Matrix* weights_delta = scale(temp6, network->learning_rate);
|
||||
Matrix* bias_delta = scale(sigma1, network->learning_rate);
|
||||
|
||||
Matrix* temp7 = add(weights_delta, network->weights_output);
|
||||
matrix_free(network->weights_output);
|
||||
network->weights_output = temp7;
|
||||
|
||||
Matrix* temp8 = add(bias_delta, network->bias_output);
|
||||
matrix_free(network->bias_output);
|
||||
network->bias_output = temp8;
|
||||
|
||||
// other levels
|
||||
Matrix* sigma2 = backPropagation(network->learning_rate, network->weights_3, network->bias_3, h3_outputs, h2_outputs, sigma1);
|
||||
Matrix* sigma3 = backPropagation(network->learning_rate, network->weights_2, network->bias_2, h2_outputs, h1_outputs, sigma2);
|
||||
Matrix* sigma4 = backPropagation(network->learning_rate, network->weights_1, network->bias_1, h1_outputs, input, sigma3);
|
||||
|
||||
matrix_free(input);
|
||||
|
||||
matrix_free(h1_dot);
|
||||
matrix_free(h1_add);
|
||||
matrix_free(h1_outputs);
|
||||
|
||||
matrix_free(h2_dot);
|
||||
matrix_free(h2_add);
|
||||
matrix_free(h2_outputs);
|
||||
|
||||
matrix_free(h3_dot);
|
||||
matrix_free(h3_add);
|
||||
matrix_free(h3_outputs);
|
||||
|
||||
matrix_free(final_dot);
|
||||
matrix_free(final_add);
|
||||
matrix_free(final_outputs);
|
||||
|
||||
matrix_free(weights_delta);
|
||||
matrix_free(bias_delta);
|
||||
|
||||
matrix_free(sigma1);
|
||||
matrix_free(sigma2);
|
||||
matrix_free(sigma3);
|
||||
matrix_free(sigma4);
|
||||
|
||||
|
||||
matrix_free(temp1);
|
||||
matrix_free(temp2);
|
||||
matrix_free(temp3);
|
||||
matrix_free(temp4);
|
||||
matrix_free(temp5);
|
||||
matrix_free(temp6);
|
||||
matrix_free(temp7);
|
||||
matrix_free(temp8);
|
||||
}
|
||||
|
||||
Matrix * backPropagation(double learning_rate, Matrix* weights, Matrix* biases, Matrix* current_layer_activation, Matrix* previous_layer_activation, Matrix* sigma_old) {
|
||||
Matrix* sigma_new = matrix_create(current_layer_activation->rows, 1);
|
||||
matrix_fill(sigma_new, 1);
|
||||
|
||||
Matrix* temp1 = subtract(sigma_new, current_layer_activation);
|
||||
Matrix* temp2 = multiply(temp1, current_layer_activation); // *sum(delta*weights)
|
||||
|
||||
for(int i = 0; i < current_layer_activation->rows; i++) {
|
||||
double sum = 0;
|
||||
for (int j = 0; j < sigma_old->rows; j++) {
|
||||
sum += current_layer_activation->numbers[i][j] * sigma_old->numbers[j][0];
|
||||
}
|
||||
temp1->numbers[i][0] = sum;
|
||||
}
|
||||
sigma_new = multiply(temp2, temp1);
|
||||
|
||||
// new sigma done
|
||||
|
||||
Matrix* temp3 = transpose(previous_layer_activation);
|
||||
Matrix* temp4 = dot(sigma_new, temp3);
|
||||
Matrix* weights_delta = scale(temp4, learning_rate);
|
||||
Matrix* bias_delta = scale(sigma_new, learning_rate);
|
||||
|
||||
Matrix* temp5 = add(weights_delta, weights);
|
||||
for (int i = 0; i < weights->rows; ++i) {
|
||||
for (int j = 0; j < weights->columns; ++j) {
|
||||
weights->numbers[i][j] = temp5->numbers[i][j];
|
||||
}
|
||||
}
|
||||
|
||||
Matrix* temp6 = add(bias_delta, biases);
|
||||
for (int i = 0; i < biases->rows; ++i) {
|
||||
for (int j = 0; j < biases->columns; ++j) {
|
||||
biases->numbers[i][j] = temp6->numbers[i][j];
|
||||
}
|
||||
}
|
||||
|
||||
matrix_free(temp1);
|
||||
matrix_free(temp2);
|
||||
matrix_free(temp3);
|
||||
matrix_free(temp4);
|
||||
matrix_free(temp5);
|
||||
matrix_free(temp6);
|
||||
matrix_free(weights_delta);
|
||||
matrix_free(bias_delta);
|
||||
|
||||
return sigma_new;
|
||||
}
|
||||
|
||||
|
||||
//void batch_train_network(Neural_Network* network, Image** images, int size);
|
||||
|
||||
double sigmoid(double input) {
|
||||
return 1.0 / (1 + exp(-1 * input));
|
||||
}
|
||||
|
||||
double sigmoid_derivative(double x) {
|
||||
return x * (1.0 - x);
|
||||
}
|
||||
|
||||
Matrix* softmax(Matrix* matrix) {
|
||||
double total = 0;
|
||||
|
||||
for (int i = 0; i < matrix->rows; i++) {
|
||||
for (int j = 0; j < matrix->columns; j++) {
|
||||
total += exp(matrix->numbers[i][j]);
|
||||
}
|
||||
}
|
||||
Matrix* result_matrix = matrix_create(matrix->rows, matrix->columns);
|
||||
for (int i = 0; i < result_matrix->rows; i++) {
|
||||
for (int j = 0; j < result_matrix->columns; j++) {
|
||||
result_matrix->numbers[i][j] = exp(matrix->numbers[i][j]) / total;
|
||||
}
|
||||
}
|
||||
return result_matrix;
|
||||
}
|
||||
|
||||
double square(double input) {
|
||||
return input * input;
|
||||
}
|
||||
|
||||
double loss_function(Matrix* output_matrix, int image_label) {
|
||||
Matrix* temp = matrix_copy(output_matrix);
|
||||
|
||||
temp->numbers[1, image_label] -= 1;
|
||||
apply(square, temp);
|
||||
|
||||
matrix_free(temp);
|
||||
|
||||
return matrix_sum(temp);;
|
||||
}
|
||||
|
|
@ -1,25 +1,14 @@
|
|||
#pragma once
|
||||
|
||||
#include "matrix.h"
|
||||
#include "image.h"
|
||||
|
||||
typedef struct {
|
||||
int input_size;
|
||||
//Matrix* input; as local variable given to function
|
||||
|
||||
// hidden layers
|
||||
int hidden_size;
|
||||
Matrix* weights_1;
|
||||
Matrix* bias_1;
|
||||
Matrix* weights_2;
|
||||
Matrix* bias_2;
|
||||
Matrix* weights_3;
|
||||
Matrix* bias_3;
|
||||
|
||||
int hidden_amount;
|
||||
int output_size;
|
||||
Matrix* weights_output;
|
||||
Matrix* bias_output;
|
||||
//Matrix* output; as local variable given to function
|
||||
|
||||
Matrix** weights;
|
||||
|
||||
double learning_rate;
|
||||
|
||||
|
|
@ -27,17 +16,18 @@ typedef struct {
|
|||
|
||||
static const int MAX_BYTES = 100;
|
||||
|
||||
Neural_Network* new_network(int input_size, int hidden_size, int output_size, double learning_rate);
|
||||
//void print_network(Neural_Network* network);
|
||||
Neural_Network* new_network(int input_size, int hidden_size, int hidden_amount, int output_size, double learning_rate);
|
||||
|
||||
void randomize_network(Neural_Network* network, int scope);
|
||||
void free_network(Neural_Network* network);
|
||||
|
||||
void save_network(Neural_Network* network);
|
||||
void save_network(Neural_Network* network, char * file_name);
|
||||
Neural_Network* load_network(char* file);
|
||||
|
||||
void print_network(Neural_Network* network);
|
||||
|
||||
void batch_train(Neural_Network* network, Image** images, int amount, int batch_size);
|
||||
double measure_network_accuracy(Neural_Network* network, Image** images, int amount);
|
||||
Matrix* predict_image(Neural_Network* network, Image* image);
|
||||
Matrix* predict(Neural_Network* network, Matrix* image_data);
|
||||
|
||||
void train_network(Neural_Network* network, Image *image, int label);
|
||||
void batch_train_network(Neural_Network* network, Image** images, int size);
|
||||
|
|
|
|||
Reference in a new issue