Skip to content
GitLab
Explore
Sign in
Primary navigation
Search or go to…
Project
I
Image 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
Community forum
Contribute to GitLab
Provide feedback
Terms and privacy
Keyboard shortcuts
?
Snippets
Groups
Projects
Show more breadcrumbs
Brudy Saintespes Baptiste
Image classification
Commits
2418acfd
Commit
2418acfd
authored
1 year ago
by
BaptisteBrd
Browse files
Options
Downloads
Patches
Plain Diff
knn save
parent
1c34f86e
Branches
Branches containing commit
No related tags found
No related merge requests found
Changes
1
Show whitespace changes
Inline
Side-by-side
Showing
1 changed file
knn.py
+29
-5
29 additions, 5 deletions
knn.py
with
29 additions
and
5 deletions
knn.py
+
29
−
5
View file @
2418acfd
import
numpy
as
np
def
distance_matrix
(
a
,
b
):
s
x
=
np
.
sum
(
a
**
2
,
axis
=
1
,
keepdims
=
True
)
s
y
=
np
.
sum
(
b
**
2
,
axis
=
1
,
keepdims
=
True
)
dist
s
=
np
.
sqrt
(
-
2
*
a
.
dot
(
b
.
T
)
+
s
x
+
sy
.
T
)
return
dist
s
s
um_a
=
np
.
sum
(
a
**
2
,
axis
=
1
,
keepdims
=
True
)
s
um_b
=
np
.
sum
(
b
**
2
,
axis
=
1
,
keepdims
=
True
)
dist
=
np
.
sqrt
(
-
2
*
a
.
dot
(
b
.
T
)
+
s
um_a
+
sum_b
)
return
dist
#def knn_predict(dists, labels_train, k):
#
#
def
knn_predict
(
dists
,
labels_train
,
k
):
predicted_labels
=
[]
# For every image in the test set
for
i
in
range
(
len
(
dists
)):
# Initialize an array to store the neighbors
classes
=
[
0
]
*
10
# indexes of the closest neighbors
indexes_closest_nb
=
np
.
argsort
(
dists
[
i
])[:
k
]
for
index
in
indexes_closest_nb
:
#find the labels of the training batch associated with the closest indexes
classes
[
labels_train
[
index
]]
+=
1
#The class with the highest neighbors is added to the predicted labels
predicted_labels
.
append
(
np
.
argmax
(
classes
))
return
(
np
.
array
(
predicted_labels
))
def
evaluate_knn
(
data_train
,
labels_train
,
data_test
,
labels_test
,
k
):
if
__name__
==
"
__main__
"
:
if
__name__
==
"
__main__
"
:
a1
=
np
.
array
([[
0
,
0
,
1
],[
0
,
0
,
0
],[
1
,
1
,
2
]])
b1
=
np
.
array
([[
1
,
3
,
1
],
[
1
,
1
,
4
],
[
1
,
5
,
1
]])
print
(
distance_matrix
(
a1
,
b1
))
\ No newline at end of file
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