Skip to content
GitLab
Explore
Sign in
Primary navigation
Search or go to…
Project
I
Images classification
Manage
Activity
Members
Labels
Plan
Issues
Issue boards
Milestones
Wiki
Code
Merge requests
Repository
Branches
Commits
Tags
Repository graph
Compare revisions
Snippets
Deploy
Releases
Package registry
Model registry
Operate
Terraform modules
Monitor
Incidents
Analyze
Value stream analytics
Contributor analytics
Repository analytics
Model experiments
Help
Help
Support
GitLab documentation
Compare GitLab plans
GitLab community forum
Contribute to GitLab
Provide feedback
Terms and privacy
Keyboard shortcuts
?
Snippets
Groups
Projects
Show more breadcrumbs
Saidi Aya
Images classification
Commits
be1fe1ce
Commit
be1fe1ce
authored
2 years ago
by
Saidi Aya
Browse files
Options
Downloads
Patches
Plain Diff
Update knn.py
parent
08be5a9b
No related branches found
No related tags found
No related merge requests found
Changes
1
Show whitespace changes
Inline
Side-by-side
Showing
1 changed file
knn.py
+25
-2
25 additions, 2 deletions
knn.py
with
25 additions
and
2 deletions
knn.py
+
25
−
2
View file @
be1fe1ce
#Libraries
import
numpy
as
np
import
torch
#Functions
def
distance_matrix
(
Y
,
X
):
#This function takes as parameters two matrices X and Y
dists
=
np
.
sqrt
(
np
.
sum
(
-
2
*
np
.
multiply
(
X
,
Y
)
+
np
.
multiply
(
Y
,
Y
)
+
np
.
multiply
(
X
,
X
)))
...
...
@@ -5,4 +9,23 @@ def distance_matrix(Y , X):
return
dists
def
knn_predict
(
dists
,
labels_train
,
k
):
#This function takes as parameters: dists (from above), labels_train, and k the number of neighbors
labels_test_pred
=
torch
.
zeros
(
len
(
data_test
),
dtype
=
torch
.
int64
)
for
i
in
range
(
dists
.
shape
[
1
]):
# Find index of k lowest values
x
=
torch
.
topk
(
dists
[:,
i
],
k
,
largest
=
False
).
indices
# Index the labels according to x
k_lowest_labels
=
labels_train
[
x
]
# y_test_pred[i] = the most frequent occuring index
labels_test_pred
[
i
]
=
torch
.
argmax
(
torch
.
bincount
(
k_lowest_labels
))
return
labels_test_pred
def
evaluate_knn
(
data_train
,
labels_train
,
data_test
,
labels_test
,
k
):
labels_test_pred
=
knn_predict
(
distance_matrix
(
data_train
,
data_test
),
labels_train
,
k
)
num_samples
=
data_test
.
shape
[
0
]
num_correct
=
(
labels_test
==
labels_test_pred
).
sum
().
item
()
accuracy
=
100
*
num_correct
/
num_samples
return
accuracy
This diff is collapsed.
Click to expand it.
Preview
0%
Loading
Try again
or
attach a new file
.
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Save comment
Cancel
Please
register
or
sign in
to comment