機(jī)器學(xué)習(xí)實(shí)戰(zhàn)篇 (k近鄰算法)

機(jī)器學(xué)習(xí)實(shí)戰(zhàn)篇 (k近鄰算法)

k近鄰算法:通過測(cè)量不同特征值之間的距離進(jìn)行分類

優(yōu)點(diǎn):精度高,對(duì)異常值不敏感署海,無數(shù)據(jù)輸入假定吗购。

缺點(diǎn):計(jì)算復(fù)雜度高,空間復(fù)雜度高砸狞。

計(jì)算公式

分類器的代碼實(shí)現(xiàn)

import numpy as np
from collections import Counter

def classify0(inx, dataset, labels, k=1):
    ##預(yù)處理(此處的輸入labels是帶有具體分類內(nèi)容的list),inx和dataset都numpy對(duì)象
    if k <= 0:
        k = 1
    try:
        y = inx.shape[1]
    except:
        inx.shape=(-1, inx.shape[0])
    ##計(jì)算歐氏距離
    num_test = inx.shape[0]
    num_train = dataset.shape[0]
    dists = np.zeros((num_test, num_train))
    dists = np.multiply(np.dot(inx, dataset.T), -2)
    inx_sq = np.sum(np.square(inx), axis=1, keepdims=True)
    dataset_sq = np.sum(np.square(dataset), axis=1)
    dists = np.add(dists, inx_sq)
    dists = np.add(dists, dataset_sq)
    dists = np.sqrt(dists)
    ###獲取標(biāo)簽
    result = []
    per_line_labels=[]
    sort_arg = dists.argsort()[:,:k]
    for line in sort_arg:
        per_line_labels = [labels[index] for index in line]
        result.append(Counter(per_line_labels).most_common(1)[0][0])
    return result

實(shí)例1 利用K-近鄰算法改進(jìn)約會(huì)網(wǎng)站的配對(duì)效果

數(shù)據(jù)集下載 http://pan.baidu.com/s/1geMv2mf

1.從文件中讀取數(shù)據(jù)轉(zhuǎn)化為可計(jì)算的numpy對(duì)象

def file1matrix(filename):
    ###從文件中讀取數(shù)據(jù)并轉(zhuǎn)為可計(jì)算的numpy對(duì)象
    dataset = []
    labels = []
    with open(filename,'r') as f:
        for line in f:
            line = line.strip().split('\t')
            labels.append(line.pop())
            dataset.append(line)
    dataset = np.array(dataset, dtype=np.float32)
    return dataset, labels

2.將數(shù)據(jù)可視化

def convert(labels):
    label_names = list(set(labels))
    labels = [label_names.index(label) for label in labels]
    return label_names,labels

def draw(dataset, labels, label_names):
    labels = [ i+1 for i in labels]  ###下標(biāo)加1捻勉,繪色
    from matplotlib import pyplot as plt
    from matplotlib import font_manager
    zhfont = font_manager.FontProperties(fname='C:\\Windows\\Fonts\\msyh.ttc')
    plt.figure(figsize=(8, 5), dpi=80)
    ax = plt.subplot(111)
    # ax.scatter(dataset[:,1], dataset[:,2], 15.0*np.array(labels), 15.0*np.array(labels))
    # plt.show()
    type1_x = []
    type1_y = []
    type2_x = []
    type2_y = []
    type3_x = []
    type3_y = []
    for i in xrange(len(labels)):
        if labels[i] == 1:
            type1_x.append(dataset[i][0])
            type1_y.append(dataset[i][1])
        if labels[i] == 2:
            type2_x.append(dataset[i][0])
            type2_y.append(dataset[i][1])
        if labels[i] == 3:
            type3_x.append(dataset[i][0])
            type3_y.append(dataset[i][1])
    ax.scatter(type1_x, type1_y, color = 'red', s = 20)
    ax.scatter(type2_x, type2_y, color = 'green', s = 20)    
    ax.scatter(type3_x, type3_y, color = 'blue', s = 20)    
    plt.xlabel(u'飛行里程數(shù)', fontproperties=zhfont)
    plt.ylabel(u'視頻游戲消耗時(shí)間', fontproperties=zhfont)
    ax.legend((label_names[0], label_names[1], label_names[2]), loc=2, prop=zhfont)
    plt.show()

3.歸一化特征值 (這里介紹兩種方法)

####由于數(shù)據(jù)中飛行里程數(shù)特征值與其他的特征值差距較大,對(duì)計(jì)算結(jié)果會(huì)產(chǎn)生非常大的影響刀森,所以將特征值轉(zhuǎn)化為0到1區(qū)間內(nèi)的值   
def autoNorm0(dataset):
    if not isinstance(dataset, np.ndarray):
        dataset = np.array(dataset,dtype=np.float32)
    ###歸一化特征值 newvalue = (oldvalue - min) / (max - min)
    minVals = dataset.min(0)
    maxVals = dataset.max(0)
    ranges = maxVals - minVals
    dataset = dataset - minVals
    dataset = dataset / ranges
    return dataset

def autoNorm1(dataset):
    ###歸一化特征值 newvalue = (oldvalue - 均值) / 標(biāo)準(zhǔn)差    ----->推薦使用這種方法
    if not isinstance(dataset, np.ndarray):
        dataset = np.array(dataset,dtype=np.float32)
    mean = dataset.mean(0)
    std = dataset.std(0)
    dataset = dataset - mean
    dataset = dataset / std
    return dataset

4.編寫測(cè)試代碼

def datingTest():
    ##隨機(jī)選取測(cè)試集和訓(xùn)練集
    filename = 'datingTestSet.txt'
    dataset, labels = file1matrix(filename)
    dataset = autoNorm1(dataset)
    train_length = int(dataset.shape[0] * 0.9)
    test_length = dataset.shape[0] - train_length
    from random import sample
    all_index = sample(range(dataset.shape[0]), dataset.shape[0])
    train_index = all_index[:train_length]
    test_index = all_index[-test_length:]
    train_dataset = dataset[train_index, :]
    train_labels = []
    test_dataset = dataset[test_index, :]
    test_labels = []
    for index in train_index:
        train_labels.append(labels[index])
    for index in test_index:
        test_labels.append(labels[index])
    ##訓(xùn)練并計(jì)算錯(cuò)誤率
    test_result = classify0(test_dataset, train_dataset, train_labels, k=3)
    error = 0
    for res in zip(test_result, test_labels):
        if res[0] != res[1]:
            error += 1
    print 'error accaury:%f' % (float(error) / len(test_labels))

實(shí)例2 識(shí)別手寫數(shù)字

1.讀取文件數(shù)據(jù)并轉(zhuǎn)化為可計(jì)算的numpy對(duì)象

import os

def imgVector(filename):
    vect = []
    with open(filename,'r') as f:
        for line in f:
            line = line.strip()
            vect += [float(n) for n in line]
    number = os.path.split(filename)[-1].split('_')[0]
    return np.array(vect, dtype=np.float32), number

def all_imgVector(directory):
    filelist = os.listdir(directory)
    vects = []
    labels = []
    for filename in filelist:
        vect, label= imgVector(os.path.join(directory, filename))
        vects.append(vect)
        labels.append(label)
    return np.array(vects, dtype=np.float32), labels

2.編寫測(cè)試代碼

def handwritingClassTest():
    test_dir = 'digits\\testDigits'
    train_dir = 'digits\\trainingDigits'
    train_dataset, train_labels = all_imgVector(train_dir)
    test_dataset, test_labels = all_imgVector(test_dir)
    result_labels = classify0(test_dataset, train_dataset, train_labels, k=3)

    error = 0 
    for res in zip(result_labels, test_labels):
        if res[0] != res[1]:
            error += 1
    print 'error accaury:%f' % (float(error) / len(test_labels))
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末贯底,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子撒强,更是在濱河造成了極大的恐慌禽捆,老刑警劉巖,帶你破解...
    沈念sama閱讀 221,273評(píng)論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件飘哨,死亡現(xiàn)場(chǎng)離奇詭異胚想,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)芽隆,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,349評(píng)論 3 398
  • 文/潘曉璐 我一進(jìn)店門浊服,熙熙樓的掌柜王于貴愁眉苦臉地迎上來统屈,“玉大人,你說我怎么就攤上這事牙躺〕钽荆” “怎么了?”我有些...
    開封第一講書人閱讀 167,709評(píng)論 0 360
  • 文/不壞的土叔 我叫張陵孽拷,是天一觀的道長(zhǎng)吨掌。 經(jīng)常有香客問我,道長(zhǎng)脓恕,這世上最難降的妖魔是什么膜宋? 我笑而不...
    開封第一講書人閱讀 59,520評(píng)論 1 296
  • 正文 為了忘掉前任,我火速辦了婚禮炼幔,結(jié)果婚禮上秋茫,老公的妹妹穿的比我還像新娘。我一直安慰自己乃秀,他們只是感情好肛著,可當(dāng)我...
    茶點(diǎn)故事閱讀 68,515評(píng)論 6 397
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著跺讯,像睡著了一般策泣。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上抬吟,一...
    開封第一講書人閱讀 52,158評(píng)論 1 308
  • 那天萨咕,我揣著相機(jī)與錄音,去河邊找鬼火本。 笑死危队,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的钙畔。 我是一名探鬼主播茫陆,決...
    沈念sama閱讀 40,755評(píng)論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼擎析!你這毒婦竟也來了簿盅?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,660評(píng)論 0 276
  • 序言:老撾萬榮一對(duì)情侶失蹤揍魂,失蹤者是張志新(化名)和其女友劉穎桨醋,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體现斋,經(jīng)...
    沈念sama閱讀 46,203評(píng)論 1 319
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡喜最,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,287評(píng)論 3 340
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了庄蹋。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片瞬内。...
    茶點(diǎn)故事閱讀 40,427評(píng)論 1 352
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡迷雪,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出虫蝶,到底是詐尸還是另有隱情章咧,我是刑警寧澤,帶...
    沈念sama閱讀 36,122評(píng)論 5 349
  • 正文 年R本政府宣布能真,位于F島的核電站赁严,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏舟陆。R本人自食惡果不足惜误澳,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,801評(píng)論 3 333
  • 文/蒙蒙 一耻矮、第九天 我趴在偏房一處隱蔽的房頂上張望秦躯。 院中可真熱鬧,春花似錦裆装、人聲如沸踱承。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,272評(píng)論 0 23
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽茎活。三九已至,卻和暖如春琢唾,著一層夾襖步出監(jiān)牢的瞬間载荔,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,393評(píng)論 1 272
  • 我被黑心中介騙來泰國(guó)打工采桃, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留懒熙,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 48,808評(píng)論 3 376
  • 正文 我出身青樓普办,卻偏偏與公主長(zhǎng)得像工扎,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子衔蹲,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,440評(píng)論 2 359

推薦閱讀更多精彩內(nèi)容