KNN algorithm: 'int' object is not subscriptable2019 Community Moderator ElectionConvert hex string to int in PythonHow do I parse a string to a float or int in Python?How to know if an object has an attribute in PythonWhat is the meaning of a single and a double underscore before an object name?In Python, how do I determine if an object is iterable?Determine the type of an object?null object in Python?Python class inherits objectMaximum and Minimum values for intsHow do I fix the EOL Syntax error in this programm

A vote on the Brexit backstop

Help! My Character is too much for her story!

Who has more? Ireland or Iceland?

Short story about an infectious indestructible metal bar?

How to make sure I'm assertive enough in contact with subordinates?

A running toilet that stops itself

How can I have x-axis ticks that show ticks scaled in powers of ten?

Why do we call complex numbers “numbers” but we don’t consider 2-vectors numbers?

Do I need a return ticket to Canada if I'm a Japanese National?

Is it a Cyclops number? "Nobody" knows!

How does a sound wave propagate?

ESPP--any reason not to go all in?

How to write a chaotic neutral protagonist and prevent my readers from thinking they are evil?

Did Amazon pay $0 in taxes last year?

What does it take to become a wilderness skills guide as a business?

Should I file my taxes? No income, unemployed, but paid 2k in student loan interest

Inorganic chemistry handbook with reaction lists

Too soon for a plot twist?

Can Witch Sight see through Mirror Image?

Does the US political system, in principle, allow for a no-party system?

Sort array by month and year

I've given my players a lot of magic items. Is it reasonable for me to give them harder encounters?

Short story about cities being connected by a conveyor belt

Is it appropriate to ask a former professor to order a library book for me through ILL?



KNN algorithm: 'int' object is not subscriptable



2019 Community Moderator ElectionConvert hex string to int in PythonHow do I parse a string to a float or int in Python?How to know if an object has an attribute in PythonWhat is the meaning of a single and a double underscore before an object name?In Python, how do I determine if an object is iterable?Determine the type of an object?null object in Python?Python class inherits objectMaximum and Minimum values for intsHow do I fix the EOL Syntax error in this programm










0















i have not been using python for some time and having trouble finding the solution to this problem.
I tried to change the equation for euclidean distance function but it did not do any good. Maybe i am blind to see the solution to my problem.



Here is my code:



from math import sqrt
import csv
from random import shuffle
import numpy as np
import numpy
import matplotlib.pyplot as plt
import operator
import math


iris = datasets.load_iris()

X = iris.data
y = iris.target



def euclideanDistance(id1, id2):
for x in range(len(id1)-1):
dist = np.sqrt(np.sum((int(id2[x]) - int(id1[x]))**2))
return dist

data1 = [2, 2, 2, 'a']
data2 = [4, 4, 4, 'b']
distance = euclideanDistance(data1, data2)
print(distance)

def mykNN(X, y, x_):
distance = []
neighbour = []

for i in range(len(X)):
d = euclideanDistance(X[i], x_ )
distance.append((X[i], d))
distance.sort(key=operator.itemgetter(1))

for r in range(k):
options.append(distance[r][0])
options = neighbour
return neighbour

k=3

y_ = mykNN(X, y,k)
print(y_)


no matter what how i change my function it comes up with this error.



---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-85-2a5bfc4a796d> in <module>
42 k=3
43
---> 44 y_ = mykNN(X, y,k)
45 print(y_)
46

<ipython-input-85-2a5bfc4a796d> in mykNN(X, y, x_)
31
32 for i in range(len(X)):
---> 33 d = euclideanDistance(X[i], x_ )
34 distance.append((X[i], d))
35 distance.sort(key=operator.itemgetter(1))

<ipython-input-85-2a5bfc4a796d> in euclideanDistance(id1, id2)
18 def euclideanDistance(id1, id2):
19 for x in range(len(id1)-1):
---> 20 dist = np.sqrt(np.sum((int(id2[x]) - int(id1[x]))**2))
21 return dist
22

TypeError: 'int' object is not subscriptable


I would appreciate your response as this has been bothering me.



Thank you.










share|improve this question







New contributor




Tim kamariddinov is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
























    0















    i have not been using python for some time and having trouble finding the solution to this problem.
    I tried to change the equation for euclidean distance function but it did not do any good. Maybe i am blind to see the solution to my problem.



    Here is my code:



    from math import sqrt
    import csv
    from random import shuffle
    import numpy as np
    import numpy
    import matplotlib.pyplot as plt
    import operator
    import math


    iris = datasets.load_iris()

    X = iris.data
    y = iris.target



    def euclideanDistance(id1, id2):
    for x in range(len(id1)-1):
    dist = np.sqrt(np.sum((int(id2[x]) - int(id1[x]))**2))
    return dist

    data1 = [2, 2, 2, 'a']
    data2 = [4, 4, 4, 'b']
    distance = euclideanDistance(data1, data2)
    print(distance)

    def mykNN(X, y, x_):
    distance = []
    neighbour = []

    for i in range(len(X)):
    d = euclideanDistance(X[i], x_ )
    distance.append((X[i], d))
    distance.sort(key=operator.itemgetter(1))

    for r in range(k):
    options.append(distance[r][0])
    options = neighbour
    return neighbour

    k=3

    y_ = mykNN(X, y,k)
    print(y_)


    no matter what how i change my function it comes up with this error.



    ---------------------------------------------------------------------------
    TypeError Traceback (most recent call last)
    <ipython-input-85-2a5bfc4a796d> in <module>
    42 k=3
    43
    ---> 44 y_ = mykNN(X, y,k)
    45 print(y_)
    46

    <ipython-input-85-2a5bfc4a796d> in mykNN(X, y, x_)
    31
    32 for i in range(len(X)):
    ---> 33 d = euclideanDistance(X[i], x_ )
    34 distance.append((X[i], d))
    35 distance.sort(key=operator.itemgetter(1))

    <ipython-input-85-2a5bfc4a796d> in euclideanDistance(id1, id2)
    18 def euclideanDistance(id1, id2):
    19 for x in range(len(id1)-1):
    ---> 20 dist = np.sqrt(np.sum((int(id2[x]) - int(id1[x]))**2))
    21 return dist
    22

    TypeError: 'int' object is not subscriptable


    I would appreciate your response as this has been bothering me.



    Thank you.










    share|improve this question







    New contributor




    Tim kamariddinov is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
    Check out our Code of Conduct.






















      0












      0








      0








      i have not been using python for some time and having trouble finding the solution to this problem.
      I tried to change the equation for euclidean distance function but it did not do any good. Maybe i am blind to see the solution to my problem.



      Here is my code:



      from math import sqrt
      import csv
      from random import shuffle
      import numpy as np
      import numpy
      import matplotlib.pyplot as plt
      import operator
      import math


      iris = datasets.load_iris()

      X = iris.data
      y = iris.target



      def euclideanDistance(id1, id2):
      for x in range(len(id1)-1):
      dist = np.sqrt(np.sum((int(id2[x]) - int(id1[x]))**2))
      return dist

      data1 = [2, 2, 2, 'a']
      data2 = [4, 4, 4, 'b']
      distance = euclideanDistance(data1, data2)
      print(distance)

      def mykNN(X, y, x_):
      distance = []
      neighbour = []

      for i in range(len(X)):
      d = euclideanDistance(X[i], x_ )
      distance.append((X[i], d))
      distance.sort(key=operator.itemgetter(1))

      for r in range(k):
      options.append(distance[r][0])
      options = neighbour
      return neighbour

      k=3

      y_ = mykNN(X, y,k)
      print(y_)


      no matter what how i change my function it comes up with this error.



      ---------------------------------------------------------------------------
      TypeError Traceback (most recent call last)
      <ipython-input-85-2a5bfc4a796d> in <module>
      42 k=3
      43
      ---> 44 y_ = mykNN(X, y,k)
      45 print(y_)
      46

      <ipython-input-85-2a5bfc4a796d> in mykNN(X, y, x_)
      31
      32 for i in range(len(X)):
      ---> 33 d = euclideanDistance(X[i], x_ )
      34 distance.append((X[i], d))
      35 distance.sort(key=operator.itemgetter(1))

      <ipython-input-85-2a5bfc4a796d> in euclideanDistance(id1, id2)
      18 def euclideanDistance(id1, id2):
      19 for x in range(len(id1)-1):
      ---> 20 dist = np.sqrt(np.sum((int(id2[x]) - int(id1[x]))**2))
      21 return dist
      22

      TypeError: 'int' object is not subscriptable


      I would appreciate your response as this has been bothering me.



      Thank you.










      share|improve this question







      New contributor




      Tim kamariddinov is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.












      i have not been using python for some time and having trouble finding the solution to this problem.
      I tried to change the equation for euclidean distance function but it did not do any good. Maybe i am blind to see the solution to my problem.



      Here is my code:



      from math import sqrt
      import csv
      from random import shuffle
      import numpy as np
      import numpy
      import matplotlib.pyplot as plt
      import operator
      import math


      iris = datasets.load_iris()

      X = iris.data
      y = iris.target



      def euclideanDistance(id1, id2):
      for x in range(len(id1)-1):
      dist = np.sqrt(np.sum((int(id2[x]) - int(id1[x]))**2))
      return dist

      data1 = [2, 2, 2, 'a']
      data2 = [4, 4, 4, 'b']
      distance = euclideanDistance(data1, data2)
      print(distance)

      def mykNN(X, y, x_):
      distance = []
      neighbour = []

      for i in range(len(X)):
      d = euclideanDistance(X[i], x_ )
      distance.append((X[i], d))
      distance.sort(key=operator.itemgetter(1))

      for r in range(k):
      options.append(distance[r][0])
      options = neighbour
      return neighbour

      k=3

      y_ = mykNN(X, y,k)
      print(y_)


      no matter what how i change my function it comes up with this error.



      ---------------------------------------------------------------------------
      TypeError Traceback (most recent call last)
      <ipython-input-85-2a5bfc4a796d> in <module>
      42 k=3
      43
      ---> 44 y_ = mykNN(X, y,k)
      45 print(y_)
      46

      <ipython-input-85-2a5bfc4a796d> in mykNN(X, y, x_)
      31
      32 for i in range(len(X)):
      ---> 33 d = euclideanDistance(X[i], x_ )
      34 distance.append((X[i], d))
      35 distance.sort(key=operator.itemgetter(1))

      <ipython-input-85-2a5bfc4a796d> in euclideanDistance(id1, id2)
      18 def euclideanDistance(id1, id2):
      19 for x in range(len(id1)-1):
      ---> 20 dist = np.sqrt(np.sum((int(id2[x]) - int(id1[x]))**2))
      21 return dist
      22

      TypeError: 'int' object is not subscriptable


      I would appreciate your response as this has been bothering me.



      Thank you.







      python python-3.x knn






      share|improve this question







      New contributor




      Tim kamariddinov is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.











      share|improve this question







      New contributor




      Tim kamariddinov is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.









      share|improve this question




      share|improve this question






      New contributor




      Tim kamariddinov is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.









      asked 2 days ago









      Tim kamariddinovTim kamariddinov

      11




      11




      New contributor




      Tim kamariddinov is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.





      New contributor





      Tim kamariddinov is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.






      Tim kamariddinov is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.






















          1 Answer
          1






          active

          oldest

          votes


















          1














          Well, the error is telling you that in euclideanDistance(), either id1 or id2 (or both) is an integer, since those are the two identifiers you're indexing on that line. To follow it through:



          • You set k = 3

          • You call mykNN(X, y, k), which means that in mykNN(), x_ == 3.

          • You call euclideanDistance(X[i], x_), which means that in euclideanDistance(), id2 == 3.

          • You attempt to index id2 on the indicated line. Integers can't be indexed, thus the exception.

          So that's what caused your error. As I'm not sure exactly what your code is doing, I can't directly recommend a fix.






          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
            );



            );






            Tim kamariddinov is a new contributor. Be nice, and check out our Code of Conduct.









            draft saved

            draft discarded


















            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55027043%2fknn-algorithm-int-object-is-not-subscriptable%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown

























            1 Answer
            1






            active

            oldest

            votes








            1 Answer
            1






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            1














            Well, the error is telling you that in euclideanDistance(), either id1 or id2 (or both) is an integer, since those are the two identifiers you're indexing on that line. To follow it through:



            • You set k = 3

            • You call mykNN(X, y, k), which means that in mykNN(), x_ == 3.

            • You call euclideanDistance(X[i], x_), which means that in euclideanDistance(), id2 == 3.

            • You attempt to index id2 on the indicated line. Integers can't be indexed, thus the exception.

            So that's what caused your error. As I'm not sure exactly what your code is doing, I can't directly recommend a fix.






            share|improve this answer



























              1














              Well, the error is telling you that in euclideanDistance(), either id1 or id2 (or both) is an integer, since those are the two identifiers you're indexing on that line. To follow it through:



              • You set k = 3

              • You call mykNN(X, y, k), which means that in mykNN(), x_ == 3.

              • You call euclideanDistance(X[i], x_), which means that in euclideanDistance(), id2 == 3.

              • You attempt to index id2 on the indicated line. Integers can't be indexed, thus the exception.

              So that's what caused your error. As I'm not sure exactly what your code is doing, I can't directly recommend a fix.






              share|improve this answer

























                1












                1








                1







                Well, the error is telling you that in euclideanDistance(), either id1 or id2 (or both) is an integer, since those are the two identifiers you're indexing on that line. To follow it through:



                • You set k = 3

                • You call mykNN(X, y, k), which means that in mykNN(), x_ == 3.

                • You call euclideanDistance(X[i], x_), which means that in euclideanDistance(), id2 == 3.

                • You attempt to index id2 on the indicated line. Integers can't be indexed, thus the exception.

                So that's what caused your error. As I'm not sure exactly what your code is doing, I can't directly recommend a fix.






                share|improve this answer













                Well, the error is telling you that in euclideanDistance(), either id1 or id2 (or both) is an integer, since those are the two identifiers you're indexing on that line. To follow it through:



                • You set k = 3

                • You call mykNN(X, y, k), which means that in mykNN(), x_ == 3.

                • You call euclideanDistance(X[i], x_), which means that in euclideanDistance(), id2 == 3.

                • You attempt to index id2 on the indicated line. Integers can't be indexed, thus the exception.

                So that's what caused your error. As I'm not sure exactly what your code is doing, I can't directly recommend a fix.







                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered 2 days ago









                glibdudglibdud

                5,65921731




                5,65921731






















                    Tim kamariddinov is a new contributor. Be nice, and check out our Code of Conduct.









                    draft saved

                    draft discarded


















                    Tim kamariddinov is a new contributor. Be nice, and check out our Code of Conduct.












                    Tim kamariddinov is a new contributor. Be nice, and check out our Code of Conduct.











                    Tim kamariddinov is a new contributor. Be nice, and check out our Code of Conduct.














                    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%2f55027043%2fknn-algorithm-int-object-is-not-subscriptable%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

                    Identity Server 4 is not redirecting to Angular app after login2019 Community Moderator ElectionIdentity Server 4 and dockerIdentityserver implicit flow unauthorized_clientIdentityServer Hybrid Flow - Access Token is null after user successful loginIdentity Server to MVC client : Page Redirect After loginLogin with Steam OpenId(oidc-client-js)Identity Server 4+.NET Core 2.0 + IdentityIdentityServer4 post-login redirect not working in Edge browserCall to IdentityServer4 generates System.NullReferenceException: Object reference not set to an instance of an objectIdentityServer4 without HTTPS not workingHow to get Authorization code from identity server without login form

                    2005 Ahvaz unrest Contents Background Causes Casualties Aftermath See also References Navigation menue"At Least 10 Are Killed by Bombs in Iran""Iran"Archived"Arab-Iranians in Iran to make April 15 'Day of Fury'"State of Mind, State of Order: Reactions to Ethnic Unrest in the Islamic Republic of Iran.10.1111/j.1754-9469.2008.00028.x"Iran hangs Arab separatists"Iran Overview from ArchivedConstitution of the Islamic Republic of Iran"Tehran puzzled by forged 'riots' letter""Iran and its minorities: Down in the second class""Iran: Handling Of Ahvaz Unrest Could End With Televised Confessions""Bombings Rock Iran Ahead of Election""Five die in Iran ethnic clashes""Iran: Need for restraint as anniversary of unrest in Khuzestan approaches"Archived"Iranian Sunni protesters killed in clashes with security forces"Archived

                    Can't initialize raids on a new ASUS Prime B360M-A motherboard2019 Community Moderator ElectionSimilar to RAID config yet more like mirroring solution?Can't get motherboard serial numberWhy does the BIOS entry point start with a WBINVD instruction?UEFI performance Asus Maximus V Extreme