diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..649ad0aa1b2834c31f07e7ff6e05840684574e78 --- /dev/null +++ b/.gitignore @@ -0,0 +1,167 @@ +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +share/python-wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.nox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +*.py,cover +.hypothesis/ +.pytest_cache/ +cover/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py +db.sqlite3 +db.sqlite3-journal + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +.pybuilder/ +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# IPython +profile_default/ +ipython_config.py + +# pyenv +# For a library or package, you might want to ignore these files since the code is +# intended to run in multiple environments; otherwise, check them in: +# .python-version + +# pipenv +# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. +# However, in case of collaboration, if having platform-specific dependencies or dependencies +# having no cross-platform support, pipenv may install dependencies that don't work, or not +# install all needed dependencies. +#Pipfile.lock + +# poetry +# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. +# This is especially recommended for binary packages to ensure reproducibility, and is more +# commonly ignored for libraries. +# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control +#poetry.lock + +# pdm +# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. +#pdm.lock +# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it +# in version control. +# https://pdm.fming.dev/#use-with-ide +.pdm.toml + +# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm +__pypackages__/ + +# Celery stuff +celerybeat-schedule +celerybeat.pid + +# SageMath parsed files +*.sage.py + +# Environments +.env +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ +.dmypy.json +dmypy.json + +# Pyre type checker +.pyre/ + +# pytype static type analyzer +.pytype/ + +# Cython debug symbols +cython_debug/ + +# PyCharm +# JetBrains specific template is maintained in a separate JetBrains.gitignore that can +# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore +# and can be added to the global gitignore or merged into this file. For a more nuclear +# option (not recommended) you can uncomment the following to ignore the entire idea folder. +#.idea/ + + +# Dataset +data/ + +# VSCode +.vscode/ diff --git a/README-instructions.md b/README-instructions.md new file mode 100644 index 0000000000000000000000000000000000000000..73d7e983fb7e0ad522223c511770f8a17c03f5ee --- /dev/null +++ b/README-instructions.md @@ -0,0 +1,223 @@ +# TD 1 : Image Classification + +MOD 4.6 Deep Learning & Artificial Intelligence: an introduction + + +## Introduction + +The objective of this tutorial is to write a complete image classification program in Python. +Two classification models will be successively developed and tested: k-nearest neighbors (KNN) and neural networks (NN). + +### Before you start + +In this tutorial we use Python 3.7 or higher. Make sure it is properly installed. Make sure `numpy` is installed. + +We assume that `git` is installed, and that you are familiar with the basic `git` commands. (Optionnaly, you can use GitHub Desktop.) +We also assume that you have access to the [ECL GitLab](https://gitlab.ec-lyon.fr/). If necessary, please consult [this tutorial](https://gitlab.ec-lyon.fr/edelland/inf_tc2/-/blob/main/Tutoriel_gitlab/tutoriel_gitlab.md). + +**Important note**: In this tutorial, you will be asked to write functions. If you want to test the correct operation of your functions in the same file, you must use the statement `if __name__ == "__main__":`: + +```python +def func(): + ... + +if __name__ == "__main__": + func() +``` + +### README + +Your repository must contain a text file `README.md` that introduces the project in a **short way**. To learn how to write a readme, visit https://www.makeareadme.com. We recommend that you include at least the sections _Description_ and _Usage_. + + +### Prepare your directory + +1. Create a new blank project on the ECL GitLab (`New project` then `Create blank project`). +2. Fill in the form as follows. + - Project name: `Image classification`. + - Project slug: `image-classification`. + - Visibility Level: public + - Project Configuration: Initialize repository with a README +3. Clone the repository. + ```bash + git clone https://gitlab.ec-lyon.fr/<user>/image-classification + ``` +4. In this tutorial you will use files that should not be pushed to the remote repository. To ignore them when committing, you can put their path in a file named `.gitignore`. For simplicity, we use the [`.gitignore` file](https://github.com/github/gitignore/blob/main/Python.gitignore) recommended by GitHub for Python projects. + + +## Prepare the CIFAR dataset + +The image database used for the experiments is CIFAR-10 which consists of 60 000 color images of size 32x32 divided into 10 classes (plane, car, bird, cat, ...). +This database can be obtained at the address https://www.cs.toronto.edu/~kriz/cifar.html where are also given the indications to read the data. + +1. Create a folder named `data` in which you move the downloaded `cifar-10-batches-py` folder. Make sure that the `data` folder is ignored when commiting. +2. Create a Python file named `read_cifar.py`. Write the function `read_cifar_batch` taking as parameter the path of a single batch as a string, and returning: + - a matrix `data` of size (`batch_size` x `data_size`) where `batch_size` is the number of available data in the batch, and `data_size` the dimension of these data (number of numerical values describing the data), and + - a vector `labels` of size `batch_size` whose values correspond to the class code of the data of the same index in `data`. + `data` must be `np.float32` array and `labels` must be `np.int64` array. +3. Write the function `read_cifar` taking as parameter the path of the directory containing the six batches (five `data_batch` and one `test_batch`) as a string, and returning + - a matrix `data` of shape (`batch_size` x `data_size`) where `batch_size` is the number of available data in all batches (including `test_batch`), and + - a vector `labels` of size `batch_size` whose values correspond to the class code of the data of the same index in `data`. + `data` must be `np.float32` array and `labels` must be `np.int64` array. +4. Write the function `split_dataset` which splits the dataset into a training set and a test set. The data must be shuffled, so that two successive calls shouldn't give the same output. This function takes as parameter + - `data` and `labels`, two arrays that have the same size in the first dimension. + - `split`, a float between 0 and 1 which determines the split factor of the training set with respect to the test set. + This function must return + - `data_train` the training data, + - `labels_train` the corresponding labels, + - `data_test` the testing data, and + - `labels_test` the corresponding labels. + +## k-nearest neighbors + +1. Create a Python fil named `knn.py`. Write the function `distance_matrix` taking as parameters two matrices and returns `dists`, the L2 Euclidean distance matrix. The computation must be done only with matrix manipulation (no loops). + Hint: $`(a-b)^2 = a^2 + b^2 - 2 ab`$ +2. Write the function `knn_predict` taking as parameters: + - `dists` the distance matrix between the train set and the test set, + - `labels_train` the training labels, and + - `k` the number of of neighbors. + This function must return the predicted labels for the elements of `data_test`. + + **Note:** if the memory occupation is too important, you can use several batches for the calculation of the distance matrix (loop on sub-batches of test data). +3. Write the function `evaluate_knn` taking as parameters: + - `data_train` the training data, + - `labels_train` the corresponding labels, + - `data_test` the testing data, + - `labels_test` the corresponding labels, and + - `k` the number of of neighbors. + This function must return the classification rate (accuracy). +4. For `split_factor=0.9`, plot the variation of the accuracy as a function of `k` (from 1 to 20). Save the plot as an image named `knn.png` in the directory `results`. + +## Artificial Neural Network + +The objective here is to develop a classifier based on a multilayer perceptron (MLP) neural network. + +First of all, let's focus on the backpropagation of the gradient with an example. If you still have trouble understanding the intuition behind the back propagation of the gradient, check out this video: [3Blue1Brown/Backpropagation calculus | Chapter 4, Deep learning](https://www.youtube.com/watch?v=tIeHLnjs5U8). + + +The weight matrix of the layer $`L`$ is denoted $`W^{(L)}`$. The bias vector of the layer $`L`$ is denoted $`B^{(L)}`$. We choose the sigmoid function, denoted $`\sigma`$, as the activation function. The output vector of the layer $`L`$ before activation is denoted $`Z^{(L)}`$. The output vector of the layer $`L`$ after activation is denoted $`A^{(L)}`$. By convention, we note $`A^{(0)}`$ the network input vector. Thus $`Z^{(L+1)} = W^{(L+1)}A^{(L)} + B^{(L+1)}`$ and $`A^{(L+1)} = \sigma\left(Z^{(L+1)}\right)`$. Let's consider a network with one hidden layer. Thus, the output is $`\hat{Y} = A^{(2)}`$. +Let $`Y`$ be the target (desired output). We use mean squared error (MSE) as the cost function. Thus, the cost is $`C = \frac{1}{N_{out}}\sum_{i=1}^{N_{out}} (\hat{y_i} - y_i)^2`$. + +1. Prove that $`\sigma' = \sigma \times (1-\sigma)`$ +2. Express $`\frac{\partial C}{\partial A^{(2)}}`$, i.e. the vector of $`\frac{\partial C}{\partial a^{(2)}_i}`$ as a function of $`A^{(2)}`$ and $`Y`$. +3. Using the chaining rule, express $`\frac{\partial C}{\partial Z^{(2)}}`$, i.e. the vector of $`\frac{\partial C}{\partial z^{(2)}_i}`$ as a function of $`\frac{\partial C}{\partial A^{(2)}}`$ and $`A^{(2)}`$. +4. Similarly, express $`\frac{\partial C}{\partial W^{(2)}}`$, i.e. the matrix of $`\frac{\partial C}{\partial w^{(2)}_{i,j}}`$ as a function of $`\frac{\partial C}{\partial Z^{(2)}}`$ and $`A^{(1)}`$. +5. Similarly, express $`\frac{\partial C}{\partial B^{(2)}}`$ as a function of $`\frac{\partial C}{\partial Z^{(2)}}`$. +6. Similarly, express $`\frac{\partial C}{\partial A^{(1)}}`$ as a function of $`\frac{\partial C}{\partial Z^{(2)}}`$ and $`W^{(2)}`$. +7. Similarly, express $`\frac{\partial C}{\partial Z^{(1)}}`$ as a function of $`\frac{\partial C}{\partial A^{(1)}}`$ and $`A^{(1)}`$. +8. Similarly, express $`\frac{\partial C}{\partial W^{(1)}}`$ as a function of $`\frac{\partial C}{\partial Z^{(1)}}`$ and $`A^{(0)}`$. +9. Similarly, express $`\frac{\partial C}{\partial B^{(1)}}`$ as a function of $`\frac{\partial C}{\partial Z^{(1)}}`$. + +Below is a Python code performing a forward pass and computing the cost in a network containing one hidden layer for the regression task. It uses the sigmoid function as the activation function: + +```python +import numpy as np + +N = 30 # number of input data +d_in = 3 # input dimension +d_h = 3 # number of neurons in the hidden layer +d_out = 2 # output dimension (number of neurons of the output layer) + +# Random initialization of the network weights and biaises +w1 = 2 * np.random.rand(d_in, d_h) - 1 # first layer weights +b1 = np.zeros((1, d_h)) # first layer biaises +w2 = 2 * np.random.rand(d_h, d_out) - 1 # second layer weights +b2 = np.zeros((1, d_out)) # second layer biaises + +data = np.random.rand(N, d_in) # create a random data +targets = np.random.rand(N, d_out) # create a random targets + +# Forward pass +a0 = data # the data are the input of the first layer +z1 = np.matmul(a0, w1) + b1 # input of the hidden layer +a1 = 1 / (1 + np.exp(-z1)) # output of the hidden layer (sigmoid activation function) +z2 = np.matmul(a1, w2) + b2 # input of the output layer +a2 = 1 / (1 + np.exp(-z2)) # output of the output layer (sigmoid activation function) +predictions = a2 # the predicted values are the outputs of the output layer + +# Compute loss (MSE) +loss = np.mean(np.square(predictions - targets)) +print(loss) +``` + +10. Create a Python file named `mlp.py`. Use the above code to write the function `learn_once_mse` taking as parameters: + - `w1`, `b1`, `w2` and `b2` the weights and biases of the network, + - `data` a matrix of shape (`batch_size` x `d_in`), + - `targets` a matrix of shape (`batch_size` x `d_out`), + - `learning_rate` the learning rate, + + that perform one gradient descent step, and returns: + - `w1`, `b1`, `w2` and `b2` the updated weights and biases of the network, + - `loss` the loss, for monitoring purpose. + + +MSE loss is not well suited for a classification task. Instead, we want to use the binary cross-entropy loss. To use this loss, we need the target to be is the one-hot encoding of the desired labels. Example: +``` +one_hot(labels=[1 2 0]) = [[0 1 0] + [0 0 1] + [1 0 0]] +``` + +We also need that the last activation layer of the network to be a softmax layer. + +11. Write the function `one_hot` taking a (n)-D array as parameters and returning the corresponding (n+1)-D one-hot matrix. +12. Write the function `learn_once_cross_entropy` taking as parameters: + - `w1`, `b1`, `w2` and `b2` the weights and biases of the network, + - `data` a matrix of shape (`batch_size` x `d_in`), + - `labels_train` a vector of size `batch_size`, and + - `learning_rate` the learning rate, + + that perform one gradient descent step using a binary cross-entropy loss. + We admit that $`\frac{\partial C}{\partial Z^{(2)}} = A^{(2)} - Y`$, where $`Y`$ is a one-hot vector encoding the label. + The function must return: + - `w1`, `b1`, `w2` and `b2` the updated weights and biases of the network, + - `loss` the loss, for monitoring purpose. +13. Write the function `train_mlp` taking as parameters: + - `w1`, `b1`, `w2` and `b2` the weights and biases of the network, + - `data_train` a matrix of shape (`batch_size` x `d_in`), + - `labels_train` a vector of size `batch_size`, + - `learning_rate` the learning rate, and + - `num_epoch` the number of training epoch, + + that perform `num_epoch` of training steps and returns: + - `w1`, `b1`, `w2` and `b2` the updated weights and biases of the network, + - `train_accuracies` the list of train accuracies across epochs as a list of floats. +14. Write the function `test_mlp` taking as parameters: + - `w1`, `b1`, `w2` and `b2` the weights and biases of the network, + - `data_test` a matrix of shape (`batch_size` x `d_in`), and + - `labels_test` a vector of size `batch_size`, + + testing the network on the test set and returns: + - `test_accuracy` the testing accuracy. +15. Write the function `run_mlp_training` taking as parameter: + - `data_train`, `labels_train`, `data_test`, `labels_test`, the training and testing data, + - `d_h` the number of neurons in the hidden layer + - `learning_rate` the learning rate, and + - `num_epoch` the number of training epoch, + + that train an MLP classifier and return the training accuracies across epochs as a list of floats and the final testing accuracy as a float. +16. For `split_factor=0.9`, `d_h=64`, `learning_rate=0.1` and `num_epoch=100`, plot the evolution of learning accuracy across learning epochs. Save the graph as an image named `mlp.png` in the `results` directory. + + +## To go further (optional) + +### Unittest + +Your code should contain unit tests. All unit tests should be contained in the `tests` directory located at the root of the directory. +We choose to use [pytest](https://docs.pytest.org/en/7.1.x/). To help you write unit tests, you can consult the pytest documentation. + +### Deep dive into the classifier + +Experiments will have to be carried out by studying the following variations: +- use image representation by descriptors (LBP, HOG, ...) instead of raw pixels using the `scikit-image` module. +- use of N-fold cross-validation instead of a fixed learning and testing subset. + + +## To be handed in + +This work must be done individually. The expected output is a repository on https://gitlab.ec-lyon.fr. It must contain the complete, minimal and functional code corresponding to this tutorial. + + +The last commit is due before 11:59 pm on Friday, November 10, 2023. Subsequent commits will not be considered. + + diff --git a/README.md b/README.md index 0f64602d3c72d95f23fe9fdf8488331a73083cf5..aa8c082dab18aa7096c89a383654a69f7e1cbefc 100644 --- a/README.md +++ b/README.md @@ -1,92 +1,39 @@ -# Image classification +# TD 1 : Image Classification +MOD 4.6 Deep Learning & Artificial Intelligence: an introduction +## Introduction -## 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://gitlab.ec-lyon.fr/mduhalde/image-classification.git -git branch -M main -git push -uf origin main -``` - -## Integrate with your tools - -- [ ] [Set up project integrations](https://gitlab.ec-lyon.fr/mduhalde/image-classification/-/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. +The objective of this tutorial is to write a complete image classification program in Python. +Two classification models will be successively developed and tested: k-nearest neighbors (KNN) and neural networks (NN). ## Description -Let people know what your project can do specifically. Provide context and add a link to any reference visitors might be unfamiliar with. A list of Features or a Background subsection can also be added here. If there are alternatives to your project, this is a good place to list differentiating factors. -## Badges -On some READMEs, you may see small images that convey metadata, such as whether or not all the tests are passing for the project. You can use Shields to add some to your README. Many services also have instructions for adding a badge. +This project contains several files and directory. A brief description of each is given. -## Visuals -Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method. - -## Installation -Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection. +- `data/`: This directory contains the raw dataset, downloaded from the [CIFAR-10 website](https://www.cs.toronto.edu/~kriz/cifar.html). This directory should contain the folder `cifar-10-batches-py/`, found within the tar file downloadable from the website. This folder is ignored from source tracking, so it should be created manually. +- `tests/`: This folder contains tests for each functionality. The test files are named `test_{source-file-to-test}.py`, and the functions to test are named `test_{function-to-test}`. +- `results/`: This folder contains some of the results generated by the program. +- `knn.py`: Contains functions related to the KNN algorithm. +- `read_cifar.py`: Contains functions related to reading and parsing the CIFAR-10 dataset. +- `nn.py`: Contains functions related to the Neural Network algorithm. +- `main.ipynb`: Jupyter Notebook containing the main program. It is used to the algorithms and generate the results. ## 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. +This program was made using the latest version of Python, `3.11.5`. This program requires the following packages: -## Contributing -State if you are open to contributions and what your requirements are for accepting them. +- `numpy==1.26.1` +- `notebook==7.0.6` +- `scikit-image==0.22.0` +- `pytest==7.4.2` -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. +The CIFAR-10 dataset should be downloaded and the extracted contents should be placed a `data` folder in the root of the project, before any execution. -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. +To trigger the tests, one should simply run `pytest` while on the root directory. -## Authors and acknowledgment -Show your appreciation to those who have contributed to the project. +The main program is contained in the `main.ipynb` file. It can be run using Jupyter Notebook or Jupyter Lab. The results are generated in the `results` folder. -## License -For open source projects, say how it is licensed. +## References -## 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. +- Data Source : The CIFAR-10 Dataset. <https://www.cs.toronto.edu/~kriz/cifar.html> diff --git a/knn.py b/knn.py new file mode 100644 index 0000000000000000000000000000000000000000..76d28ab650c95d4e5563d63ef26ec4bf2137fee0 --- /dev/null +++ b/knn.py @@ -0,0 +1,69 @@ +import numpy as np + + +def distance_matrix(matrix_a: np.ndarray, matrix_b: np.ndarray) -> np.ndarray: + """Calculate the distance matrix between two matrices. + + Args: + matrix_a (np.ndarray): Matrix of shape (n, d). + matrix_b (np.ndarray): Matrix of shape (m, d). + + Returns: + np.ndarray: The distance matrix, of shape (n, m) + """ + # sqrt((A - B)^2) = sqrt(A^2 + B^2 - 2AB) + + matrix_a_2 = np.sum(np.square(matrix_a), axis=1) + matrix_b_2 = np.sum(np.square(matrix_b), axis=1) + a_b = np.dot(matrix_a, matrix_b.T) + return np.sqrt(matrix_a_2[:, np.newaxis] + matrix_b_2 - 2 * a_b) + + +def knn_predict(dists: np.ndarray, labels_train: np.ndarray, k: int) -> np.ndarray: + """Generate predictions based on the distance matrix between the train and test datasets. + + Args: + dists (np.ndarray): The distance matrix (rows: test datapoints, columns: train datapoints), of size (n, m). + labels_train (np.ndarray): The labels of the training data, of size (m,). + k (int): The number of neighbors to use. + + Returns: + np.ndarray: The predicted labels, of size (n,). + """ + # for each row, get the indices of the k smallest values, then get the labels of those indices, then get the most common label + # argpartition sorts the first k elements of each row (axis=1) and returns the sorted indices (more efficient than argsort) + indices = np.argpartition(dists, k, axis=1)[:, :k] + + # get the labels of the indices + nearest_labels = labels_train[indices] + + # get the most common label + predicted_labels = np.array([np.bincount(row).argmax() for row in nearest_labels]) + + return predicted_labels + + +def evaluate_knn( + data_train: np.ndarray, + labels_train: np.ndarray, + data_test: np.ndarray, + labels_test: np.ndarray, + k: int, +) -> float: + """Evaluate the accuracy of k-nearest neighbors on the given dataset. + + Args: + data_train (np.ndarray): The training data. + labels_train (np.ndarray): The training data labels. + data_test (np.ndarray): The test data. + labels_test (np.ndarray): The test data labels. + k (int): The number of neighbors to use. + + Returns: + float: The accuracy of the model (between 0 and 1). + """ + dists = distance_matrix(data_test, data_train) + predicted_labels = knn_predict(dists, labels_train, k) + # Get array of ones and zeros and average over it + accuracy = (predicted_labels == labels_test).mean() + return accuracy diff --git a/main.ipynb b/main.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..48b0b864ea73fc38bcf1b9b6e379a711ae0d7e12 --- /dev/null +++ b/main.ipynb @@ -0,0 +1,261 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# TD 1 : Image Classification" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Dataset" + ] + }, + { + "cell_type": "code", + "execution_count": 20, + "metadata": {}, + "outputs": [], + "source": [ + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "from read_cifar import read_cifar, split_dataset" + ] + }, + { + "cell_type": "code", + "execution_count": 21, + "metadata": {}, + "outputs": [], + "source": [ + "DATASET_PATH = \"./data/cifar-10-batches-py\"" + ] + }, + { + "cell_type": "code", + "execution_count": 22, + "metadata": {}, + "outputs": [], + "source": [ + "cifar_data, cifar_labels = read_cifar(DATASET_PATH)" + ] + }, + { + "cell_type": "code", + "execution_count": 23, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[[ 59. 43. 50. ... 140. 84. 72.]\n", + " [154. 126. 105. ... 139. 142. 144.]\n", + " [255. 253. 253. ... 83. 83. 84.]\n", + " [ 28. 37. 38. ... 28. 37. 46.]\n", + " [170. 168. 177. ... 82. 78. 80.]]\n", + "[6 9 9 4 1]\n" + ] + } + ], + "source": [ + "print(cifar_data[0:5])\n", + "print(cifar_labels[0:5])" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## K-Nearest Neighbors (KNN) Classification" + ] + }, + { + "cell_type": "code", + "execution_count": 24, + "metadata": {}, + "outputs": [], + "source": [ + "from knn import evaluate_knn, distance_matrix, knn_predict" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Example with split = 0.8 and k = 3" + ] + }, + { + "cell_type": "code", + "execution_count": 25, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "(48000, 3072)\n", + "(48000,)\n", + "(12000, 3072)\n", + "(12000,)\n" + ] + } + ], + "source": [ + "example_split = 0.8\n", + "example_k = 3\n", + "example_train_data, example_train_labels, example_test_data, example_test_labels = split_dataset(cifar_data, cifar_labels, example_split)\n", + "\n", + "print(example_train_data.shape)\n", + "print(example_train_labels.shape)\n", + "print(example_test_data.shape)\n", + "print(example_test_labels.shape)" + ] + }, + { + "cell_type": "code", + "execution_count": 26, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "0.33066666666666666\n" + ] + } + ], + "source": [ + "example_accuracy = evaluate_knn(example_train_data, example_train_labels, example_test_data, example_test_labels, example_k)\n", + "\n", + "print(example_accuracy)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### split = 0.9 with K from 1 to 20" + ] + }, + { + "cell_type": "code", + "execution_count": 27, + "metadata": {}, + "outputs": [], + "source": [ + "# Split dataset into training and testing with 90% training and 10% testing\n", + "train_data_09, train_labels_09, test_data_09, test_labels_09 = split_dataset(cifar_data, cifar_labels, 0.9)" + ] + }, + { + "cell_type": "code", + "execution_count": 28, + "metadata": {}, + "outputs": [], + "source": [ + "# The distance matrix won't change, so we only calculate it once\n", + "dist_matrix_09 = distance_matrix(test_data_09, train_data_09)" + ] + }, + { + "cell_type": "code", + "execution_count": 29, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "k = 1, accuracy = 0.3506666666666667\n", + "k = 2, accuracy = 0.30716666666666664\n", + "k = 3, accuracy = 0.3298333333333333\n", + "k = 4, accuracy = 0.3328333333333333\n", + "k = 5, accuracy = 0.3323333333333333\n", + "k = 6, accuracy = 0.3383333333333333\n", + "k = 7, accuracy = 0.3401666666666667\n", + "k = 8, accuracy = 0.3395\n", + "k = 9, accuracy = 0.3416666666666667\n", + "k = 10, accuracy = 0.3388333333333333\n", + "k = 11, accuracy = 0.3416666666666667\n", + "k = 12, accuracy = 0.3426666666666667\n", + "k = 13, accuracy = 0.3435\n", + "k = 14, accuracy = 0.3405\n", + "k = 15, accuracy = 0.3395\n", + "k = 16, accuracy = 0.341\n", + "k = 17, accuracy = 0.3375\n", + "k = 18, accuracy = 0.33816666666666667\n", + "k = 19, accuracy = 0.33466666666666667\n", + "k = 20, accuracy = 0.333\n" + ] + } + ], + "source": [ + "accuracies_09 = []\n", + "\n", + "for k in range(1, 21):\n", + " predicted_labels_09 = knn_predict(dist_matrix_09, train_labels_09, k)\n", + " accuracy = (predicted_labels_09 == test_labels_09).mean()\n", + " accuracies_09.append(accuracy)\n", + " print(f\"k = {k}, accuracy = {accuracy}\")" + ] + }, + { + "cell_type": "code", + "execution_count": 32, + "metadata": {}, + "outputs": [ + { + "data": { + "image/png": "iVBORw0KGgoAAAANSUhEUgAAAkAAAAGwCAYAAABB4NqyAAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjguMCwgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy81sbWrAAAACXBIWXMAAA9hAAAPYQGoP6dpAABVYElEQVR4nO3dd3zTdf4H8FdGk+6ke9EW2gJlFygUUBC0LHHgAtFjlOHAeb3zd6KeOE57eqeiwoGDZRHEgQsZYgEFBcoqQ6BSVls66Ew60zT5/v5ok1Ip0ECSb9K8no9HH3emafquUvrq5/P+fN4SQRAEEBEREbkQqdgFEBEREdkbAxARERG5HAYgIiIicjkMQERERORyGICIiIjI5TAAERERkcthACIiIiKXIxe7AEdkNBpRUFAAHx8fSCQSscshIiKidhAEAVVVVQgPD4dUeuU1HgagNhQUFCAyMlLsMoiIiOga5OXloVOnTld8DgNQG3x8fAA0/Qv09fUVuRoiIiJqD61Wi8jISPPP8SthAGqDadvL19eXAYiIiMjJtKd9hU3QRERE5HIYgIiIiMjlMAARERGRy2EAIiIiIpfDAEREREQuhwGIiIiIXA4DEBEREbkcBiAiIiJyOQxARERE5HIYgIiIiMjlMAARERGRy2EAIiIiIpfDYah2VK83oLRaB4VMimBfd7HLISIicllcAbKj/20/hRvf2Ib3tp4UuxQiIiKXxgBkR2oPNwBAZa1e5EqIiIhcm0MEoEWLFqFz585wd3dHUlISMjMzL/vcdevWITExEWq1Gl5eXkhISEB6enqr58yYMQMSiaTV27hx42z9ZVyV2rMpAGnqGICIiIjEJHoP0Nq1a5GamoolS5YgKSkJCxYswNixY5GdnY3g4OBLnu/v74/nn38e8fHxUCgUWL9+PVJSUhAcHIy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8Mu655x6Ehobi1KlT+L//+z/ExcVh7NixIlbdpD1/t2u1WnzxxRd46623xCqzTVer/YsvvkBQUBCioqJw5MgRPPXUU5g4cSLGjBkjYtVWJPYxNFexbds2AcAlb9OnTxe7tKuaOXOmEB0dLSgUCiEoKEi45ZZbhB9//FHsstpl8uTJQlhYmKBQKISIiAhh8uTJQk5OjthlWWTz5s0CACE7O1vsUiy2du1aISYmRlAoFEJoaKjw2GOPCZWVlWKX1aarfY8uX768zffPnz9f1LoF4cq119XVCXfddZcQHh4uKBQKISwsTLjjjjuEzMxMscs2u1L9tbW1wpgxY4SgoCDBzc1NiI6OFubMmSMUFRWJXbYgCO37u/2DDz4QPDw8HO7P/tVqf/fdd4VOnToJbm5uQlRUlPDCCy8IOp1O3KKtSCIIHaSbiYiIiKid2ANERERELocBiIiIiFwOAxARERG5HAYgIiIicjkMQERERORyGICIiIjI5TAAERERkcthACIiIiKXwwBERC5h5MiRePrpp8Uug4gcBAMQERERuRwGICIiInI5DEBE5JJ++OEHqFQqfPrpp2KXQkQikItdABGRva1evRqPPPIIVq9ejdtuu03scohIBFwBIiKXsmjRIsydOxfff/89ww+RC+MKEBG5jC+//BIXLlzAr7/+ikGDBoldDhGJiCtAROQy+vfvj6CgICxbtgyCIIhdDhGJiAGIiFxGbGwstm3bhm+//RZPPPGE2OUQkYi4BUZELqVbt27Ytm0bRo4cCblcjgULFohdEhGJgAGIiFxO9+7dsXXrVowcORIymQxvvfWW2CURkZ1JBG6EExERkYthDxARERG5HAYgIiIicjkMQERERORyGICIiIjI5TAAERERkcthACIiIiKXwwBERERELocBiIiIiFwOAxARERG5HAYgIiIicjkMQERERORy/h8QWNrfUqRJ+gAAAABJRU5ErkJggg==", + "text/plain": [ + "<Figure size 640x480 with 1 Axes>" + ] + }, + "metadata": {}, + "output_type": "display_data" + } + ], + "source": [ + "plt.plot(range(1, 21), accuracies_09)\n", + "plt.xlabel(\"k\")\n", + "plt.xticks(range(1, 21, 2))\n", + "plt.ylabel(\"Accuracy\")\n", + "plt.savefig('./results/knn.png')\n", + "plt.show()\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": ".venv", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.11.5" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/read_cifar.py b/read_cifar.py new file mode 100644 index 0000000000000000000000000000000000000000..1ca59d3a9cb3c021d62a791e31032d8c3708fa51 --- /dev/null +++ b/read_cifar.py @@ -0,0 +1,84 @@ +import pickle + +import numpy as np + + +def read_cifar_batch(path: str) -> (np.ndarray, np.ndarray): + """Reads the batch of CIFAR-10 data corresponding to the given path. + + Args: + path (str): The path to the batch file. + + Returns: + (np.ndarray, np.ndarray): A tuple containing the data and labels contained in the batch file. + """ + with open(path, "rb") as file: + dict_ = pickle.load(file, encoding="bytes") + raw_data = dict_[b"data"] + data_array = np.array(raw_data, dtype=np.float32) + + raw_labels = dict_[b"labels"] + labels_array = np.array(raw_labels, dtype=np.int64) + + return data_array, labels_array + + +def read_cifar(path: str) -> (np.ndarray, np.ndarray): + """Reads the CIFAR-10 dataset from the given path. The path must contain files data_batch_1 to 5, and test_batch. + + Args: + path (str): The path to the folder containing the batches. + + Returns: + (np.ndarray, np.ndarray): A tuple containing the dataset's data and labels. The data also includes the test data. + """ + batch_filenames = [f"{path}/data_batch_{i}" for i in range(1, 6)] + [ + f"{path}/test_batch" + ] + cifar_data = None + cifar_labels = None + for filename in batch_filenames: + batch_data, batch_labels = read_cifar_batch(filename) + if cifar_data is None: + cifar_data = batch_data + else: + cifar_data = np.concatenate((cifar_data, batch_data)) + if cifar_labels is None: + cifar_labels = batch_labels + else: + cifar_labels = np.concatenate((cifar_labels, batch_labels)) + + return cifar_data, cifar_labels + + +def split_dataset( + data: np.ndarray, + labels: np.ndarray, + split: float, +) -> (np.ndarray, np.ndarray, np.ndarray, np.ndarray): + """Splits the dataset into a training and test set. + + Args: + data (np.ndarray): The data to split. + labels (np.ndarray): The labels to split. + split (float): The fraction of the data to use for training. + + Returns: + (np.ndarray, np.ndarray, np.ndarray, np.ndarray): A tuple containing the training data, training labels, test data, and test labels. + """ + # get array of indices from the length of the data + indices = np.arange(data.shape[0]) + # shuffle the indices around + np.random.shuffle(indices) + # match entries to the shuffled indices + shuffled_data = data[indices] + suffled_labels = labels[indices] + + split_index = round(split * shuffled_data.shape[0]) + + data_train = shuffled_data[:split_index] + labels_train = suffled_labels[:split_index] + data_test = shuffled_data[split_index:] + labels_test = suffled_labels[split_index:] + + return data_train, labels_train, data_test, labels_test diff --git a/results/knn.png b/results/knn.png new file mode 100644 index 0000000000000000000000000000000000000000..f428964fb1937c49736e5d51031c8774556cd188 Binary files /dev/null and b/results/knn.png differ diff --git a/tests/__init__.py b/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tests/test_knn.py b/tests/test_knn.py new file mode 100644 index 0000000000000000000000000000000000000000..716d55f8fb76e4fb377d7f4f5e932b64a1a0c03d --- /dev/null +++ b/tests/test_knn.py @@ -0,0 +1,69 @@ +from math import sqrt + +import numpy as np + +from knn import distance_matrix, evaluate_knn, knn_predict + + +def test_distance_matrix(): + matrix_a = np.array([[1, 2], [3, 4], [5, 6]]) + matrix_b = np.array([[10, 9], [8, 7]]) + + expected = np.array( + [ + [sqrt((1 - 10) ** 2 + (2 - 9) ** 2), sqrt((1 - 8) ** 2 + (2 - 7) ** 2)], + [sqrt((3 - 10) ** 2 + (4 - 9) ** 2), sqrt((3 - 8) ** 2 + (4 - 7) ** 2)], + [sqrt((5 - 10) ** 2 + (6 - 9) ** 2), sqrt((5 - 8) ** 2 + (6 - 7) ** 2)], + ] + ) + + result = distance_matrix(matrix_a, matrix_b) + + print(result) + print(expected) + + assert np.allclose(result, expected) + + +def test_knn_predict(): + dists = np.array( + [ + [1, 2, 3, 4, 5, 6], + [6, 5, 4, 3, 2, 1], + ] + ) + labels_train = np.array([1, 1, 1, 2, 2, 2]) + k = 3 + + expected = np.array([1, 2]) + + result = knn_predict(dists, labels_train, k) + + assert np.allclose(result, expected) + + +def test_evaluate_knn(): + data_train = np.array( + [ + [10, 10], + [20, 20], + [30, 30], + [40, 40], + [50, 50], + ] + ) + labels_train = np.array([5, 4, 3, 2, 1]) + data_test = np.array( + [ + [19, 19], + [42, 42], + ] + ) + labels_test = np.array([4, 2]) + k = 1 + + expected = 1.0 + + result = evaluate_knn(data_train, labels_train, data_test, labels_test, k) + + assert np.allclose(result, expected) diff --git a/tests/test_read_cifar.py b/tests/test_read_cifar.py new file mode 100644 index 0000000000000000000000000000000000000000..4d230cfb535cdf2a06537990f76dc024b52d0393 --- /dev/null +++ b/tests/test_read_cifar.py @@ -0,0 +1,62 @@ +import numpy as np + +from read_cifar import read_cifar, read_cifar_batch, split_dataset + +DATASET_PATH = "./data/cifar-10-batches-py" + + +def test_read_cifar_batch(): + data, labels = read_cifar_batch(f"{DATASET_PATH}/data_batch_1") + + # check dimensions + assert data.shape == (10000, 3072) + assert labels.shape == (10000,) + # check types + assert data.dtype == np.float32 + assert labels.dtype == np.int64 + + +def test_read_cifar(): + data, labels = read_cifar(DATASET_PATH) + + # check dimensions + assert data.shape == (60000, 3072) + assert labels.shape == (60000,) + # check types + assert data.dtype == np.float32 + assert labels.dtype == np.int64 + + +def test_split_dataset(): + cifar_data, cifar_labels = read_cifar(DATASET_PATH) + split = 0.8 + + datapoint_size = cifar_data.shape[1] + + data_train, labels_train, data_test, labels_test = split_dataset( + cifar_data, cifar_labels, split + ) + + expected_train_size = round(split * cifar_data.shape[0]) + expected_test_size = cifar_data.shape[0] - expected_train_size + + # check dimensions + assert data_train.shape == (expected_train_size, datapoint_size) + assert labels_train.shape == (expected_train_size,) + assert data_test.shape == (expected_test_size, datapoint_size) + assert labels_test.shape == (expected_test_size,) + + # check types + assert data_train.dtype == cifar_data.dtype + assert labels_train.dtype == cifar_labels.dtype + assert data_test.dtype == cifar_data.dtype + assert labels_test.dtype == cifar_labels.dtype + + # check that the first data and label are still in the dataset and match indices + # pick random index in the training set + i = np.random.randint(0, expected_train_size) + random_data = data_train[i] + random_label = labels_train[i] + # check that the data and label match in original dataset + original_index = np.where(np.all(cifar_data == random_data, axis=1))[0][0] + assert cifar_labels[original_index] == random_label