Using KNN algorithm to classify

Source: Internet
Author: User

1 ImportMatplotlib.pyplot as Plt2 ImportNumPy as NP3 4  fromSklearn.datasets.samples_generatorImportMake_blobs5 #Generate Data6Centers = [[-2, 2], [2, 2], [0, 4]]7X, y = Make_blobs (n_samples=600, Centers=centers, random_state=0, cluster_std=0.60)8 #Draw the data9Plt.figure (figsize=), dpi=144)Tenc =Np.array (centers) OnePlt.scatter (x[:, 0], x[:, 1], c=y, s=100, cmap='Cool');#Draw a sample APlt.scatter (c[:, 0], c[:, 1], s=100, marker='^', c='Orange');#Draw the center point -  -  fromSklearn.neighborsImportKneighborsclassifier the  fromNumPy as NP - #Model Training -K = 5 -CLF = Kneighborsclassifier (n_neighbors=k) + Clf.fit (X, y); -  + #Make predictions A #x_sample = [[0,2],[1,1],[-1,3]] atX_sample = Np.array ([[0,2],[1,1],[-1,3]],dtype=int) -  -Y_sample =clf.predict (x_sample); -Neighbors = Clf.kneighbors (X_sample, return_distance=False); -  -x_sample_disp_x = Np.array (x_sample[:,0],dtype=int) inx_sample_disp_y = Np.array (x_sample[:,1],dtype=int) - #Draw a toPlt.figure (figsize=), dpi=144) +Plt.scatter (x[:, 0], x[:, 1], c=y, s=100, cmap='Cool');#Sample -Plt.scatter (c[:, 0], c[:, 1], s=100, marker='^', c='k');#Center Point thePlt.scatter (x_sample_disp_x, x_sample_disp_y, marker="x",  *C=y_sample, s=100, cmap='Cool')#points to be predicted $ Panax Notoginseng  -  the  forIinchNeighbors[0]: +Plt.plot ([x[i][0], x_sample[0][0]], [x[i][1], x_sample[0][1]], A              'k--', linewidth=0.8);#The connection between the predicted point and the nearest 5 samples the  forIinchNeighbors[1]: +Plt.plot ([x[i][0], x_sample[1][0]], [x[i][1], x_sample[1][1]], -              'k--', linewidth=0.8); $  forIinchNeighbors[2]: $Plt.plot ([x[i][0], x_sample[2][0]], [x[i][1], x_sample[2][1]], -              'k--', linewidth=0.8);

Using KNN algorithm to classify

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.