Skip to content
Snippets Groups Projects

Compare revisions

Changes are shown as if the source revision was being merged into the target revision. Learn more about comparing revisions.

Source

Select target project
No results found
Select Git revision
  • main
1 result

Target

Select target project
  • barryt/image-classification
1 result
Select Git revision
  • main
1 result
Show changes
Commits on Source (2)
Showing with 2274 additions and 85 deletions
/data
*.pyc
tests.ipynb
# Image classification
## 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/barryt/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/barryt/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.
## 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.
## Visuals
Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method.
## Installation
Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection.
## Usage
Use examples liberally, and show the expected output if you can. It's helpful to have inline the smallest example of usage that you can demonstrate, while providing links to more sophisticated examples if they are too long to reasonably include in the README.
## Support
Tell people where they can go to for help. It can be any combination of an issue tracker, a chat room, an email address, etc.
## Roadmap
If you have ideas for releases in the future, it is a good idea to list them in the README.
## Contributing
State if you are open to contributions and what your requirements are for accepting them.
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.
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.
This BE is about image classification. The goal is to classify images from CIFAR10 dataset and evaluate the accuracy of the models, firstly by using a simple KNN and then by using a manually implemented MLP with one hidden layer. The MLP is implemented using numpy and the forward and backward passes are implemented using the chain rule. The MLP is trained using SGD and the gradients are computed using backpropagation. The MLP is trained using the CIFAR10 dataset and the accuracy is evaluated on the test set.
## Authors and acknowledgment
Show your appreciation to those who have contributed to the project.
## Documentation
The `be_image_classification.ipynb` file contains the main code used to train and evaluate the models.
## License
For open source projects, say how it is licensed.
The functions implemented and used in this BE are located in the `utils` folder.
## 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.
The images located in the `images` folder are:
- `knn_accuracy.png`: the evolution of the accuracy of the model with respect to the number of neighbors
- `mlp_loss.png`: the evolution of the loss of the model with respect to the number of epochs, for the manually implemented MLP
- `mlp_loss_tf.png`: the evolution of the accuracy of the equivalent model implemented using tensorflow with respect to the number of epochs to compare with the manually implemented MLP and check that the implementation is correct
Source diff could not be displayed: it is too large. Options to address this: view the blob.
images/knn_accuracy.png

32.4 KiB

images/mlp_loss.png

22.5 KiB

images/mlp_loss_tf.png

20.7 KiB

import numpy as np
def binary_cross_entropy(predictions: np.ndarray, targets: np.ndarray):
# compute the binary cross-entropy loss (1e-7 is added to avoid log(0))
predictions = np.clip(predictions, 1e-7, 1 - 1e-7)
term_0 = (1-targets) * np.log(1-predictions)
term_1 = targets * np.log(predictions)
return -np.mean(term_0+term_1)
\ No newline at end of file
import numpy as np
def distance_matrix(X: np.ndarray, Y: np.ndarray):
# compute the distance matrix between two sets of samples
x2 = np.sum(X**2, axis=1, keepdims=True)
y2 = np.sum(Y**2, axis=1, keepdims=True)
xy = X.dot(Y.T)
return np.sqrt(x2 - 2 * xy + y2.T)
\ No newline at end of file
from utils.knn_predict import knn_predict
from utils.distance_matrix import distance_matrix
import numpy as np
def evaluate_knn(data_train, labels_train, data_test, labels_test, k):
# compute the accuracy of the kNN model
dists = distance_matrix(data_test, data_train)
y_pred = knn_predict(dists, labels_train, k)
accuracy = np.mean(y_pred == labels_test)
return accuracy
\ No newline at end of file
from utils.sigmoid import sigmoid
import numpy as np
def forward_pass(w1, b1, w2, b2, data):
# compute the forward pass of the MLP with sigmoid activations
z1 = np.matmul(data, w1) + b1
a1 = sigmoid(z1)
z2 = np.matmul(a1, w2) + b2
a2 = sigmoid(z2)
return a1, a2
\ No newline at end of file
import numpy as np
def knn_predict(dists: np.ndarray, labels_train, k):
# predict labels based on k nearest neighbors
n = dists.shape[0]
y_pred = np.zeros(n, dtype=np.int64)
for i in range(n):
closest_y = []
closest_y = labels_train[np.argsort(dists[i])[:k]]
y_pred[i] = np.argmax(np.bincount(closest_y))
return y_pred
\ No newline at end of file
import numpy as np
from utils.forward_pass import forward_pass
from utils.binary_cross_entropy import binary_cross_entropy
def adjust_weights_binary_cross_entropy(a1, a2, w1, b1, w2, b2, data, targets, learning_rate):
batch_size = data.shape[0]
dCdZ2 = a2 - targets
dCdW2 = np.matmul(a1.T, dCdZ2) / batch_size
dCdB2 = np.sum(dCdZ2, axis=0, keepdims=True) / batch_size
dCdA1 = np.matmul(dCdZ2, w2.T)
dCdZ1 = dCdA1 * a1 * (1 - a1)
dCdW1 = np.matmul(data.T, dCdZ1) / batch_size
dCdB1 = np.sum(dCdZ1, axis=0, keepdims=True) / batch_size
w2 -= learning_rate * dCdW2
w1 -= learning_rate * dCdW1
b1 -= learning_rate * dCdB1
b2 -= learning_rate * dCdB2
return w1, b1, w2, b2
def learn_once_cross_entropy(w1,b1,w2,b2,data,targets,learning_rate):
a1, a2 = forward_pass(w1, b1, w2, b2, data)
loss = binary_cross_entropy(a2, targets)
w1, b1, w2, b2 = adjust_weights_binary_cross_entropy(a1, a2, w1, b1, w2, b2, data, targets, learning_rate)
return w1, b1, w2, b2, loss
\ No newline at end of file
import numpy as np
from utils.forward_pass import forward_pass
def adjust_weights_mse(a1, a2, w1, b1, w2, b2, data, targets, learning_rate):
batch_size = data.shape[0]
N_out = targets.shape[1]
dCdA2 = 2 * (a2 - targets) / N_out
dCdZ2 = dCdA2 * a2 * (1 - a2)
dCdW2 = np.matmul(a1.T, dCdZ2) / batch_size
dCdB2 = np.sum(dCdZ2, axis=0, keepdims=True) / batch_size
dCdA1 = np.matmul(dCdZ2, w2.T)
dCdZ1 = dCdA1 * a1 * (1 - a1)
dCdW1 = np.matmul(data.T, dCdZ1) / batch_size
dCdB1 = np.sum(dCdZ1, axis=0, keepdims=True) / batch_size
w2 -= learning_rate * dCdW2
w1 -= learning_rate * dCdW1
b1 -= learning_rate * dCdB1
b2 -= learning_rate * dCdB2
return w1, b1, w2, b2
def learn_once_mse(w1: np.ndarray, b1: np.ndarray, w2: np.ndarray, b2: np.ndarray, data: np.ndarray, targets: np.ndarray, learning_rate: float):
a1, a2 = forward_pass(w1, b1, w2, b2, data)
loss = np.mean(np.square(a2 - targets))
w1, b1, w2, b2 = adjust_weights_mse(a1, a2, w1, b1, w2, b2, data, targets, learning_rate)
return w1, b1, w2, b2, loss
\ No newline at end of file
import tqdm
import numpy as np
from utils.forward_pass import forward_pass
from utils.one_hot import one_hot
from utils.learn_once_cross_entropy import learn_once_cross_entropy
def train_mlp(w1, b1, w2, b2, data_train, labels_train, learning_rate, num_epochs, batch_size, n_classes):
# train the MLP for num_epochs epochs, using batches of size batch_size
losses = []
for epoch in range(num_epochs):
for i in tqdm.tqdm(range(0, data_train.shape[0], batch_size)):
data = data_train[i:i+batch_size]
targets = one_hot(labels_train[i:i+batch_size], n_classes)
w1, b1, w2, b2, loss = learn_once_cross_entropy(w1, b1, w2, b2, data, targets, learning_rate)
losses.append(loss)
print(f'epoch={epoch}, loss={loss}')
return losses, w1, b1, w2, b2
def test_mlp(w1, b1, w2, b2, data_test, labels_test):
# test the MLP on data_test, and return the accuracy
_, a2 = forward_pass(w1, b1, w2, b2, data_test)
predictions = np.argmax(a2, axis=1)
test_accuracy = np.mean(predictions == labels_test)
return test_accuracy
def initialize_mlp(d_in, d_h, d_out):
# initialize the weights and biases of the MLP
w1 = 2 * np.random.rand(d_in, d_h) - 1
b1 = np.zeros((1, d_h))
w2 = 2 * np.random.rand(d_h, d_out) - 1
b2 = np.zeros((1, d_out))
return w1, b1, w2, b2
def run_mlp_training(data_train, labels_train, data_test, labels_test, d_h, learning_rate, num_epochs, batch_size, n_classes = 10):
# run the training and testing of the MLP on data_train and data_test
d_in = data_train.shape[1]
d_out = np.max(labels_train) + 1
w1, b1, w2, b2 = initialize_mlp(d_in, d_h, d_out)
losses, w1, b1, w2, b2 = train_mlp(w1, b1, w2, b2, data_train, labels_train, learning_rate, num_epochs, batch_size, n_classes)
test_accuracy = test_mlp(w1, b1, w2, b2, data_test, labels_test)
return losses, test_accuracy
\ No newline at end of file
import numpy as np
def one_hot(labels: np.ndarray, n_classes: int):
# convert an array of labels to a one-hot representation
n = labels.shape[0]
one_hot_labels = np.zeros((n, n_classes))
one_hot_labels[np.arange(n), labels] = 1
return one_hot_labels
\ No newline at end of file
import matplotlib.pyplot as plt
def plot_image_with_label(img, label):
# plot image with label
plt.imshow(img)
plt.title(label)
plt.show()
def save_plot_as_image(X, Y, y_label, x_label, save_path):
# plot and save image as png
plt.figure(figsize=(10,5))
plt.plot(X, Y)
plt.ylabel(y_label)
plt.xlabel(x_label)
plt.savefig(save_path)
plt.show()
plt.close()
\ No newline at end of file
import glob
import numpy as np
import pickle
def read_cifar_batch(batch_path):
# read a batch of cifar data
with open(batch_path, 'rb') as f:
batch = pickle.load(f, encoding='bytes')
data=np.array(batch[b'data'],dtype=np.float32)/255.0
labels=np.array(batch[b'labels'],dtype=np.int64)
return data, labels
def read_cifar(directory):
# read all cifar data in a directory
files = glob.glob(f'{directory}/*_batch*')
data = np.empty((0, 3072), dtype=np.float32)
labels = np.empty((0), dtype=np.int64)
for file in files:
batch_data, batch_labels = read_cifar_batch(file)
data = np.vstack((data, batch_data))
labels = np.hstack((labels, batch_labels))
#print(data.shape, labels.shape)
return data, labels
import numpy as np
def sigmoid(x):
return 1 / (1 + np.exp(-x))
\ No newline at end of file
import numpy as np
def split_dataset(data, labels, split: float)-> (np.ndarray, np.ndarray, np.ndarray, np.ndarray):
# split dataset into train and test
assert data.shape[0] == labels.shape[0]
# shuffle data
indices = np.arange(data.shape[0])
np.random.shuffle(indices)
data = data[indices]
labels = labels[indices]
# split data
split_index = int(data.shape[0] * split)
train_data = data[:split_index]
train_labels = labels[:split_index]
test_data = data[split_index:]
test_labels = labels[split_index:]
return train_data, train_labels, test_data, test_labels
\ No newline at end of file