機器學習--kNN演算法案例

來源:互聯網
上載者:User

標籤:

一、改進約會網站的配對效果

       想要預測的目標變數:不喜歡的人、魅力一般的人、極具魅力的人

       樣本特徵:每年獲得的飛行常客裡程數、玩視頻遊戲所耗時間百分比、每周消費的冰淇淋公升數

       約會資料資訊存放在文字檔datingTestSet.txt中,每個樣本資料佔據一行,共有1000行。

 

實現步驟

1、將文字檔中的資料進行解析

###################################
#功能:將文字檔中的資料解析為矩陣形式
#輸入變數:filename 檔案名稱字串
#輸出變數:return_mat, class_label_vector 檔案轉換後的矩陣, 類標籤向量
###################################


def file2matrix(filename):
    fr = open(filename, ‘r‘)  # 唯讀方式開啟檔案
    array_of_lines = fr.readlines()  # readlines()來讀取所有資料,這樣可以儘快釋放檔案資源
    number_of_lines = len(array_of_lines)  # 得到檔案行數
    return_mat = zeros((number_of_lines, 3))  # 建立返回矩陣

    class_label_vector = []
    index = 0

    label_dict = {‘largeDoses‘: 3, ‘smallDoses‘: 2, ‘didntLike‘: 1}

    # readlines()讀取整個檔案並以行構成一個列表,每行作為for的一個迴圈
    for line in array_of_lines:

        #先去除字串兩邊的空格,再以tab分隔字元分切字串
        list_form_line = line.strip().split(‘\t‘)

        return_mat[index, :] = list_form_line[0:3]  # 替代每行資料

        # 使用負下標選取list_form_line最後一列
        # 即把三種類型的人數添加到class_label_vector列表中
        class_label_vector.append(label_dict[list_form_line[-1]])

        index += 1
    return return_mat, class_label_vector

 

2、歸一化特徵值

在處理不同取值範圍的特徵值時,為了避免權重失衡,通常會對數值進行歸一化處理,此函數可以自動將數字特徵值轉化為0到1的區間。

###################################
#功能:對數值進行歸一化處理
#輸入變數:data_set 樣本資料
#輸出變數:norm_data_set, ranges, min_vals 歸一化後的樣本,取值範圍,最小值
###################################
def auto_norm(data_set):
    min_values = data_set.min(0)  # 參數0使得函數可以從列中選取最小值,而不是選取當前行的最小值
    max_values = data_set.max(0)

    ranges = max_values - min_values

    m = data_set.shape[0]  # 獲得數組的行數
    diff_data_set = data_set - tile(min_values, (m, 1))
    norm_data_set = diff_data_set/tile(ranges, (m, 1))  # 對應數值進行相除

    return norm_data_set, ranges, min_values

 

3、利用約會網站資料測試分類器效果

機器學習演算法一個很重要的工作就是評估演算法的正確率,通常用已有資料的90%作為訓練樣本,其餘的10%資料去測試分類器。需要注意的是,10%的資料應該是隨機播放的。對於分類器來說,錯誤率是檢測效能的指標。錯誤率是錯誤結果的次數除以測試資料的總數,完美分類器錯誤率為0,而錯誤率為1.0的分類器不會給出任何正確的分類結果。

 

###################################
#功能:測試分類器的效果
###################################
def dating_class_test():
    ho_ratio = 0.10  # 測試資料占的百分比

    dating_data_mat, dating_labels = file2matrix(‘datingTestSet.txt‘)
    norm_mat, ranges, min_values = auto_norm(dating_data_mat)

    m = norm_mat.shape[0]
    num_test_vectors = int(m*ho_ratio)  # 10%的資料作為測試

    error_count = 0.0
    for i in xrange(num_test_vectors):
        classifier_result = classify0(norm_mat[i, :], norm_mat[num_test_vectors:m, :],
                                      dating_labels[num_test_vectors:m], 3)
        print "the classifier came back with: %d, the real answer is: %d" % \
              (classifier_result, dating_labels[i])

        if classifier_result != dating_labels[i]:
            error_count += 1.0
    print "the total error rate is: %f" % (error_count/num_test_vectors)

 

4、從錯誤率來看,分類器的效能還不錯,接下來將利用該分類器來預測喜歡程度

 

###################################
#功能:輸入某人的資訊,得出對對方喜歡程度的預測值
###################################
def classify_person():
    result_list = [‘not at all‘, ‘in small doses‘, ‘in large doses‘]

    # 飛行常客裡程數
    ff_miles = float(raw_input("frequent flier miles earned per year:"))
    # 玩視頻遊戲所耗時間百分比
    percent_tats = float(raw_input("percentage of time spent playing video games:"))
    # 每周消費的冰淇淋公升數
    ice_cream = float(raw_input("liters of ice cream consumed per week:"))

    dating_data_mat, dating_labels = file2matrix(‘datingTestSet.txt‘)
    norm_mat, ranges, min_values = auto_norm(dating_data_mat)

    in_arr = array([ff_miles, percent_tats, ice_cream])
    classifier_result = classify0((in_arr-min_values)/ranges, norm_mat, dating_labels, 3)

    print "you will probably like this person: ", result_list[classifier_result - 1]

 

二、手寫辨識系統

        將手寫字元看成由0、1組成的32行32列的一個二進位影像檔,手寫字元是數字0到9。由此可知,

        想要預測的目標變數:0到9的數字

        樣本特徵:無

        手寫文本資料有兩個子目錄:目錄trainingDigits中包含了大約2000個例子,每個例子的內容是0到9的數位影像,每個數字有大約200個樣本;目錄testDigits中包含了大約900個測試資料。使用trainingDigits中的資料訓練分類器,使用testDigits中的資料測試分類器效果。

 

實現步驟:

1、將影像檔的資料轉為向量,把32*32的二進位映像矩陣轉為1*1024的向量,這樣分類器就可以處理數位影像資訊了。

 

###################################
#功能:將映像轉換成向量,將一個32*32的二進位映像轉換成1*1024的向量
#輸入變數:filename 檔案名稱字串
#輸出變數:return_vector 轉換後的向量
###################################
def img2vector(filename):
    return_vector = zeros((1, 1024))
    fr = open(filename, ‘r‘)  # 唯讀方式開啟檔案
    for i in xrange(32):
        line_str = fr.readline()  # readline()一次讀取一行資料
        for j in xrange(32):
            return_vector[0, 32*i+j] = int(line_str[j])  # 32*32個資料寫入一行內

    return return_vector

 

2、使用kNN演算法識別手寫數字

 

###################################
#功能:測試手寫辨識系統
###################################
def hand_writing_class_test():
    hw_labels = []
    training_file_list = listdir(‘trainingDigits‘)  # 將目錄中的檔案名稱(例如‘0_0.txt‘)儲存在列表中
    m = len(training_file_list)  # 計算檔案數
    training_mat = zeros((m, 1024))

    for i in xrange(m):
        file_name_str = training_file_list[i]
        file_str = file_name_str.split(‘.‘)[0]  # 得到檔案名稱如[0_12.txt],[0]是第一個資料0_12
        class_num_str = int(file_str.split(‘_‘)[0])  # 得到數組如[0_12]獲得第一個數[0]
        hw_labels.append(class_num_str)  # 將獲得的數字添加到標籤數組中

        training_mat[i, :] = img2vector(‘trainingDigits/%s‘ % file_name_str)  # 資料格式轉換

    test_file_list = listdir(‘testDigits‘)
    error_count = 0.0
    m_test = len(test_file_list)

    for i in xrange(m_test):
        file_name_str = test_file_list[i]
        file_str = file_name_str.split(‘.‘)[0]
        class_num_str = int(file_str.split(‘_‘)[0])

        vector_under_test = img2vector(‘testDigits/%s‘ % file_name_str)

        classifier_result = classify0(vector_under_test, training_mat, hw_labels, 3)
        print "the classifier came back with: %d, the real answer is: %d" % (classifier_result, class_num_str)

        if classifier_result != class_num_str:
            error_count += 1.0

    print "the total number of errors is: %d" % error_count
    print "the total error rate is: %f" % (error_count/float(m_test))

 

 

def main():

   dating_data_mat, dating_labels = file2matrix(‘datingTestSet.txt‘)
   print ‘dating_data_mat=‘, dating_data_mat
   print ‘dating_labels=‘, dating_labels

   norm_mat, ranges, min_values = auto_norm(dating_data_mat)
   print ‘norm_mat=‘, norm_mat
   print ‘ranges=‘, ranges
   print ‘min_values=‘, min_values

   dating_class_test()

   classify_person()

 

   test_vector = img2vector(‘testDigits/0_13.txt‘)
   print ‘test_vector=‘, test_vector[0, 0:31]
   print ‘test_vector=‘, test_vector[0, 32:63]

   hand_writing_class_test()

 

if __name__ == ‘__main__‘:
    main()

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

機器學習--kNN演算法案例

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.