Compare commits

...
This repository has been archived on 2026-04-20. You can view files and clone it, but you cannot make any changes to it's state, such as pushing and creating new issues, pull requests or comments.

4 commits

Author SHA1 Message Date
Raphael Walcher
3a8ab15bf2 Merge remote-tracking branch 'origin/Delta-Error-Test' into Delta-Error-Test 2023-09-24 20:41:32 +02:00
Raphael Walcher
2a4fbf9bbd readme 2023-09-24 20:41:12 +02:00
Thomas
cf8b0a8b94 Clean up (1) 2023-09-24 12:22:28 +02:00
Thomas
f836c53711 Clean up (before drastic refactoring) 2023-09-24 11:54:55 +02:00
13 changed files with 326 additions and 384 deletions

View file

@ -3,5 +3,5 @@ project(c_net C)
set(CMAKE_C_STANDARD 11) 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/matrix.c image/image.c neuronal_network.c util.c matrix/operations.c)
target_link_libraries(c_net m) target_link_libraries(c_net m)

100
README.md
View file

@ -1,92 +1,30 @@
# C-net ඞ # 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 ## 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. C-net ඞ is a Python project designed to read and predict numbers from the MNIST dataset using neural networks.
## 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 ## 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. ![Insert GIF or Screenshot here](link_to_visual.gif)
## 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 ## Roadmap
If you have ideas for releases in the future, it is a good idea to list them in the README.
## Contributing - [x] Implemented an Image Loader for MNIST dataset.
State if you are open to contributions and what your requirements are for accepting them. - [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 project, which served as an inspiration and reference:
- [MNIST from Scratch](https://github.com/markkraay/mnist-from-scratch) by markkraay
## Authors and acknowledgment ## Project Status
Show your appreciation to those who have contributed to the project. 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.

32
image.h
View file

@ -1,32 +0,0 @@
#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;
static const int MAGIC_NUMBER_IMAGES = 2051;
/**
* reads a specified number of images out of the training dataset
* @param image_file_string Path to the file containing the image data
* @param label_file_string Path to the file containing the image labels
* @param ptr via this pointer, the images can be accessed
* @param count maximum number of images to be loaded. If it is 0, all available images are loaded.
* @return
*/
Image ** import_images(char* image_file_string, char* label_file_string, int* number_imported, int count);
Image * load_pgm_image(char * image_file_string);
void img_print (Image* image);
void img_visualize(Image*image);
void img_free (Image* image);

View file

@ -2,8 +2,8 @@
#include <stdlib.h> #include <stdlib.h>
#include "image.h" #include "image.h"
#include "matrix.h" #include "../matrix/matrix.h"
#include "util.h" #include "../util.h"
void big_endian_to_c_uint(const char * bytes, void * target, int size) { void big_endian_to_c_uint(const char * bytes, void * target, int size) {
char* helper = (char*)target; char* helper = (char*)target;
@ -68,8 +68,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) { Image** import_images(char* image_file_string, char* label_file_string, int* _number_imported, int count) {
printf("Loading Images\n"); printf("Loading Images\n");
// create file pointer for the image and label data // create file pointer for the image and label data
FILE* image_file = fopen(image_file_string, "r"); FILE* image_file = fopen(image_file_string, "rb");
FILE* label_file = fopen(label_file_string, "r"); FILE* label_file = fopen(label_file_string, "rb");
// check if the file could be opened // check if the file could be opened
if(image_file == NULL || label_file == NULL) { if(image_file == NULL || label_file == NULL) {
@ -159,7 +159,6 @@ Image** import_images(char* image_file_string, char* label_file_string, int* _nu
} }
void img_print (Image* img) { void img_print (Image* img) {
//print the image //print the image
matrix_print(img->pixel_values); matrix_print(img->pixel_values);
//print the number of the image //print the number of the image
@ -183,7 +182,7 @@ void img_free (Image* img) {
free(img); free(img);
} }
void images_free (Image** images, int quantity){ void images_free(Image** images, int quantity) {
//frees every single image //frees every single image
for(int i=0;i<quantity;i++){ for(int i=0;i<quantity;i++){
img_free(images[i]); img_free(images[i]);

21
image/image.h Normal file
View file

@ -0,0 +1,21 @@
#include "../matrix/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;
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);
void img_print (Image* image);
void img_visualize(Image*image);
void img_free (Image* image);
void images_free (Image** images, int quantity);

63
main.c
View file

@ -1,29 +1,64 @@
#include <stdio.h> #include <stdio.h>
#include "image.h" #include "image/image.h"
#include "neuronal_network.h" #include "neuronal_network.h"
int main() { int main() {
Image** images = import_images("../data/train-images.idx3-ubyte", "../data/train-labels.idx1-ubyte", NULL, 60000);
const int amount_of_images_to_load = 60000;
const int amount_of_images_used_to_train = 30000;
const int amount_of_images_used_to_test = 1000;
const int input_size = 28*28;
const int hidden_layer_size = 50;
const int hidden_layer_count = 3;
const double learning_rate = 0.1;
/*
* Loading Images from Dataset
*/
Image** images = import_images("../data/train-images.idx3-ubyte", "../data/train-labels.idx1-ubyte", NULL, amount_of_images_to_load);
// img_visualize(images[0]); // img_visualize(images[0]);
// img_visualize(images[1]); // img_print(images[0]);
// matrix_print(images[0]->pixel_values); /*
// matrix_print(images[1]->pixel_values); * Create a new network and randomize the weights
*/
Neural_Network* nn = new_network(28*28, 40, 5, 10, 0.08); Neural_Network* network = new_network(input_size, hidden_layer_size, hidden_layer_count, 10, learning_rate);
randomize_network(nn, 1); randomize_network(network, 1);
// Neural_Network* nn = load_network("../networks/newest_network.txt");
// printf("Done loading!\n");
// batch_train(nn, images, 20000, 20); /*
* Training
*/
for (int i = 0; i < 30000; ++i) { for (int i = 0; i < amount_of_images_used_to_train; i++) {
train_network(nn, images[i], images[i]->label); train_network(network, images[i], images[i]->label);
} }
save_network(nn); // Batch training works if you change the train_network method, but the results are not that good (needs further testing)
// batch_train(nn, images, 30000, 2);
printf("%lf\n", measure_network_accuracy(nn, images, 10000)); printf("Trinaing Done!\n");
/*
* Saving and Loading
*/
// save_network(network);
// Neural_Network* network = load_network("../networks/newest_network.txt");
/*
* Measure Accuracy & predict single images
*/
printf("Accuracy: %lf\n", measure_network_accuracy(network, images, amount_of_images_used_to_test));
// matrix_print(predict_image(network, images[0]));
images_free(images, amount_of_images_to_load);
free_network(network);
return 0;
} }

View file

@ -1,41 +0,0 @@
#pragma once
#include <stdio.h>
typedef struct {
int rows, columns;
double **numbers;
} Matrix;
static const int scaling_value = 10000;
// operational functions
Matrix* matrix_create(int rows, int columns);
void matrix_fill(Matrix* matrix, double value);
void matrix_free(Matrix* matrix);
void matrix_print(Matrix *matrix);
Matrix* matrix_copy(Matrix *matrix);
void matrix_save(Matrix* matrix, char* file_string);
Matrix* matrix_load(char* file_string);
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.
* It creates a new matrix, which is modified and then returned.
* If we don't need the original matrix, we should consider just changing the original matrix and changing the method signature to void.
*/
// mathematical functions
Matrix* multiply(Matrix* matrix1, Matrix* matrix2);
Matrix* add(Matrix* matrix1, Matrix* matrix2);
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);

139
matrix/matrix.c Normal file
View file

@ -0,0 +1,139 @@
#include "matrix.h"
#include <stdlib.h>
#include <stdio.h>
#define MAX_BYTES 100
Matrix* matrix_create(int rows, int columns) {
// allocate memory for the matrix
Matrix* matrix = malloc(sizeof(Matrix));
// set size variables to the correct size
matrix->rows = rows;
matrix->columns = columns;
// allocate memory for the numbers (2D-Array)
matrix->numbers = malloc(sizeof(double*) * rows);
for (int i = 0; i < rows; i++) {
matrix->numbers[i] = calloc(sizeof(double), columns);
}
// return the pointer to the allocated memory
return matrix;
}
void matrix_fill(Matrix* matrix, double value) {
// simple for loop to populate the 2D-array with a value
for (int i = 0; i < matrix->rows; i++) {
for (int j = 0; j < matrix->columns; j++) {
matrix->numbers[i][j] = value;
}
}
}
void matrix_free(Matrix* matrix) {
// de-allocate every column
for (int i = 0; i < matrix->rows; i++) {
free(matrix->numbers[i]);
}
// de-allocate the rows
free(matrix->numbers);
// de-allocate the matrix
free(matrix);
}
void matrix_print(Matrix *matrix) {
// print the dimensions of the matrix
printf("Rows: %d, Columns: %d\n", matrix->rows, matrix->columns);
// loop through all values and format them into the correct matrix representation
for (int i = 0; i < matrix->rows; i++) {
for (int j = 0; j < matrix->columns; j++) {
printf("%lf ", matrix->numbers[i][j]);
}
printf("\n");
}
}
Matrix* matrix_copy(Matrix *matrix) {
// create another matrix of the same size
Matrix* copy_of_matrix = matrix_create(matrix->rows, matrix->columns);
// copy the values from the original matrix into the copy
for (int i = 0; i < matrix->rows; i++) {
for (int j = 0; j < matrix->columns; j++) {
copy_of_matrix->numbers[i][j] = matrix->numbers[i][j];
}
}
// return the pointer to the copy
return copy_of_matrix;
}
void matrix_save(Matrix* matrix, char* file_string){
// open the file in append mode
FILE *file = fopen(file_string, "a");
// check if the file could be found
if(file == NULL) {
printf("ERROR: Unable to get handle for \"%s\"! (matrix_save)", file_string);
exit(1);
}
// save the size of the matrix
fprintf(file, "%d\n", matrix->rows);
fprintf(file, "%d\n", matrix->columns);
// save all the numbers of the matrix into the file
for(int i = 0; i < matrix->rows; i++){
for(int j = 0; j < matrix->columns; j++){
fprintf(file, "%.10f\n", matrix->numbers[i][j]);
}
}
// close the file
fclose(file);
}
Matrix* matrix_load(char* file_string){
FILE *fptr = fopen(file_string, "r");
if(!fptr){
printf("Could not open \"%s\"", file_string);
exit(1);
}
Matrix * m = load_next_matrix(fptr);
fclose(fptr);
return m;
}
Matrix* load_next_matrix(FILE *save_file){
char buffer[MAX_BYTES];
fgets(buffer, MAX_BYTES, save_file);
int rows = (int)strtol(buffer, NULL, 10);
fgets(buffer, MAX_BYTES, save_file);
int cols = (int)strtol(buffer, NULL, 10);
Matrix *matrix = matrix_create(rows, cols);
for(int i = 0; i < rows; i++){
for(int j = 0; j < cols; j++){
fgets(buffer, MAX_BYTES, save_file);
matrix->numbers[i][j] = strtod(buffer, NULL);
}
}
return matrix;
}

15
matrix/matrix.h Normal file
View file

@ -0,0 +1,15 @@
#include <stdio.h>
typedef struct {
int rows, columns;
double **numbers;
} Matrix;
Matrix* matrix_create(int rows, int columns);
void matrix_fill(Matrix* matrix, double value);
void matrix_free(Matrix* matrix);
void matrix_print(Matrix *matrix);
Matrix* matrix_copy(Matrix *matrix);
void matrix_save(Matrix* matrix, char* file_string);
Matrix* matrix_load(char* file_string);
Matrix* load_next_matrix(FILE * save_file);

View file

@ -1,92 +1,10 @@
#include "matrix.h" #include <process.h>
#include <stdlib.h> #include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <time.h> #include <time.h>
#define MAX_BYTES 100 #include "math.h"
#include "operations.h"
static int RANDOMIZED = 0; static int RANDOMIZED = 0;
// operational functions
Matrix* matrix_create(int rows, int columns) {
// allocate memory for the matrix
Matrix* matrix = malloc(sizeof(Matrix));
// set size variables to the correct size
matrix->rows = rows;
matrix->columns = columns;
// allocate memory for the numbers (2D-Array)
matrix->numbers = malloc(sizeof(double*) * rows);
for (int i = 0; i < rows; i++) {
matrix->numbers[i] = calloc(sizeof(double), columns);
}
// return the pointer to the allocated memory
return matrix;
}
void matrix_fill(Matrix* matrix, double value) {
// simple for loop to populate the 2D-array with a value
for (int i = 0; i < matrix->rows; i++) {
for (int j = 0; j < matrix->columns; j++) {
matrix->numbers[i][j] = value;
}
}
}
void matrix_free(Matrix* matrix) {
// de-allocate every column
for (int i = 0; i < matrix->rows; i++) {
free(matrix->numbers[i]);
}
// de-allocate the rows
free(matrix->numbers);
// de-allocate the matrix
free(matrix);
}
void matrix_print(Matrix *matrix) {
// print the dimensions of the matrix
printf("Rows: %d, Columns: %d\n", matrix->rows, matrix->columns);
// loop through all values and format them into the correct matrix representation
for (int i = 0; i < matrix->rows; i++) {
for (int j = 0; j < matrix->columns; j++) {
printf("%lf ", matrix->numbers[i][j]);
}
printf("\n");
}
}
Matrix* matrix_copy(Matrix *matrix) {
// create another matrix of the same size
Matrix* copy_of_matrix = matrix_create(matrix->rows, matrix->columns);
// copy the values from the original matrix into the copy
for (int i = 0; i < matrix->rows; i++) {
for (int j = 0; j < matrix->columns; j++) {
copy_of_matrix->numbers[i][j] = matrix->numbers[i][j];
}
}
// return the pointer to the copy
return copy_of_matrix;
}
// mathematical functions
/*
* These methods won't change or free the input matrix.
* It creates a new matrix, which is modified and then returned.
* If we don't need the original matrix, we should consider just changing the original matrix and changing the method signature to void.
*/
Matrix* multiply(Matrix* matrix1, Matrix* matrix2) { Matrix* multiply(Matrix* matrix1, Matrix* matrix2) {
@ -216,22 +134,6 @@ Matrix* scale(Matrix* matrix, double value) {
return result_matrix; 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) { Matrix* transpose(Matrix* matrix) {
// create a new matrix of the size n-m, based on the original matrix of size m-n // create a new matrix of the size n-m, based on the original matrix of size m-n
@ -249,77 +151,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
FILE *file = fopen(file_string, "a");
// check if the file could be found
if(file == NULL) {
printf("ERROR: Unable to get handle for \"%s\"! (matrix_save)", file_string);
exit(1);
}
// save the size of the matrix
fprintf(file, "%d\n", matrix->rows);
fprintf(file, "%d\n", matrix->columns);
// save all the numbers of the matrix into the file
for(int i = 0; i < matrix->rows; i++){
for(int j = 0; j < matrix->columns; j++){
fprintf(file, "%.10f\n", matrix->numbers[i][j]);
}
}
// close the file
fclose(file);
}
Matrix* matrix_load(char* file_string){
FILE *fptr = fopen(file_string, "r");
if(!fptr){
printf("Could not open \"%s\"", file_string);
exit(1);
}
Matrix * m = load_next_matrix(fptr);
fclose(fptr);
return m;
}
Matrix* load_next_matrix(FILE *save_file){
char buffer[MAX_BYTES];
fgets(buffer, MAX_BYTES, save_file);
int rows = (int)strtol(buffer, NULL, 10);
fgets(buffer, MAX_BYTES, save_file);
int cols = (int)strtol(buffer, NULL, 10);
Matrix *matrix = matrix_create(rows, cols);
for(int i = 0; i < rows; i++){
for(int j = 0; j < cols; j++){
fgets(buffer, MAX_BYTES, save_file);
matrix->numbers[i][j] = strtod(buffer, NULL);
}
}
return matrix;
}
Matrix* matrix_flatten(Matrix* matrix, int axis) { Matrix* matrix_flatten(Matrix* matrix, int axis) {
// Axis = 0 -> Column Vector, Axis = 1 -> Row Vector // Axis = 0 -> Column Vector, Axis = 1 -> Row Vector
Matrix* result_matrix; Matrix* result_matrix;
@ -343,10 +174,10 @@ Matrix* matrix_flatten(Matrix* matrix, int axis) {
return result_matrix; return result_matrix;
} }
int matrix_argmax(Matrix* matrix) { int argmax(Matrix* matrix) {
// Expects a Mx1 matrix // Expects a Mx1 matrix
if (matrix->columns != 1){ if (matrix->columns != 1){
printf("ERROR: Matrix is not Mx1 (matrix_argmax)"); printf("ERROR: Matrix is not Mx1 (argmax)");
exit(EXIT_FAILURE); exit(EXIT_FAILURE);
} }

25
matrix/operations.h Normal file
View file

@ -0,0 +1,25 @@
#include "matrix.h"
static const int scaling_value = 10000;
Matrix* multiply(Matrix* matrix1, Matrix* matrix2);
Matrix* add(Matrix* matrix1, Matrix* matrix2); //only used in the batch_training method
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* transpose(Matrix* matrix);
Matrix* matrix_flatten(Matrix* matrix, int axis);
int argmax(Matrix* matrix);
void matrix_randomize(Matrix* matrix, int n);
Matrix* matrix_add_bias(Matrix* matrix);

View file

@ -1,13 +1,14 @@
#include <stdlib.h> #include <stdlib.h>
#include "neuronal_network.h" #include "neuronal_network.h"
#include "matrix\operations.h"
#include <stdio.h> #include <stdio.h>
#include <math.h> #include <math.h>
double sigmoid(double input); double sigmoid(double input);
Matrix* predict(Neural_Network* network, Matrix* image_data); Matrix* predict(Neural_Network* network, Matrix* image_data);
Matrix* sigmoid_derivative(Matrix* matrix); Matrix* sigmoid_derivative(Matrix* matrix);
Matrix *calculate_weights_delta(Matrix *previous_layer_output, Matrix *delta_matrix, double learning_rate); Matrix *calculate_weights_delta(Matrix *previous_layer_output, Matrix *delta_matrix);
void apply_weights(Neural_Network* network, Matrix* delta_weights_matrix, int index); void apply_weights(Neural_Network *network, Matrix *delta_weights_matrix, int index, double learning_rate);
Matrix* calculate_delta_hidden(Matrix* next_layer_delta, Matrix* weights, Matrix* current_layer_output); Matrix* calculate_delta_hidden(Matrix* next_layer_delta, Matrix* weights, Matrix* current_layer_output);
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 hidden_amount, int output_size, double learning_rate){
@ -120,7 +121,7 @@ double measure_network_accuracy(Neural_Network* network, Image** images, int amo
for (int i = 0; i < amount; i++) { for (int i = 0; i < amount; i++) {
Matrix* prediction = predict_image(network, images[i]); Matrix* prediction = predict_image(network, images[i]);
int guess = matrix_argmax(prediction); int guess = argmax(prediction);
int answer = (unsigned char) images[i]->label; int answer = (unsigned char) images[i]->label;
if (guess == answer) { if (guess == answer) {
@ -167,22 +168,26 @@ Matrix* predict(Neural_Network* network, Matrix* image_data) {
//void batch_train(Neural_Network* network, Image** images, int amount, int batch_size) { //void batch_train(Neural_Network* network, Image** images, int amount, int batch_size) {
// //
// for (int i = 0; i < amount; ++i) { // if(amount % batch_size != 0) {
// // printf("ERROR: Batch Size is not compatible with image amount! (batch_train)");
// if(amount % 1000 == 0) { // exit(1);
// printf("1k pics!\n");
// } // }
// //
// int image_index = 0;
//
// for (int i = 0; i < amount / batch_size; ++i) {
//
// Matrix* batch_weights[network->hidden_amount + 1]; // Matrix* batch_weights[network->hidden_amount + 1];
// //
// for (int j = 0; j < network->hidden_amount + 1; j++) {
// batch_weights[j] = matrix_create(network->weights[j]->rows, network->weights[j]->columns);
// matrix_fill(batch_weights[j], 0);
// }
//
// for (int j = 0; j < batch_size; ++j) { // for (int j = 0; j < batch_size; ++j) {
// Matrix** delta_weights = train_network(network, images[i], images[i]->label); // Matrix** delta_weights = train_network(network, images[image_index], images[image_index]->label);
// //
// for (int k = 0; k < network->hidden_amount + 1; k++) { // 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* temp_result = add(batch_weights[k], delta_weights[k]);
// //
@ -193,14 +198,16 @@ Matrix* predict(Neural_Network* network, Matrix* image_data) {
// } // }
// //
// free(delta_weights); // free(delta_weights);
//
// image_index++;
// } // }
// //
// for (int j = 0; j < network->hidden_amount + 1; ++j) { // for (int j = 0; j < network->hidden_amount + 1; j++) {
// Matrix* average_delta_weight = scale(batch_weights[j], (1.0 / batch_size)); // Matrix* average_delta_weight = scale(batch_weights[j], (1.0 / batch_size));
// apply_weights(network, average_delta_weight, j); // apply_weights(network, average_delta_weight, j, network->learning_rate);
// //
// matrix_free(average_delta_weight);
// matrix_free(batch_weights[j]); // matrix_free(batch_weights[j]);
// matrix_free(average_delta_weight);
// } // }
// } // }
//} //}
@ -239,13 +246,13 @@ void train_network(Neural_Network* network, Image *image, int label) {
Matrix* delta = multiply(sigmoid_prime, error); Matrix* delta = multiply(sigmoid_prime, error);
//calculate and apply the delta for all weights in out-put layer //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); delta_weights[network->hidden_amount] = calculate_weights_delta(output[network->hidden_amount - 1], delta);
//hidden layers //hidden layers
Matrix* previous_delta = delta; Matrix* previous_delta = delta;
for (int i = network->hidden_amount; i > 1; i--) { for (int i = network->hidden_amount; i > 1; i--) {
delta = calculate_delta_hidden(previous_delta, network->weights[i], output[i - 1]); 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); delta_weights[i - 1] = calculate_weights_delta(output[i - 2], delta);
matrix_free(previous_delta); matrix_free(previous_delta);
previous_delta = delta; previous_delta = delta;
@ -253,10 +260,16 @@ void train_network(Neural_Network* network, Image *image, int label) {
// Input Layer // Input Layer
delta = calculate_delta_hidden(previous_delta, network->weights[1], output[0]); delta = calculate_delta_hidden(previous_delta, network->weights[1], output[0]);
delta_weights[0] = calculate_weights_delta(image_data, delta, network->learning_rate); delta_weights[0] = calculate_weights_delta(image_data, delta);
// if you want to use this method as a standalone method this part needs to be uncommented
for (int i = 0; i < network->hidden_amount + 1; ++i) {
apply_weights(network, delta_weights[i], i, network->learning_rate);
}
for (int i = 0; i < network->hidden_amount + 1; ++i) { for (int i = 0; i < network->hidden_amount + 1; ++i) {
apply_weights(network, delta_weights[i], i); matrix_free(delta_weights[i]);
} }
// De-allocate stuff // De-allocate stuff
@ -267,9 +280,7 @@ void train_network(Neural_Network* network, Image *image, int label) {
matrix_free(output[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(sigmoid_prime);
matrix_free(wanted_output); matrix_free(wanted_output);
@ -308,7 +319,7 @@ Matrix* calculate_delta_hidden(Matrix* next_layer_delta, Matrix* weights, Matrix
return new_deltas; return new_deltas;
} }
void apply_weights(Neural_Network* network, Matrix* delta_weights_matrix, int index) { void apply_weights(Neural_Network *network, Matrix *delta_weights_matrix, int index, double learning_rate) {
if(index > network->hidden_amount || index < 0) { if(index > network->hidden_amount || index < 0) {
printf("ERROR: Index out of range! (apply_weights)"); printf("ERROR: Index out of range! (apply_weights)");
@ -320,27 +331,28 @@ void apply_weights(Neural_Network* network, Matrix* delta_weights_matrix, int in
exit(1); exit(1);
} }
// scale by learning rate
Matrix* scaled_delta_weights_matrix = scale(delta_weights_matrix, learning_rate);
for (int i = 0; i < delta_weights_matrix->rows; i++) { for (int i = 0; i < delta_weights_matrix->rows; i++) {
for (int j = 0; j < delta_weights_matrix->columns; j++) { for (int j = 0; j < scaled_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 network->weights[index]->numbers[i][j] += scaled_delta_weights_matrix->numbers[i][j]; // multiply delta_weights_matrix with learning rate AND - instead of + because soll-ist
} }
} }
matrix_free(scaled_delta_weights_matrix);
} }
Matrix *calculate_weights_delta(Matrix *previous_layer_output, Matrix *delta_matrix, double learning_rate) { Matrix *calculate_weights_delta(Matrix *previous_layer_output, Matrix *delta_matrix) {
Matrix* previous_out_with_one = matrix_add_bias(previous_layer_output); Matrix* previous_out_with_one = matrix_add_bias(previous_layer_output);
Matrix* transposed_previous_out_with_bias = transpose(previous_out_with_one); Matrix* transposed_previous_out_with_bias = transpose(previous_out_with_one);
Matrix* weights_delta_matrix = dot(delta_matrix, transposed_previous_out_with_bias); 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(previous_out_with_one);
matrix_free(transposed_previous_out_with_bias); matrix_free(transposed_previous_out_with_bias);
matrix_free(weights_delta_matrix);
return result; return weights_delta_matrix;
} }
Matrix* sigmoid_derivative(Matrix* matrix) { Matrix* sigmoid_derivative(Matrix* matrix) {

View file

@ -1,6 +1,6 @@
#include "matrix.h" #include "matrix/matrix.h"
#include "image.h" #include "image/image.h"
typedef struct { typedef struct {
int input_size; int input_size;