KneighborsClassifier giving different euclidean value than linalg.norm and scipy.spatial.distance.euclidean2019 Community Moderator ElectionHow can the Euclidean distance be calculated with NumPy?What is the difference between @staticmethod and @classmethod?Difference between append vs. extend list methods in PythonHow do I sort a dictionary by value?Difference between __str__ and __repr__?Parsing values from a JSON file?How to access environment variable values?Why is reading lines from stdin much slower in C++ than Python?Euclidean distance two pixels, each belonging to different imagesHow to use Scipy's Kd-tree function to speed up K-Nearest Neighbors (KNN)Euclidean distance, different results between Scipy, pure Python, and Java

Pronounciation of the combination "st" in spanish accents

Is this an example of a Neapolitan chord?

What can I do if I am asked to learn different programming languages very frequently?

Does multi-classing into Fighter give you heavy armor proficiency?

Wrapping homogeneous Python objects

What (if any) is the reason to buy in small local stores?

How are passwords stolen from companies if they only store hashes?

Calculate the frequency of characters in a string

Why is there so much iron?

Writing in a Christian voice

HP P840 HDD RAID 5 many strange drive failures

In the 1924 version of The Thief of Bagdad, no character is named, right?

The average age of first marriage in Russia

How do hiring committees for research positions view getting "scooped"?

How to define limit operations in general topological spaces? Are nets able to do this?

Am I eligible for the Eurail Youth pass? I am 27.5 years old

Bash - pair each line of file

Geography in 3D perspective

Suggestions on how to spend Shaabath (constructively) alone

Is honey really a supersaturated solution? Does heating to un-crystalize redissolve it or melt it?

Is it insecure to send a password in a `curl` command?

Generic TVP tradeoffs?

Describing a chess game in a novel

Turning a hard to access nut?



KneighborsClassifier giving different euclidean value than linalg.norm and scipy.spatial.distance.euclidean



2019 Community Moderator ElectionHow can the Euclidean distance be calculated with NumPy?What is the difference between @staticmethod and @classmethod?Difference between append vs. extend list methods in PythonHow do I sort a dictionary by value?Difference between __str__ and __repr__?Parsing values from a JSON file?How to access environment variable values?Why is reading lines from stdin much slower in C++ than Python?Euclidean distance two pixels, each belonging to different imagesHow to use Scipy's Kd-tree function to speed up K-Nearest Neighbors (KNN)Euclidean distance, different results between Scipy, pure Python, and Java










0















I am trying to implement a knearest neighbors classifier on the mnist dataset.

I tried to check my results by comparing with the Scipy KNeighborsClassifier



For verification I am using the first 6 samples in the training set and finding the 6 nearest neighbors of the first sample in the training set.

The distance that I calculate does not match with the distance given by the KNeighborsClassifier library.

I am not able to figure out why are my values different.



I have referred to this question for getting the euclidean distance.



My code:



from mlxtend.data import loadlocal_mnist
import numpy as np
from scipy.spatial import distance

train, train_label = loadlocal_mnist(
images_path='train-images.idx3-ubyte',
labels_path='train-labels.idx1-ubyte')
train_label = train_label.reshape(-1, 1)

train = train[:6, :]
train_label = train_label[:6, :]
# print(train_label)

test = train.copy()
test_label = train_label.copy()

test = test[:1, :]
test_label = test_label[:1, :]

for test_idx, test_row in enumerate(test):
for train_idx, train_row in enumerate(train):
d1 = np.linalg.norm(train_row - test_row)
d2 = distance.euclidean(train_row, test_row)
d3 = (((train_row - test_row)**2).sum())**0.5
d4 = np.dot(train_row - test_row, train_row - test_row)**0.5
print(train_idx, d1, d2, d3, d4)


Test set is only the first row of train set



The output for the above is:



0 0.0 0.0 0.0 0.0
1 2618.6771469579826 2618.6771469579826 140.3923074815711 15.937377450509228
2 2372.0210791643485 2372.0210791643485 134.29817571359635 10.770329614269007
3 2139.966354875702 2139.966354875702 122.37646832622684 11.313708498984761
4 2485.1432554281455 2485.1432554281455 135.5322839769182 13.892443989449804
5 2582.292392429641 2582.292392429641 144.69968901141425 14.212670403551895


And this is the KNeighborsClassifier code i compare with:



neigh = KNeighborsClassifier(n_neighbors=6)
neigh.fit(train, train_label)
closest = neigh.kneighbors(test[0].reshape(1, -1))
print(closest)


Output:



(array([[ 0. , 2387.11164381, 2554.81975881, 2582.29239243,
2672.46721215, 2773.14911247]]), array([[0, 1, 3, 5, 4, 2]], dtype=int64))


I am trying to calculate the euclidean distance between the data points to find the nearest neighbors. d1, d2, d3, d4 are 4 different approaches I found from the question linked above and the output are their specific values.

But the distance value I get from the KNeighborsClassifier is different from all of these which also uses euclidean distance as given in the documentation. Why is that happening?










share|improve this question
























  • Please make your question reproducible (should not be that hard with MNIST); what is train & test, and how exactly they are built?

    – desertnaut
    Mar 7 at 17:12











  • @desertnaut Added code for train and test. Thanks

    – Otaku
    Mar 7 at 21:28











  • Good. What do d3 & d4 have to do with the question? They seem irrelevant...

    – desertnaut
    Mar 7 at 21:46











  • @desertnaut Added more details explaining that

    – Otaku
    Mar 7 at 23:02















0















I am trying to implement a knearest neighbors classifier on the mnist dataset.

I tried to check my results by comparing with the Scipy KNeighborsClassifier



For verification I am using the first 6 samples in the training set and finding the 6 nearest neighbors of the first sample in the training set.

The distance that I calculate does not match with the distance given by the KNeighborsClassifier library.

I am not able to figure out why are my values different.



I have referred to this question for getting the euclidean distance.



My code:



from mlxtend.data import loadlocal_mnist
import numpy as np
from scipy.spatial import distance

train, train_label = loadlocal_mnist(
images_path='train-images.idx3-ubyte',
labels_path='train-labels.idx1-ubyte')
train_label = train_label.reshape(-1, 1)

train = train[:6, :]
train_label = train_label[:6, :]
# print(train_label)

test = train.copy()
test_label = train_label.copy()

test = test[:1, :]
test_label = test_label[:1, :]

for test_idx, test_row in enumerate(test):
for train_idx, train_row in enumerate(train):
d1 = np.linalg.norm(train_row - test_row)
d2 = distance.euclidean(train_row, test_row)
d3 = (((train_row - test_row)**2).sum())**0.5
d4 = np.dot(train_row - test_row, train_row - test_row)**0.5
print(train_idx, d1, d2, d3, d4)


Test set is only the first row of train set



The output for the above is:



0 0.0 0.0 0.0 0.0
1 2618.6771469579826 2618.6771469579826 140.3923074815711 15.937377450509228
2 2372.0210791643485 2372.0210791643485 134.29817571359635 10.770329614269007
3 2139.966354875702 2139.966354875702 122.37646832622684 11.313708498984761
4 2485.1432554281455 2485.1432554281455 135.5322839769182 13.892443989449804
5 2582.292392429641 2582.292392429641 144.69968901141425 14.212670403551895


And this is the KNeighborsClassifier code i compare with:



neigh = KNeighborsClassifier(n_neighbors=6)
neigh.fit(train, train_label)
closest = neigh.kneighbors(test[0].reshape(1, -1))
print(closest)


Output:



(array([[ 0. , 2387.11164381, 2554.81975881, 2582.29239243,
2672.46721215, 2773.14911247]]), array([[0, 1, 3, 5, 4, 2]], dtype=int64))


I am trying to calculate the euclidean distance between the data points to find the nearest neighbors. d1, d2, d3, d4 are 4 different approaches I found from the question linked above and the output are their specific values.

But the distance value I get from the KNeighborsClassifier is different from all of these which also uses euclidean distance as given in the documentation. Why is that happening?










share|improve this question
























  • Please make your question reproducible (should not be that hard with MNIST); what is train & test, and how exactly they are built?

    – desertnaut
    Mar 7 at 17:12











  • @desertnaut Added code for train and test. Thanks

    – Otaku
    Mar 7 at 21:28











  • Good. What do d3 & d4 have to do with the question? They seem irrelevant...

    – desertnaut
    Mar 7 at 21:46











  • @desertnaut Added more details explaining that

    – Otaku
    Mar 7 at 23:02













0












0








0








I am trying to implement a knearest neighbors classifier on the mnist dataset.

I tried to check my results by comparing with the Scipy KNeighborsClassifier



For verification I am using the first 6 samples in the training set and finding the 6 nearest neighbors of the first sample in the training set.

The distance that I calculate does not match with the distance given by the KNeighborsClassifier library.

I am not able to figure out why are my values different.



I have referred to this question for getting the euclidean distance.



My code:



from mlxtend.data import loadlocal_mnist
import numpy as np
from scipy.spatial import distance

train, train_label = loadlocal_mnist(
images_path='train-images.idx3-ubyte',
labels_path='train-labels.idx1-ubyte')
train_label = train_label.reshape(-1, 1)

train = train[:6, :]
train_label = train_label[:6, :]
# print(train_label)

test = train.copy()
test_label = train_label.copy()

test = test[:1, :]
test_label = test_label[:1, :]

for test_idx, test_row in enumerate(test):
for train_idx, train_row in enumerate(train):
d1 = np.linalg.norm(train_row - test_row)
d2 = distance.euclidean(train_row, test_row)
d3 = (((train_row - test_row)**2).sum())**0.5
d4 = np.dot(train_row - test_row, train_row - test_row)**0.5
print(train_idx, d1, d2, d3, d4)


Test set is only the first row of train set



The output for the above is:



0 0.0 0.0 0.0 0.0
1 2618.6771469579826 2618.6771469579826 140.3923074815711 15.937377450509228
2 2372.0210791643485 2372.0210791643485 134.29817571359635 10.770329614269007
3 2139.966354875702 2139.966354875702 122.37646832622684 11.313708498984761
4 2485.1432554281455 2485.1432554281455 135.5322839769182 13.892443989449804
5 2582.292392429641 2582.292392429641 144.69968901141425 14.212670403551895


And this is the KNeighborsClassifier code i compare with:



neigh = KNeighborsClassifier(n_neighbors=6)
neigh.fit(train, train_label)
closest = neigh.kneighbors(test[0].reshape(1, -1))
print(closest)


Output:



(array([[ 0. , 2387.11164381, 2554.81975881, 2582.29239243,
2672.46721215, 2773.14911247]]), array([[0, 1, 3, 5, 4, 2]], dtype=int64))


I am trying to calculate the euclidean distance between the data points to find the nearest neighbors. d1, d2, d3, d4 are 4 different approaches I found from the question linked above and the output are their specific values.

But the distance value I get from the KNeighborsClassifier is different from all of these which also uses euclidean distance as given in the documentation. Why is that happening?










share|improve this question
















I am trying to implement a knearest neighbors classifier on the mnist dataset.

I tried to check my results by comparing with the Scipy KNeighborsClassifier



For verification I am using the first 6 samples in the training set and finding the 6 nearest neighbors of the first sample in the training set.

The distance that I calculate does not match with the distance given by the KNeighborsClassifier library.

I am not able to figure out why are my values different.



I have referred to this question for getting the euclidean distance.



My code:



from mlxtend.data import loadlocal_mnist
import numpy as np
from scipy.spatial import distance

train, train_label = loadlocal_mnist(
images_path='train-images.idx3-ubyte',
labels_path='train-labels.idx1-ubyte')
train_label = train_label.reshape(-1, 1)

train = train[:6, :]
train_label = train_label[:6, :]
# print(train_label)

test = train.copy()
test_label = train_label.copy()

test = test[:1, :]
test_label = test_label[:1, :]

for test_idx, test_row in enumerate(test):
for train_idx, train_row in enumerate(train):
d1 = np.linalg.norm(train_row - test_row)
d2 = distance.euclidean(train_row, test_row)
d3 = (((train_row - test_row)**2).sum())**0.5
d4 = np.dot(train_row - test_row, train_row - test_row)**0.5
print(train_idx, d1, d2, d3, d4)


Test set is only the first row of train set



The output for the above is:



0 0.0 0.0 0.0 0.0
1 2618.6771469579826 2618.6771469579826 140.3923074815711 15.937377450509228
2 2372.0210791643485 2372.0210791643485 134.29817571359635 10.770329614269007
3 2139.966354875702 2139.966354875702 122.37646832622684 11.313708498984761
4 2485.1432554281455 2485.1432554281455 135.5322839769182 13.892443989449804
5 2582.292392429641 2582.292392429641 144.69968901141425 14.212670403551895


And this is the KNeighborsClassifier code i compare with:



neigh = KNeighborsClassifier(n_neighbors=6)
neigh.fit(train, train_label)
closest = neigh.kneighbors(test[0].reshape(1, -1))
print(closest)


Output:



(array([[ 0. , 2387.11164381, 2554.81975881, 2582.29239243,
2672.46721215, 2773.14911247]]), array([[0, 1, 3, 5, 4, 2]], dtype=int64))


I am trying to calculate the euclidean distance between the data points to find the nearest neighbors. d1, d2, d3, d4 are 4 different approaches I found from the question linked above and the output are their specific values.

But the distance value I get from the KNeighborsClassifier is different from all of these which also uses euclidean distance as given in the documentation. Why is that happening?







python machine-learning scikit-learn scipy knn






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 7 at 23:02







Otaku

















asked Mar 7 at 17:05









OtakuOtaku

147313




147313












  • Please make your question reproducible (should not be that hard with MNIST); what is train & test, and how exactly they are built?

    – desertnaut
    Mar 7 at 17:12











  • @desertnaut Added code for train and test. Thanks

    – Otaku
    Mar 7 at 21:28











  • Good. What do d3 & d4 have to do with the question? They seem irrelevant...

    – desertnaut
    Mar 7 at 21:46











  • @desertnaut Added more details explaining that

    – Otaku
    Mar 7 at 23:02

















  • Please make your question reproducible (should not be that hard with MNIST); what is train & test, and how exactly they are built?

    – desertnaut
    Mar 7 at 17:12











  • @desertnaut Added code for train and test. Thanks

    – Otaku
    Mar 7 at 21:28











  • Good. What do d3 & d4 have to do with the question? They seem irrelevant...

    – desertnaut
    Mar 7 at 21:46











  • @desertnaut Added more details explaining that

    – Otaku
    Mar 7 at 23:02
















Please make your question reproducible (should not be that hard with MNIST); what is train & test, and how exactly they are built?

– desertnaut
Mar 7 at 17:12





Please make your question reproducible (should not be that hard with MNIST); what is train & test, and how exactly they are built?

– desertnaut
Mar 7 at 17:12













@desertnaut Added code for train and test. Thanks

– Otaku
Mar 7 at 21:28





@desertnaut Added code for train and test. Thanks

– Otaku
Mar 7 at 21:28













Good. What do d3 & d4 have to do with the question? They seem irrelevant...

– desertnaut
Mar 7 at 21:46





Good. What do d3 & d4 have to do with the question? They seem irrelevant...

– desertnaut
Mar 7 at 21:46













@desertnaut Added more details explaining that

– Otaku
Mar 7 at 23:02





@desertnaut Added more details explaining that

– Otaku
Mar 7 at 23:02












2 Answers
2






active

oldest

votes


















1














OK, here is a hint (have no time currently to look it further, and it may be possibly helpful):



There is certainly something very wrong in the first way you compute the distances (possibly in the way you are slicing the initial data); to see this, let's modify your loops to:



for test_idx, test_row in enumerate(test):
for train_idx, train_row in enumerate(train):
d1 = np.linalg.norm(train_row - test_row)
d2 = np.linalg.norm(test_row - train_row)
d3 = distance.euclidean(train_row, test_row)
d4 = distance.euclidean(test_row, train_row)
print(train_idx, d1, d2, d3, d4)


Here, clearly we should have d1 = d2 = d3 = d4; but the results are:



0 0.0 0.0 0.0 0.0
1 2618.6771469579826 2213.268623552053 2618.6771469579826 2213.268623552053
2 2372.0210791643485 2547.0901044132693 2372.0210791643485 2547.0901044132693
3 2139.966354875702 2374.7201940439213 2139.966354875702 2374.7201940439213
4 2485.1432554281455 2467.6727903026367 2485.1432554281455 2467.6727903026367
5 2582.292392429641 2449.1912951013032 2582.292392429641 2449.1912951013032


i.e. it is d1 = d3 and d2 = d4, but these two quantities are different between them; this should certainly not happen, as the distance is a symmetric function and the order of arguments should play no role:



a = np.array((1, 2, 3))
b = np.array((4, 5, 6))
distance.euclidean(a, b)
# 5.196152422706632
distance.euclidean(b, a)
# 5.196152422706632
np.linalg.norm(a-b)
# 5.196152422706632
np.linalg.norm(b-a)
# 5.196152422706632


Food for thought - hope it helps...






share|improve this answer

























  • yes that makes sense but still not able to find the source of this bug

    – Otaku
    Mar 8 at 1:04


















0














I am not sure what was causing this but converting the data from the np.array to a list and then back to an np.array apparently fixed the issue.



train = np.array(train.tolist())
test = np.array(test.tolist())


Thanks to @desertnaut for giving the idea that the issue could be in the slicing of the data but I still can't say for sure what the cause of the issue was.






share|improve this answer






















    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55049298%2fkneighborsclassifier-giving-different-euclidean-value-than-linalg-norm-and-scipy%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    1














    OK, here is a hint (have no time currently to look it further, and it may be possibly helpful):



    There is certainly something very wrong in the first way you compute the distances (possibly in the way you are slicing the initial data); to see this, let's modify your loops to:



    for test_idx, test_row in enumerate(test):
    for train_idx, train_row in enumerate(train):
    d1 = np.linalg.norm(train_row - test_row)
    d2 = np.linalg.norm(test_row - train_row)
    d3 = distance.euclidean(train_row, test_row)
    d4 = distance.euclidean(test_row, train_row)
    print(train_idx, d1, d2, d3, d4)


    Here, clearly we should have d1 = d2 = d3 = d4; but the results are:



    0 0.0 0.0 0.0 0.0
    1 2618.6771469579826 2213.268623552053 2618.6771469579826 2213.268623552053
    2 2372.0210791643485 2547.0901044132693 2372.0210791643485 2547.0901044132693
    3 2139.966354875702 2374.7201940439213 2139.966354875702 2374.7201940439213
    4 2485.1432554281455 2467.6727903026367 2485.1432554281455 2467.6727903026367
    5 2582.292392429641 2449.1912951013032 2582.292392429641 2449.1912951013032


    i.e. it is d1 = d3 and d2 = d4, but these two quantities are different between them; this should certainly not happen, as the distance is a symmetric function and the order of arguments should play no role:



    a = np.array((1, 2, 3))
    b = np.array((4, 5, 6))
    distance.euclidean(a, b)
    # 5.196152422706632
    distance.euclidean(b, a)
    # 5.196152422706632
    np.linalg.norm(a-b)
    # 5.196152422706632
    np.linalg.norm(b-a)
    # 5.196152422706632


    Food for thought - hope it helps...






    share|improve this answer

























    • yes that makes sense but still not able to find the source of this bug

      – Otaku
      Mar 8 at 1:04















    1














    OK, here is a hint (have no time currently to look it further, and it may be possibly helpful):



    There is certainly something very wrong in the first way you compute the distances (possibly in the way you are slicing the initial data); to see this, let's modify your loops to:



    for test_idx, test_row in enumerate(test):
    for train_idx, train_row in enumerate(train):
    d1 = np.linalg.norm(train_row - test_row)
    d2 = np.linalg.norm(test_row - train_row)
    d3 = distance.euclidean(train_row, test_row)
    d4 = distance.euclidean(test_row, train_row)
    print(train_idx, d1, d2, d3, d4)


    Here, clearly we should have d1 = d2 = d3 = d4; but the results are:



    0 0.0 0.0 0.0 0.0
    1 2618.6771469579826 2213.268623552053 2618.6771469579826 2213.268623552053
    2 2372.0210791643485 2547.0901044132693 2372.0210791643485 2547.0901044132693
    3 2139.966354875702 2374.7201940439213 2139.966354875702 2374.7201940439213
    4 2485.1432554281455 2467.6727903026367 2485.1432554281455 2467.6727903026367
    5 2582.292392429641 2449.1912951013032 2582.292392429641 2449.1912951013032


    i.e. it is d1 = d3 and d2 = d4, but these two quantities are different between them; this should certainly not happen, as the distance is a symmetric function and the order of arguments should play no role:



    a = np.array((1, 2, 3))
    b = np.array((4, 5, 6))
    distance.euclidean(a, b)
    # 5.196152422706632
    distance.euclidean(b, a)
    # 5.196152422706632
    np.linalg.norm(a-b)
    # 5.196152422706632
    np.linalg.norm(b-a)
    # 5.196152422706632


    Food for thought - hope it helps...






    share|improve this answer

























    • yes that makes sense but still not able to find the source of this bug

      – Otaku
      Mar 8 at 1:04













    1












    1








    1







    OK, here is a hint (have no time currently to look it further, and it may be possibly helpful):



    There is certainly something very wrong in the first way you compute the distances (possibly in the way you are slicing the initial data); to see this, let's modify your loops to:



    for test_idx, test_row in enumerate(test):
    for train_idx, train_row in enumerate(train):
    d1 = np.linalg.norm(train_row - test_row)
    d2 = np.linalg.norm(test_row - train_row)
    d3 = distance.euclidean(train_row, test_row)
    d4 = distance.euclidean(test_row, train_row)
    print(train_idx, d1, d2, d3, d4)


    Here, clearly we should have d1 = d2 = d3 = d4; but the results are:



    0 0.0 0.0 0.0 0.0
    1 2618.6771469579826 2213.268623552053 2618.6771469579826 2213.268623552053
    2 2372.0210791643485 2547.0901044132693 2372.0210791643485 2547.0901044132693
    3 2139.966354875702 2374.7201940439213 2139.966354875702 2374.7201940439213
    4 2485.1432554281455 2467.6727903026367 2485.1432554281455 2467.6727903026367
    5 2582.292392429641 2449.1912951013032 2582.292392429641 2449.1912951013032


    i.e. it is d1 = d3 and d2 = d4, but these two quantities are different between them; this should certainly not happen, as the distance is a symmetric function and the order of arguments should play no role:



    a = np.array((1, 2, 3))
    b = np.array((4, 5, 6))
    distance.euclidean(a, b)
    # 5.196152422706632
    distance.euclidean(b, a)
    # 5.196152422706632
    np.linalg.norm(a-b)
    # 5.196152422706632
    np.linalg.norm(b-a)
    # 5.196152422706632


    Food for thought - hope it helps...






    share|improve this answer















    OK, here is a hint (have no time currently to look it further, and it may be possibly helpful):



    There is certainly something very wrong in the first way you compute the distances (possibly in the way you are slicing the initial data); to see this, let's modify your loops to:



    for test_idx, test_row in enumerate(test):
    for train_idx, train_row in enumerate(train):
    d1 = np.linalg.norm(train_row - test_row)
    d2 = np.linalg.norm(test_row - train_row)
    d3 = distance.euclidean(train_row, test_row)
    d4 = distance.euclidean(test_row, train_row)
    print(train_idx, d1, d2, d3, d4)


    Here, clearly we should have d1 = d2 = d3 = d4; but the results are:



    0 0.0 0.0 0.0 0.0
    1 2618.6771469579826 2213.268623552053 2618.6771469579826 2213.268623552053
    2 2372.0210791643485 2547.0901044132693 2372.0210791643485 2547.0901044132693
    3 2139.966354875702 2374.7201940439213 2139.966354875702 2374.7201940439213
    4 2485.1432554281455 2467.6727903026367 2485.1432554281455 2467.6727903026367
    5 2582.292392429641 2449.1912951013032 2582.292392429641 2449.1912951013032


    i.e. it is d1 = d3 and d2 = d4, but these two quantities are different between them; this should certainly not happen, as the distance is a symmetric function and the order of arguments should play no role:



    a = np.array((1, 2, 3))
    b = np.array((4, 5, 6))
    distance.euclidean(a, b)
    # 5.196152422706632
    distance.euclidean(b, a)
    # 5.196152422706632
    np.linalg.norm(a-b)
    # 5.196152422706632
    np.linalg.norm(b-a)
    # 5.196152422706632


    Food for thought - hope it helps...







    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited Mar 7 at 23:50

























    answered Mar 7 at 23:45









    desertnautdesertnaut

    19.6k74076




    19.6k74076












    • yes that makes sense but still not able to find the source of this bug

      – Otaku
      Mar 8 at 1:04

















    • yes that makes sense but still not able to find the source of this bug

      – Otaku
      Mar 8 at 1:04
















    yes that makes sense but still not able to find the source of this bug

    – Otaku
    Mar 8 at 1:04





    yes that makes sense but still not able to find the source of this bug

    – Otaku
    Mar 8 at 1:04













    0














    I am not sure what was causing this but converting the data from the np.array to a list and then back to an np.array apparently fixed the issue.



    train = np.array(train.tolist())
    test = np.array(test.tolist())


    Thanks to @desertnaut for giving the idea that the issue could be in the slicing of the data but I still can't say for sure what the cause of the issue was.






    share|improve this answer



























      0














      I am not sure what was causing this but converting the data from the np.array to a list and then back to an np.array apparently fixed the issue.



      train = np.array(train.tolist())
      test = np.array(test.tolist())


      Thanks to @desertnaut for giving the idea that the issue could be in the slicing of the data but I still can't say for sure what the cause of the issue was.






      share|improve this answer

























        0












        0








        0







        I am not sure what was causing this but converting the data from the np.array to a list and then back to an np.array apparently fixed the issue.



        train = np.array(train.tolist())
        test = np.array(test.tolist())


        Thanks to @desertnaut for giving the idea that the issue could be in the slicing of the data but I still can't say for sure what the cause of the issue was.






        share|improve this answer













        I am not sure what was causing this but converting the data from the np.array to a list and then back to an np.array apparently fixed the issue.



        train = np.array(train.tolist())
        test = np.array(test.tolist())


        Thanks to @desertnaut for giving the idea that the issue could be in the slicing of the data but I still can't say for sure what the cause of the issue was.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Mar 8 at 1:38









        OtakuOtaku

        147313




        147313



























            draft saved

            draft discarded
















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55049298%2fkneighborsclassifier-giving-different-euclidean-value-than-linalg-norm-and-scipy%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Thal And Out Agency railway station See also References External links Navigation menuOfficial Web Site of Pakistan RailwaysArchivedOfficial Web Site of Pakistan Railwayseeexpanding ite

            Understanding generators in Python2019 Community Moderator ElectionGenerator function not working pythonFor loop not executing two timesGenerators - Printing generated valuesWhy can a python generator only be used once?What exactly do generators do?What does the “yield” keyword do?What does “list comprehension” mean? How does it work and how can I use it?sklearn Kfold acces single fold instead of for loopIs a generator the callable? Which is the generator?Apply Border To Range Of Cells Using OpenpyxlCalling an external command in PythonWhat are metaclasses in Python?What is the difference between @staticmethod and @classmethod?Finding the index of an item given a list containing it in PythonDifference between append vs. extend list methods in PythonHow can I safely create a nested directory in Python?Does Python have a ternary conditional operator?Understanding slice notationUnderstanding Python super() with __init__() methodsDoes Python have a string 'contains' substring method?

            How can I change the color of pagination dots of UIPageControl?How to change UIPageControl dotsIs there a way to change page indicator dots colorCustomize dot with image of UIPageControl at index 0 of UIPageControlNo visible @interface for 'NSObject<PageControlDelegate>' declares the selector 'pageControlPageDidChange:'How to change the color of pagination dots in UIPageControl with a different color per pagepagecontrol indicator custom image instead of DefaultChanging the colour of UIPageControl dots in MonoTouchpagecontrol selectable page visibility color?Alternative way to load ViewControllers on a UIPageControlHow to set only layer.border-color for UIpage control dots in swiftHow can I develop for iPhone using a Windows development machine?How to change the name of an iOS app?UITableView - change section header coloruipagecontrol indicator(dot)issueCustom UIPageControl dots color not changingchange the interspace between UIPageControl dotsHow to change Status Bar text color in iOSHow can I change image tintColor in iOS and WatchKitUIPageControl dots with larger space in between each dotsHow to change the color of pagination dots in UIPageControl with a different color per page