Skip to content
Snippets Groups Projects
Commit 470ca767 authored by corentin's avatar corentin
Browse files

Redaction of the answers on the README file

parent ca625f2e
No related branches found
No related tags found
No related merge requests found
# Image classification # Image classification
Corentin MASSALA
## Prepare the CIFAR dataset
All the code can be found on the python file read_cifar.py
## Getting started #### 2-
```
def read_cifar_batch(file):
with open(file, 'rb') as fo:
dict = pickle.load(fo, encoding='bytes')
return (np.array(dict[b'data']).astype('float32'), np.array(dict[b'labels']).astype('int64') )
```
#### 3-
```
def read_cifar(path):
data = []
labels = []
#Add the 5 batches
for i in range(1,6):
data_temp, labels_temps = read_cifar_batch(f'{path}/data_batch_{i}')
data.append(data_temp)
labels.append(labels_temps)
#Add the test batches
data_temp, labels_temps = read_cifar_batch(f'{path}/test_batch')
data.append(data_temp)
labels.append(labels_temps)
#Concatenate all the batches to create a big one
data = np.concatenate(data, axis = 0)
labels = np.concatenate(labels, axis = 0)
return(data, labels)
```
#### 4-
To make it easy for you to get started with GitLab, here's a list of recommended next steps. To split the dataset we use the split function from the sklearn library
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)! ```
def split_dataset(data, labels, split):
X_train, X_test, y_train, y_test = train_test_split(
data, labels, test_size=(1 - split), random_state=0)
return(X_train, X_test, y_train, y_test)
```
## 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 ## K-nearest neighbors
- [ ] [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: All the code can be found on the python file knn.py
#### 1-
```
def distance_matrix(matrix1, matrix2):
#X_test then X_train in this order
sum_of_squares_matrix1 = np.sum(np.square(matrix1), axis=1, keepdims=True) #A^2
sum_of_squares_matrix2 = np.sum(np.square(matrix2), axis=1, keepdims=True) #B^2
dot_product = np.dot(matrix1, matrix2.T) # A * B (matrix mutliplication)
dists = np.sqrt(sum_of_squares_matrix1 + sum_of_squares_matrix2.T - 2 * dot_product) # Compute the product
return dists
```
#### 2-
``` ```
cd existing_repo def knn_predict(dists, labels_train, k):
git remote add origin https://gitlab.ec-lyon.fr/cmassala/image-classification.git output = []
git branch -M main # Loop on all the images_test
git push -uf origin main for i in range(len(dists)):
# Innitialize table to store the neighbors
res = [0] * 10
# Get the closest neighbors
labels_close = np.argsort(dists[i])[:k]
for label in labels_close:
#add a label to the table of result
res[labels_train[label]] += 1
# Get the class with the maximum neighbors
label_temp = np.argmax(res) #Careful to the logic here, if there is two or more maximum, the function the first maximum encountered
output.append(label_temp)
return(np.array(output))
``` ```
## Integrate with your tools #### 3-
```
def evaluate_knn(data_train, labels_train, data_test, labels_tests, k):
dist = distance_matrix(data_test, data_train)
result_test = knn_predict(dist, labels_train, k)
#accuracy
N = labels_tests.shape[0]
accuracy = (labels_tests == result_test).sum() / N
return(accuracy)
```
#### 4-
```
def bench_knn():
k_indices = [i for i in range(20) if i % 2 != 0]
accuracies = []
# Load data
data, labels = read_cifar.read_cifar('image-classification/data/cifar-10-batches-py')
X_train, X_test, y_train, y_test = read_cifar.split_dataset(data, labels, 0.9)
# Loop on the k_indices to get all the accuracies
for k in k_indices:
accuracy = evaluate_knn(X_train, y_train, X_test, y_test, k)
accuracies.append(accuracy)
# Save and show the graph of accuracies
fig = plt.figure()
plt.plot(k_indices, accuracies)
plt.title("Accuracy as function of k")
plt.show()
plt.savefig('image-classification/results/knn_batch_1.png')
plt.close(fig)
```
Here is the graph of the accuracy vs K for the whole Cifar dataset with a split factor of 0.9:
![Image](results/knn.png)
Here we can conclude that the best K is 9, (if we don't use k = 1) with a performace of 35% of accuracy.
## Artificial Neural Network
### Math Theory
Here are all the answer for the theory of the backpropagation.
- [ ] [Set up project integrations](https://gitlab.ec-lyon.fr/cmassala/image-classification/-/settings/integrations) #### 1-
![Image](theory/q1.png)
## Collaborate with your team #### 2-
![Image](theory/q2.png)
- [ ] [Invite team members and collaborators](https://docs.gitlab.com/ee/user/project/members/) #### 3-
- [ ] [Create a new merge request](https://docs.gitlab.com/ee/user/project/merge_requests/creating_merge_requests.html) ![Image](theory/q3.png)
- [ ] [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 #### 4-
![Image](theory/q4.png)
Use the built-in continuous integration in GitLab. #### 5-
![Image](theory/q5.png)
- [ ] [Get started with GitLab CI/CD](https://docs.gitlab.com/ee/ci/quick_start/index.html) #### 6-
- [ ] [Analyze your code for known vulnerabilities with Static Application Security Testing(SAST)](https://docs.gitlab.com/ee/user/application_security/sast/) ![Image](theory/q6.png)
- [ ] [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)
*** #### 7-
![Image](theory/q7.png)
# Editing this README #### 8-
![Image](theory/q8.png)
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. #### 9-
![Image](theory/q9.png)
## 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 ### Coding part
Choose a self-explaining name for your project. All the code can be found on the file mlp.py
## 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. def learn_once_mse(w1, b1, w2, b2, data, targets, learning_rate):
N_out = len(targets) #number of training examples
# 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 = sigmoid(z1) # output of the hidden layer (sigmoid activation function)
z2 = np.matmul(a1, w2) + b2 # input of the output layer
a2 = sigmoid(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(f'loss: {loss}')
# print('shape a1', a1.shape)
# print('shape w1', w1.shape)
# print('shape b1', b1.shape)
# print('shape a2', a2.shape)
# print('shape w2', w2.shape)
# print('shape b2', b2.shape)
# Backpropagation
delta_a2 = 2 / N_out * (a2 - targets)
# print('shape delta_a2', delta_a2.shape)
delta_z2 = delta_a2 * (a2 * (1 - a2))
# print('shape delta_z2', delta_z2.shape)
delta_w2 = np.dot(a1.T, delta_z2)
# print('shape delta_w2', delta_w2.shape)
delta_b2 = delta_z2
delta_a1 = np.dot(delta_z2, w2.T)
# print('shape delta_a1', delta_a1.shape)
delta_z1 = delta_a1 * (a1 * (1- a1))
# print('shape delta_z1', delta_z1.shape)
delta_w1 = np.dot(a0.T, delta_z1)
# print('shape delta_w1', delta_w2.shape)
delta_b1 = delta_z1
# Update weights and biases
w2 -= learning_rate * delta_w2
b2 -= learning_rate * np.sum(delta_b2, axis = 0, keepdims = True)
w1 -= learning_rate * delta_w1
b1 -= learning_rate * np.sum(delta_b1, axis = 0, keepdims = True)
return w1, b1, w2, b2, loss
```
## Badges #### 11-
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. ```
def one_hot(labels):
#num_classes = np.max(labels) + 1 on va le hardcoder ici
num_classes = 10
one_hot_matrix = np.eye(num_classes)[labels]
return one_hot_matrix
```
## Visuals #### 12-
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. The cross_entropy_loss is :
```
def cross_entropy_loss(y_pred, y_true):
loss = -np.sum(y_true * np.log(y_pred)) / len(y_pred)
return loss
```
The new learning function is :
## 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. def learn_once_cross_entropy(w1, b1, w2, b2, data, labels_train, learning_rate):
## Usage N_out = len(labels_train) #number of training examples
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 # Forward pass
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. a0 = data # the data are the input of the first layer
z1 = np.matmul(a0, w1) + b1 # input of the hidden layer
a1 = sigmoid(z1) # output of the hidden layer (sigmoid activation function)
z2 = np.matmul(a1, w2) + b2 # input of the output layer
a2 = softmax_stable(z2) # output of the output layer (sigmoid activation function)
predictions = a2 # the predicted values are the outputs of the output layer
## Roadmap
If you have ideas for releases in the future, it is a good idea to list them in the README.
## Contributing # Compute loss (cross-entropy loss)
State if you are open to contributions and what your requirements are for accepting them. y_true_one_hot = one_hot(labels_train)
loss = cross_entropy_loss(predictions, y_true_one_hot)
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. # Backpropagation
delta_z2 = (a2 - y_true_one_hot)
delta_w2 = np.dot(a1.T, delta_z2) / N_out # We divide by the sample size to have an average on the error and avoid big gradient jumps
delta_b2 = delta_z2 / N_out
## Authors and acknowledgment
Show your appreciation to those who have contributed to the project.
## License delta_a1 = np.dot(delta_z2, w2.T)
For open source projects, say how it is licensed. delta_z1 = delta_a1 * (a1 * (1 - a1))
delta_w1 = np.dot(a0.T, delta_z1) / N_out
delta_b1 = delta_z1 / N_out
## Project status # Update weights and biases
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. w2 -= learning_rate * delta_w2
b2 -= learning_rate * np.sum(delta_b2, axis = 0, keepdims = True)
w1 -= learning_rate * delta_w1
b1 -= learning_rate * np.sum(delta_b1, axis = 0, keepdims = True)
return w1, b1, w2, b2, loss
```
#### 13-
```
def forward(w1, b1, w2, b2, data):
# 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 = sigmoid(z1) # output of the hidden layer (sigmoid activation function)
z2 = np.matmul(a1, w2) + b2 # input of the output layer
a2 = softmax_stable(z2) # output of the output layer (sigmoid activation function)
predictions = a2 # the predicted values are the outputs of the output layer
return(predictions)
```
```
def train_mlp(w1, b1, w2, b2, data_train, labels_train, learning_rate, num_epoch):
train_accuracies = []
for epoch in range(num_epoch):
w1, b1, w2, b2, loss = learn_once_cross_entropy(w1, b1, w2, b2, data_train, labels_train, learning_rate)
# Compute accuracy
predictions = forward(w1, b1, w2, b2, data_train)
predicted_labels = np.argmax(predictions, axis=1)
# print(predictions.shape)
# print(predicted_labels.shape)
# print(labels_train.shape)
accuracy = np.mean(predicted_labels == labels_train)
train_accuracies.append(accuracy)
print(f'Epoch {epoch + 1}/{num_epoch}, Loss: {loss:.3f}, Train Accuracy: {accuracy:.2f}')
return w1, b1, w2, b2, train_accuracies
```
#### 14-
```def test_mlp(w1, b1, w2, b2, data_test, labels_test):
# Compute accuracy
predictions = forward(w1, b1, w2, b2, data_test)
predicted_labels = np.argmax(predictions, axis=1)
print(predicted_labels)
test_accuracy = np.mean(predicted_labels == labels_test)
print(f'Train Accuracy: {test_accuracy:.2f}')
return test_accuracy
```
#### 15-
```
def run_mlp_training(data_train, labels_train, data_test, labels_test, d_h,learning_rate, num_epoch):
d_in = data_train.shape[1]
d_out = 10 #we can hard code it here or len(np.unique(label_train))
#Random initialisation of weights
w1 = np.random.randn(d_in, d_h)
b1 = np.random.randn(1, d_h)
w2 = np.random.randn(d_h, d_out)
b2 = np.random.randn(1, d_out)
# Train MLP
w1, b1, w2, b2, train_accuracies = train_mlp(w1, b1, w2, b2, data_train, labels_train, learning_rate, num_epoch)
# Test MLP
test_accuracy = test_mlp(w1, b1, w2, b2, data_test, labels_test)
return train_accuracies, test_accuracy
```
\ No newline at end of file
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment