Compare commits

..

3 commits

Author SHA1 Message Date
Jakob Stornig
e7378cdb51 with memleaks 2023-09-24 02:25:17 +02:00
Jakob Stornig
e0d9353d4b with memleaks 2023-09-24 00:31:29 +02:00
Jakob Stornig
34a23c6eab (try): stochastic gradient decent 2023-09-23 22:05:55 +02:00
16 changed files with 787 additions and 108752 deletions

View file

@ -1,56 +0,0 @@
# 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
View file

@ -1,8 +0,0 @@
# Default ignored files
/shelf/
/workspace.xml
# Editor-based HTTP Client requests
/httpRequests/
# Datasource local storage ignored files
/dataSources/
/dataSources.local.xml

View file

@ -3,5 +3,5 @@ project(c_net C)
set(CMAKE_C_STANDARD 11)
add_executable(c_net main.c matrix.c image.c neuronal_network.c util.c util.h)
add_executable(c_net main.c matrix.c image.c neuronal_network.c util.c util.h neural_net.c neural_net.h)
target_link_libraries(c_net m)

104
README.md
View file

@ -1,36 +1,92 @@
# 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
C-net ඞ is a C project designed to read and predict numbers from the MNIST dataset using neural networks.
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.
## Visuals
![Insert GIF or Screenshot here](https://camo.githubusercontent.com/b308207b5c5ce0970b13c21609350fab21aa61a2fae56da2a6418d6fdcdbc079/68747470733a2f2f7777772e776f6c6672616d2e636f6d2f6d617468656d61746963612f6e65772d696e2d31302f656e68616e6365642d696d6167652d70726f63657373696e672f48544d4c496d616765732e656e2f68616e647772697474656e2d6469676974732d636c617373696669636174696f6e2f736d616c6c7468756d625f31302e676966)
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.
- [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.
## Contributing
State if you are open to contributions and what your requirements are for accepting them.
## Authors and Acknowledgments
This project was brought to you by the following contributors:
- Stornig, Jakob
- Schleicher, Thomas
- Dworski, Daniel
- Walcher, Raphael
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.
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)
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.
## Project Status
The project is considered finished, but ongoing optimizations and improvements may still be in progress.
## Authors and acknowledgment
Show your appreciation to those who have contributed to the project.
![amogus](https://media.tenor.com/7kpsm7kU330AAAAd/sussy-among-us.gif)
## 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.

33
image.c
View file

@ -14,27 +14,23 @@ 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;
int counter = 0;
char c = -1;
do{
c = (char)getc(fptr);
buff[bufferOffset++] = c;
}while(!feof(fptr) && c != 0 && c != ' ' && c !='\n' && counter++ < maxCount);
}while(!feof(fptr) && c != 0 && c != ' ' && c !='\n');
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[2048];
char buffer[100];
int magic_number = 0;
fgets(buffer, 4, fptr);
if(buffer[0] != 'P' || buffer[1] != '5'){
printf("Wrong file Format");
@ -44,16 +40,17 @@ Image * load_pgm_image(char * image_file_string){
fgets(buffer, 1024, fptr);
}
int image_width, image_height, image_white ;
int image_width, image_height, image_length, image_white ;
read_until_space_or_newline(buffer, 10, fptr);
image_width = (int)strtol(buffer, NULL, 10);
image_width = strtol(buffer, NULL, 10);
read_until_space_or_newline(buffer, 10, fptr);
image_height = (int)strtol(buffer, NULL, 10);
image_height = strtol(buffer, NULL, 10);
read_until_space_or_newline(buffer, 10, fptr);
image_white = (int)strtol(buffer, NULL, 10);
image_white = 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++){
@ -93,6 +90,7 @@ 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);
@ -161,6 +159,17 @@ Image** import_images(char* image_file_string, char* label_file_string, int* _nu
return images;
}
Matrix* create_one_hot_result(Image* image){
if(image->label < 0 || image->label > 9){
printf("create_one_hot_result should only be used on correctly labeled images\n");
exit(1);
}
Matrix* result = matrix_create(10, 1);
result->numbers[image->label][0] = 1;
return result;
}
void img_print (Image* img) {
//print the image

View file

@ -1,17 +1,11 @@
#pragma once
#include "matrix.h"
#include "matrix.h"
typedef struct {
Matrix* pixel_values;
char label;
} Image;
typedef struct {
const Image* image;
const size_t size;
} Image_Container;
static const int MAGIC_NUMBER_LABEL = 2049;
@ -27,6 +21,7 @@ static const int MAGIC_NUMBER_IMAGES = 2051;
*/
Image ** import_images(char* image_file_string, char* label_file_string, int* number_imported, int count);
Image * load_pgm_image(char * image_file_string);
Matrix* create_one_hot_result(Image* image);
void img_print (Image* image);
void img_visualize(Image*image);
void img_free (Image* image);

132
main.c
View file

@ -1,122 +1,44 @@
#include <stdio.h>
#include "matrix.h"
#include "image.h"
#include "neuronal_network.h"
#include "neural_net.h"
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include "util.h"
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);
void testFree(Image ** images, int count){
for(int i = 0; i < count; i++){
img_free(images[i]);
}
free(images);
}
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);
}
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];
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);
}
int main(int argc, char** argv) {
int main() {
// Image** images = import_images("../data/train-images.idx3-ubyte", "../data/train-labels.idx1-ubyte", NULL, 60000);
//// img_visualize(images[0]);
//// img_visualize(images[1]);
//// img_visualize(images[4]);
//
//// matrix_print(images[0]->pixel_values);
//// matrix_print(images[1]->pixel_values);
// Neural_Network* nn = new_network(28*28, 16, 10, 0.5);
// randomize_network(nn, 20);
//// save_network(nn);
//
// 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");
//// Neural_Network* nn = load_network("../networks/test1.txt");
//
//// batch_train(nn, images, 20000, 20);
//
// for (int i = 0; i < 30000; ++i) {
// for (int i = 0; i < 10000; ++i) {
// train_network(nn, images[i], images[i]->label);
// }
//
// save_network(nn);
// measure_network_accuracy(nn, images, 100);
// Matrix *m = matrix_create(2, 1);
// m->numbers[0][0] = 1;
// m->numbers[1][0] = 1;
// Neural_Network * net = create_network(3, 2, 3, 1);
// feedforward(net, m);
//
// 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();
// int pause;
int imported_count = 0;
Image** images = import_images("../data/train-images.idx3-ubyte", "../data/train-labels.idx1-ubyte", &imported_count, 10000);
testFree(images, imported_count);
//Neural_Network * net = create_network(3, 28*28, 30, 10);
//train_network_with_batches(net, images, imported_count, 1, 10, 3);
}

View file

@ -216,6 +216,21 @@ 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) {
@ -234,6 +249,16 @@ 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
@ -324,10 +349,8 @@ 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];
@ -359,19 +382,3 @@ 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;
}

View file

@ -21,7 +21,6 @@ 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.
@ -36,4 +35,9 @@ 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);

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

45
networks/test1.txt Normal file
View file

@ -0,0 +1,45 @@
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

264
neural_net.c Normal file
View file

@ -0,0 +1,264 @@
//
// Created by jakob on 22.09.2023.
//
#include <stdarg.h>
#include <stdlib.h>
#include "neural_net.h"
#include <math.h>
#include "image.h"
//this is a helper struct only used for training.
typedef struct{
int layer_count;
Matrix ** weights_delta;
Matrix ** biases_delta;
Matrix ** sum_weights_delta;
Matrix ** sum_biases_delta;
Matrix ** layer_activations;
Matrix ** layer_activations_wo_sigmoid;
} DynamicTrainingContainer;
DynamicTrainingContainer * init_training_container(Neural_Network * network){
DynamicTrainingContainer * container = malloc(sizeof(DynamicTrainingContainer));
container->layer_count = network->layer_count;
container->weights_delta = malloc(sizeof(Matrix*)*network->layer_count - 1);
container->biases_delta = malloc(sizeof(Matrix*)*network->layer_count - 1);
container->sum_weights_delta = malloc(sizeof(Matrix*)*network->layer_count - 1);
container->sum_biases_delta = malloc(sizeof(Matrix*)*network->layer_count - 1);
container->layer_activations_wo_sigmoid = malloc(sizeof(Matrix*) * network->layer_count - 1);
container->layer_activations = malloc(sizeof(Matrix*) * network->layer_count);
for(int i = 0; i < network->layer_count-1; i++){
container->weights_delta[i] = matrix_create(network->weights[i]->rows, network->weights[i]->columns);
container->biases_delta[i] = matrix_create(network->biases[i]->rows, network->biases[i]->columns);
container->sum_weights_delta[i] = matrix_create(network->weights[i]->rows, network->weights[i]->columns);
container->sum_biases_delta[i] = matrix_create(network->biases[i]->rows, network->biases[i]->columns);
container->layer_activations_wo_sigmoid[i] = matrix_create(network->sizes[i], 1);
}
for (int i = 0; i < network->layer_count; i++) {
container->layer_activations[i] = matrix_create(network->sizes[i], 1);
}
return container;
}
void dynamic_training_container_reset_delta(DynamicTrainingContainer * container){
for(int i = 0; i < container->layer_count-1; i++){
matrix_fill(container->weights_delta[i], 0);
matrix_fill(container->biases_delta[i], 0);
}
}
void dynamic_training_container_reset_sum_delta(DynamicTrainingContainer * container){
for(int i = 0; i < container->layer_count-1; i++){
matrix_fill(container->sum_weights_delta[i], 0);
matrix_fill(container->sum_biases_delta[i], 0);
}
}
void dynamic_training_container_free_everything(DynamicTrainingContainer * container){
for(int i = 0; i < container->layer_count-1; i++){
matrix_free(container->weights_delta[i]);
matrix_free(container->biases_delta[i]);
matrix_free(container->sum_weights_delta[i]);
matrix_free(container->sum_biases_delta[i]);
matrix_free(container->layer_activations_wo_sigmoid[i]);
}
for (int i = 0; i < container->layer_count; i++) {
matrix_free(container->layer_activations[i]);
}
free(container->weights_delta);
free(container->biases_delta);
free(container->sum_weights_delta);
free(container->sum_biases_delta);
free(container->layer_activations_wo_sigmoid);
free(container->layer_activations);
}
void evaluate(Neural_Network * network, Image** images, int imageCount){
int numCorrect = 0;
for(int i = 0; i <= imageCount; i++){
Matrix * input = matrix_flatten(images[i]->pixel_values, 0);
Matrix * res = feedforward(network, input);
char result = (char)matrix_argmax(res);
if(result == images[i]->label){
numCorrect++;
}
matrix_free(input);
matrix_free(res);
}
printf("%d/%d", numCorrect, imageCount);
}
double sigmoid(double input) {
return 1.0 / (1 + exp(-input));
}
double sigmoid_prime(double input){
return sigmoid(input)*(1- sigmoid(input));
}
void back_prop(Neural_Network * network, Image* training_sample, DynamicTrainingContainer * trainingContainer){
dynamic_training_container_reset_delta(trainingContainer);
Matrix * desired_result = create_one_hot_result(training_sample); //freed in line 47
//feedforward######################################
//input_activation
Matrix * current_activation = matrix_flatten(training_sample->pixel_values, 0);//freed by freeing layer_activation
trainingContainer->layer_activations[0] = current_activation;
for(int i = 0; i < network->layer_count-1; i++){
Matrix * dot_result = dot(network->weights[i], current_activation);//freed 3 lines below
Matrix * addition_result = add(dot_result, network->biases[i]); //freed by freeing layer activations wo sigmoid
matrix_free(dot_result);
trainingContainer->layer_activations_wo_sigmoid[i] = addition_result;
current_activation = apply(sigmoid, addition_result);
trainingContainer->layer_activations[i+1] = current_activation; //freed by freeing layer activations
dot_result = NULL;
}
//backward pass####################################
//calculate delta for last layer;
//bias
Matrix * subtraction_result = subtract(trainingContainer->layer_activations[network->layer_count-1], desired_result);
Matrix * s_prime = apply(sigmoid_prime, trainingContainer->layer_activations_wo_sigmoid[network->layer_count-2]);
Matrix * delta = multiply(subtraction_result, s_prime);
matrix_free(s_prime);
matrix_free(subtraction_result);
trainingContainer->biases_delta[network->layer_count-2] = delta;
//weights
Matrix * transposed = transpose(trainingContainer->layer_activations[network->layer_count-2]);
trainingContainer->weights_delta[network->layer_count-2] = dot(delta, transposed);
matrix_free(transposed);
transposed = NULL;
for(int layer = network->layer_count-3; layer >= 0; layer--){
Matrix * activation_wo_sigmoid = trainingContainer->layer_activations_wo_sigmoid[layer];
Matrix * derivative = apply(sigmoid_prime, activation_wo_sigmoid);
Matrix * transposed_layer_weight = transpose(network->weights[layer + 1]);
Matrix * dot_result = dot(transposed_layer_weight, delta);
matrix_free(transposed_layer_weight);
delta = multiply(dot_result, derivative);
trainingContainer->biases_delta[layer] = delta;
Matrix * transposed_activation = transpose(trainingContainer->layer_activations[layer]);
trainingContainer->weights_delta[layer] = dot(delta, transposed_activation);
matrix_free(transposed_activation);
}
matrix_free(desired_result);
}
void update_batch(Neural_Network * network, DynamicTrainingContainer * trainingContainer, Image** training_data, int batch_start, int batch_end, double learning_rate){
dynamic_training_container_reset_delta(trainingContainer);
dynamic_training_container_reset_sum_delta(trainingContainer);
for(int i = batch_start; i <= batch_end; i++){
back_prop(network, training_data[i], trainingContainer);
for(int j = 0; j < network->layer_count-1; j++){
Matrix * sum_weights_free = trainingContainer->sum_weights_delta[j];
trainingContainer->sum_weights_delta[j] = add(trainingContainer->sum_weights_delta[j], trainingContainer->weights_delta[j]);
matrix_free(sum_weights_free);
Matrix * sum_biases_free = trainingContainer->sum_biases_delta[j];
trainingContainer->sum_biases_delta[j] = add(trainingContainer->sum_biases_delta[j], trainingContainer->biases_delta[j]);
matrix_free(sum_biases_free);
}
}
//change network
double scaling_factor = learning_rate/(batch_end-batch_start);
for(int i = 0; i < network->layer_count-1; i++){
//update weights
Matrix * weight_change = scale(trainingContainer->sum_weights_delta[i], scaling_factor);
Matrix * new_weights = subtract(network->weights[i], weight_change);
matrix_free(network->weights[i]);
network->weights[i] = new_weights;
//update biases
Matrix * bias_change = scale(trainingContainer->sum_biases_delta[i], scaling_factor);
Matrix * new_biases = subtract(network->biases[i], bias_change);
matrix_free(network->biases[i]);
network->biases[i] = new_biases;
}
}
void train_network_with_batches(Neural_Network * network, Image** training_data, int image_count, int epochs, int batch_size, double learning_rate){
DynamicTrainingContainer * container = init_training_container(network);
for(int i = 0; i < epochs; i++){
for(int j = 0; j < image_count/batch_size; j++){
int batch_start = j*batch_size;
int batch_end = j*batch_size + batch_size - 1;
update_batch(network, container, training_data, batch_start, batch_end, learning_rate);
}
evaluate(network, training_data, 500);
}
dynamic_training_container_free_everything(container);
free(container);
}
Neural_Network* create_network(int layer_count,...){
Neural_Network * network = malloc(sizeof(Neural_Network));
network->layer_count = layer_count;
network->sizes = malloc(sizeof(int) * layer_count);
network->weights = malloc(sizeof(Matrix*)*(layer_count-1));
network->biases = malloc(sizeof(Matrix*)*(layer_count-1));
//read sizes
va_list layer_sizes;
va_start(layer_sizes, layer_count);
for(int i = 0; i < layer_count; i++){
network->sizes[i] = va_arg(layer_sizes, int);
}
va_end(layer_sizes);
//init weights
for(int i = 0; i < layer_count-1; i++){
network->weights[i] = matrix_create(network->sizes[i+1], network->sizes[i]);
matrix_randomize(network->weights[i], network->sizes[i]);
}
//init biases
for(int i = 0; i < layer_count-1; i++){
network->biases[i] = matrix_create(network->sizes[i+1], 1);
matrix_randomize(network->biases[i], network->sizes[i]);
}
return network;
}
//given an input "activations" it returns the matrix that the network would output
Matrix * feedforward(Neural_Network * net, Matrix * activations){
Matrix * current_layer_activation = activations;
//next_layer_activation = sigmoid(dot(layer_weights, layer_activations)+layer_biases);
for(int i = 0; i < net->layer_count - 1; i++){
Matrix * dot_result = dot(net->weights[i], current_layer_activation);
Matrix * addition_result = add(dot_result, net->biases[i]);
Matrix * sigmoid_result = apply(sigmoid, addition_result);
current_layer_activation = sigmoid_result;
matrix_free(dot_result);
matrix_free(addition_result);
}
return current_layer_activation;
}

22
neural_net.h Normal file
View file

@ -0,0 +1,22 @@
//
// Created by jakob on 22.09.2023.
//
#include "matrix.h"
#include "image.h"
#ifndef C_NET_NEURAL_NET_H
#define C_NET_NEURAL_NET_H
#endif //C_NET_NEURAL_NET_H
typedef struct {
int layer_count;
int* sizes;
Matrix ** weights;
Matrix ** biases;
} Neural_Network;
Neural_Network* create_network(int layer_count,...);
Matrix * feedforward(Neural_Network * net, Matrix * activations);
void train_network_with_batches(Neural_Network * network, Image** training_data, int image_count, int epochs, int batch_size, double learning_rate);

View file

@ -1,52 +1,67 @@
#include <stdlib.h>
#include "neuronal_network.h"
#include <stdio.h>
#include <time.h>
#include <math.h>
#include "util.h"
double sigmoid(double input);
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);
double sigmoid_derivative(double x);
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));
Matrix* softmax(Matrix* matrix);
double square(double input);
network->input_size = input_size;
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->hidden_amount = hidden_amount;
network->input_size = input_size;
network->output_size = output_size;
network->learning_rate = learning_rate;
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);
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);
return network;
}
void randomize_network(Neural_Network* network, int scope){
for (int i = 0; i < network->hidden_amount + 1; i++) {
matrix_randomize(network->weights[i], 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);
}
//void print_network(Neural_Network* network){};
void free_network(Neural_Network* network){
for (int i = 0; i < network->hidden_amount + 1; i++) {
matrix_free(network->weights[i]);
}
free(network->weights);
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);
free(network);
}
void save_network(Neural_Network* network, char * file_name) {
void save_network(Neural_Network* network) {
char* file_name = "../networks/newest_network.txt";
// create file
FILE* save_file = fopen(file_name, "w");
@ -60,17 +75,28 @@ void save_network(Neural_Network* network, char * file_name) {
// 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);
for (int i = 0; i < network->hidden_amount + 1; ++i) {
matrix_save(network->weights[i], file_name);
}
// save first layer
matrix_save(network->bias_1, file_name);
matrix_save(network->weights_1, file_name);
printf("Network Saved!\n");
// 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!");
}
Neural_Network* load_network(char* file) {
@ -91,48 +117,36 @@ 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, hidden_amount, output_size, 0);
Neural_Network* saved_network = new_network(input_size, hidden_size, output_size, 0);
for (int i = 0; i < saved_network->hidden_amount + 1; ++i) {
saved_network->weights[i] = load_next_matrix(save_file);
}
// 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);
// 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]);
int guess = matrix_argmax(prediction);
int answer = (unsigned char) images[i]->label;
if (guess == answer) {
if (matrix_argmax(prediction) == images[i]->label) {
num_correct++;
}
matrix_free(prediction);
}
updateBar(100);
return ((double) num_correct) / amount;
return 1.0 * num_correct / amount;
}
Matrix* predict_image(Neural_Network* network, Image* image){
@ -143,221 +157,228 @@ 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* input = matrix_add_bias(image_data);
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* 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* h3_dot = dot(network->weights_3, h2_outputs);
Matrix* h3_add = add(h3_dot, network->bias_3);
Matrix* h3_outputs = apply(sigmoid, h3_add);
output[i] = neuron_activation;
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);
matrix_free(neuron_input);
matrix_free(input);
Matrix* result = softmax(final_outputs);
input = matrix_add_bias(neuron_activation);
}
matrix_free(h1_dot);
matrix_free(h1_add);
matrix_free(h1_outputs);
for (int i = 0; i < network->hidden_amount; ++i) {
matrix_free(output[i]);
}
matrix_free(h2_dot);
matrix_free(h2_add);
matrix_free(h2_outputs);
matrix_free(input);
matrix_free(h3_dot);
matrix_free(h3_add);
matrix_free(h3_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);
matrix_free(final_dot);
matrix_free(final_add);
matrix_free(final_outputs);
return result;
}
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 cost_function(Matrix* calculated, int expected){
calculated->numbers[expected] -= 1;
apply(square, calculated);
matrix_free(ones);
matrix_free(ones_minus_out);
// double loss = 0.5 * (target - output) * (target - output);
return sigmoid_derivative;
return 0;
}
double sigmoid(double input) {
return 1.0 / (1 + exp(-1 * input));
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);;
}

View file

@ -1,14 +1,25 @@
#pragma once
#include "matrix.h"
#include "image.h"
typedef struct {
int input_size;
int hidden_size;
int hidden_amount;
int output_size;
//Matrix* input; as local variable given to function
Matrix** weights;
// hidden layers
int hidden_size;
Matrix* weights_1;
Matrix* bias_1;
Matrix* weights_2;
Matrix* bias_2;
Matrix* weights_3;
Matrix* bias_3;
int output_size;
Matrix* weights_output;
Matrix* bias_output;
//Matrix* output; as local variable given to function
double learning_rate;
@ -16,18 +27,17 @@ typedef struct {
static const int MAX_BYTES = 100;
Neural_Network* new_network(int input_size, int hidden_size, int hidden_amount, int output_size, double learning_rate);
Neural_Network* new_network(int input_size, int hidden_size, int output_size, double learning_rate);
//void print_network(Neural_Network* network);
void randomize_network(Neural_Network* network, int scope);
void free_network(Neural_Network* network);
void save_network(Neural_Network* network, char * file_name);
void save_network(Neural_Network* network);
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);