KNN Python Code

Source: Internet
Author: User

A few minutes to write a KNN python code, on the compiler can run directly:


"" "PROGRAMS:KNN algorithm description:1.calculate the distance between test data and every single train data 2.sort the Distance 3.select the minimum k points by distance 4.count the label frequency of K points 5.return to the label of the Highest frequency "" "from Mlxtend.data import iris_data import NumPy as NP class Knn_csy (object): Def __init__ (SE
        Lf,dataset,label): Self.dataset=dataset self.label=label def distance (self,dataset_i,testdata): Dist=np.sum ((dataset_i-testdata) **2) return Np.sqrt (Dist) def Calculate_dis (self,testdata,k=10,updateflage= 0): "" ":p Aram TestData::p Aram K:default by:p Aram Updateflage:: R Eturn: "" "If Len (testdata)!=len (Self.dataset[0]): Raise Exception (" wrong input array of test
        Data "); Dis=[] Dimension=len (self.dataset) for I in Range (dimension): Distance=self.distance (Self.data Set[i],tEstdata) dis.append (distance) dic=zip (Dis,self.label) dic=sorted (DIC) label=[]
        For I in range (k): Label.append (dic[i][1]) count=np.bincount (label) Label=np.argmax (count)

If Updateflage:self.dataset.append (testdata) self.label.append (label) return label if __name__ = = ' __main__ ': Dataset,label=iris_data () Myknn=knn_csy (Dataset,label) testdata=[2,1,1,2] Labe







 L=myknn.calculate_dis (testdata,3) Print label


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.