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.

22 commits

Author SHA1 Message Date
Jakob Stornig
aa58f99045 minor changes 2023-09-25 11:11:07 +02:00
Jakob Stornig
ac35897396 Merge remote-tracking branch 'origin/main' 2023-09-24 22:36:51 +02:00
Jakob Stornig
746f4cf3bd deleted unused functions 2023-09-24 22:36:40 +02:00
jastornig
754d170616 Update .gitlab-ci.yml file 2023-09-24 20:36:11 +00:00
jastornig
8b4f2e2ccd Merge branch 'ci-testing' into 'main'
Ci testing

See merge request jastornig/c-net!12
2023-09-24 20:31:36 +00:00
Jakob Stornig
1cfdf93f7c (fix) evaluation
trained with 50000 images
evaluated with 10000
2023-09-24 22:29:41 +02:00
jastornig
e821afdbd5 Update .gitlab-ci.yml file 2023-09-24 20:23:22 +00:00
jastornig
a681833712 Update .gitlab-ci.yml file 2023-09-24 20:19:40 +00:00
jastornig
77b67aa949 Update .gitlab-ci.yml file 2023-09-24 20:12:14 +00:00
Jakob Stornig
38fafa672c minor changes for pgm files 2023-09-24 21:27:59 +02:00
jastornig
b9c3e93564 Update .gitlab-ci.yml file 2023-09-24 19:20:20 +00:00
jastornig
8ba83737f5 Merge branch 'merge-me' into 'main'
Update file README.md

See merge request jastornig/c-net!11
2023-09-24 19:07:59 +00:00
rawalcher
2d7fe49598 Update file README.md 2023-09-24 19:07:24 +00:00
jastornig
7bf2b88902 Merge branch 'lass-mi-de-drecks-readme-mergen' into 'main'
Lass mi de drecks readme mergen

See merge request jastornig/c-net!10
2023-09-24 19:02:24 +00:00
Raphael Walcher
eec607f7dd picture 2023-09-24 21:00:37 +02:00
jastornig
61339556c7 Merge branch 'Demonstration' into 'main'
!(feat) cli implemented

See merge request jastornig/c-net!9
2023-09-24 18:59:58 +00:00
Raphael Walcher
2019d56122 picture 2023-09-24 20:58:34 +02:00
Jakob Stornig
e9881ed2b3 !(feat) cli implemented
breaking changes.
save_network in neuronal_network.c now takes a second parameter file_name
2023-09-24 20:56:44 +02:00
jastornig
a282601751 Merge branch 'lass-mi-de-drecks-readme-mergen' into 'main'
readme

See merge request jastornig/c-net!8
2023-09-24 18:54:55 +00:00
Raphael Walcher
b9dba1a92b readme 2023-09-24 20:51:27 +02:00
jastornig
f13d3950b0 (fix) image loader windows 2023-09-23 20:30:25 +00:00
jastornig
dce3e264d9 Merge branch 'Delta-Error-Test' into 'main'
HolyFuckItsAlive

See merge request jastornig/c-net!6
2023-09-23 20:27:53 +00:00
8 changed files with 209 additions and 137 deletions

56
.gitlab-ci.yml Normal file
View 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!"

104
README.md
View file

@ -1,92 +1,36 @@
# 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 C 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](https://camo.githubusercontent.com/b308207b5c5ce0970b13c21609350fab21aa61a2fae56da2a6418d6fdcdbc079/68747470733a2f2f7777772e776f6c6672616d2e636f6d2f6d617468656d61746963612f6e65772d696e2d31302f656e68616e6365642d696d6167652d70726f63657373696e672f48544d4c496d616765732e656e2f68616e647772697474656e2d6469676974732d636c617373696669636174696f6e2f736d616c6c7468756d625f31302e676966)
## 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 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 ## 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 ![amogus](https://media.tenor.com/7kpsm7kU330AAAAd/sussy-among-us.gif)
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.

25
image.c
View file

@ -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){ void read_until_space_or_newline(char * buff, int maxCount, FILE * fptr){
int bufferOffset = 0; int bufferOffset = 0;
char c = -1; char c;
int counter = 0;
do{ do{
c = (char)getc(fptr); c = (char)getc(fptr);
buff[bufferOffset++] = c; 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; buff[bufferOffset-1] = 0;
} }
Image * load_pgm_image(char * image_file_string){ Image * load_pgm_image(char * image_file_string){
FILE * fptr = fopen(image_file_string, "r"); 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 *image = malloc(sizeof(Image));
image->label = -1; image->label = -1;
char buffer[100]; char buffer[2048];
int magic_number = 0;
fgets(buffer, 4, fptr); fgets(buffer, 4, fptr);
if(buffer[0] != 'P' || buffer[1] != '5'){ if(buffer[0] != 'P' || buffer[1] != '5'){
printf("Wrong file Format"); printf("Wrong file Format");
@ -40,17 +44,16 @@ Image * load_pgm_image(char * image_file_string){
fgets(buffer, 1024, fptr); 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); 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); 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); 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); image->pixel_values = matrix_create(image_height, image_width);
for(int i = 0; i < image_height; i++){ 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) { 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) {

123
main.c
View file

@ -2,28 +2,121 @@
#include "image.h" #include "image.h"
#include "neuronal_network.h" #include "neuronal_network.h"
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include "util.h"
int main() { void parsingErrorPrintHelp(){
Image** images = import_images("../data/train-images.idx3-ubyte", "../data/train-labels.idx1-ubyte", NULL, 60000); printf("Syntax: c_net [train | predict]\n");
// img_visualize(images[0]); printf("commands:\n");
// img_visualize(images[1]); printf("train\t train the network\n");
printf("predict\t load a pgm image and predict_demo the number\n");
exit(1);
}
// matrix_print(images[0]->pixel_values); void parsingErrorTrain(){
// matrix_print(images[1]->pixel_values); 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 = new_network(28*28, 40, 5, 10, 0.08); void parsingErrorDetect(){
randomize_network(nn, 1); printf("invalid syntax\n");
// Neural_Network* nn = load_network("../networks/newest_network.txt"); printf("Syntax: c_net predict_demo [path_to_network] [image_file]\n");
// printf("Done loading!\n"); }
// batch_train(nn, images, 20000, 20); 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 < 30000; ++i) { Neural_Network * nn = load_network(network_file);
train_network(nn, images[i], images[i]->label); 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;
save_network(nn); int training_image_count = 50000;
int testing_image_count = 10000;
printf("%lf\n", measure_network_accuracy(nn, images, 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) {
// 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();
} }

View file

@ -216,21 +216,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) {
@ -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){ void matrix_save(Matrix* matrix, char* file_string){
// open the file in append mode // open the file in append mode

View file

@ -36,6 +36,4 @@ Matrix* subtract(Matrix* matrix1, Matrix* matrix2);
Matrix* dot(Matrix* matrix1, Matrix* matrix2); Matrix* dot(Matrix* matrix1, Matrix* matrix2);
Matrix* apply(double (*function)(double), Matrix* matrix); Matrix* apply(double (*function)(double), Matrix* matrix);
Matrix* scale(Matrix* matrix, double value); Matrix* scale(Matrix* matrix, double value);
Matrix* addScalar(Matrix* matrix, double value);
Matrix* transpose(Matrix* matrix); Matrix* transpose(Matrix* matrix);
double matrix_sum(Matrix* matrix);

View file

@ -2,6 +2,7 @@
#include "neuronal_network.h" #include "neuronal_network.h"
#include <stdio.h> #include <stdio.h>
#include <math.h> #include <math.h>
#include "util.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);
@ -45,9 +46,7 @@ void free_network(Neural_Network* network){
free(network); free(network);
} }
void save_network(Neural_Network* network) { void save_network(Neural_Network* network, char * file_name) {
char* file_name = "../networks/newest_network.txt";
// create file // create file
FILE* save_file = fopen(file_name, "w"); FILE* save_file = fopen(file_name, "w");
@ -117,7 +116,10 @@ void print_network(Neural_Network* network) {
double measure_network_accuracy(Neural_Network* network, Image** images, int amount) { double measure_network_accuracy(Neural_Network* network, Image** images, int amount) {
int num_correct = 0; int num_correct = 0;
printf("evaluating network\n");
if(amount > 10000) amount = 10000;
for (int i = 0; i < amount; i++) { for (int i = 0; i < amount; i++) {
updateBar(i*100/amount);
Matrix* prediction = predict_image(network, images[i]); Matrix* prediction = predict_image(network, images[i]);
int guess = matrix_argmax(prediction); int guess = matrix_argmax(prediction);
@ -129,6 +131,7 @@ double measure_network_accuracy(Neural_Network* network, Image** images, int amo
matrix_free(prediction); matrix_free(prediction);
} }
updateBar(100);
return ((double) num_correct) / amount; return ((double) num_correct) / amount;
} }

View file

@ -21,7 +21,7 @@ Neural_Network* new_network(int input_size, int hidden_size, int hidden_amount,
void randomize_network(Neural_Network* network, int scope); void randomize_network(Neural_Network* network, int scope);
void free_network(Neural_Network* network); 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); Neural_Network* load_network(char* file);
void print_network(Neural_Network* network); void print_network(Neural_Network* network);