2016년 6월 29일 수요일

파이썬 - kNN 알고리즘 구현에 대한 데모입니다.

k-Nearest Neighbers(k-근접이웃)은 가장 단순한 예측 모델 중에 하나입니다.

아래와 같이 모듈을 임포트 받습니다.

from __future__ import division, unicode_literals
from collections import Counter
import math, random

import matplotlib.pyplot as plt

from linear_algebra import distance
from statistics import mean

from plot_state_borders import plot_state_borders

약간의 예시 데이터를 통해서 분석을 하면 다음과 같이 출력된다.
cities = [(-86.75,33.5666666666667,'Python'),(-88.25,30.6833333333333,'Python'),(-112.016666666667,33.4333333333333,'Java'),(-110.933333333333,32.1166666666667,'Java'),(-92.2333333333333,34.7333333333333,'R'),(-121.95,37.7,'R')

cities = [([longitude, latitude], language) for longitude, latitude, language in cities]

def plot_cities():

    # key is language, value is pair (longitudes, latitudes)
    plots = { "Java" : ([], []), "Python" : ([], []), "R" : ([], []) }

    # we want each language to have a different marker and color
    markers = { "Java" : "o", "Python" : "s", "R" : "^" }
    colors  = { "Java" : "r", "Python" : "b", "R" : "g" }

    for (longitude, latitude), language in cities:
        plots[language][0].append(longitude)
        plots[language][1].append(latitude)

    # create a scatter series for each language
    for language, (x, y) in plots.iteritems():
        plt.scatter(x, y, color=colors[language], marker=markers[language],
                          label=language, zorder=10)

    plot_state_borders()    # assume we have a function that does this

    plt.legend(loc=0)          # let matplotlib choose the location
    plt.axis([-130,-60,20,55]) # set the axes
    plt.title("Very popular language")
    plt.show()
   

plot_cities()


댓글 없음:

댓글 쓰기

참고: 블로그의 회원만 댓글을 작성할 수 있습니다.

테슬라 차량이 무인 배송이 된 역사적인 사건입니다. ㅎㅎ

테슬라는 꿈을 그리는 기업입니다. 좀 황당하고 무섭기도 한데 시간이 지연되고 있지만 꾸준하게 발전하는 모습을 보여줍니다.  테슬라 차량을 주문한 고객이 무인 배송으로 차를 받는 영상입니다. ㅋㅋ  이러다가 정말 화성 탐사선에 옵티머스 로봇이 탑재되는 ...