7.2一個簡單分類的程序

def classify0(inX, dataSet, labels, k):

    dataSetSize = dataSet.shape[0]                              計算行數
    diffMat = tile(inX, (dataSetSize,1)) - dataSet            計算測試點與所選樣本的距離
    sqDiffMat = diffMat**2                                             矩陣單項的平方
    sqDistances = sqDiffMat.sum(axis=1)                     矩陣單行的求和
    distances = sqDistances**0.5                                  求距離
    sortedDistIndicies = distances.argsort()                  距離的從小到大的排序
    classCount={}          
    for i in range(k):
        voteIlabel = labels[sortedDistIndicies[i]]              
順序取距離由小變大的前k位,取對應標籤
        print(i)                    
        print(sortedDistIndicies[i])
        print(voteIlabel)
        classCount[voteIlabel] = classCount.get(voteIlabel,0) + 1   每個標籤出現的次數
        print(classCount[voteIlabel])
    sortedClassCount = sorted(classCount.iteritems(), key=operator.itemgetter(1), reverse=True)                                                                              排序
    print(sortedClassCount)
    myset={'dataSetSize':dataSetSize,'diffMat':diffMat,'sqDiffMat':sqDiffMat,'sqDistances':sqDistances,'distances':distances,'sortedDistIndicies':sortedDistIndicies,'classCount':classCount}
    return sortedClassCount[0][0],myset,classCount


def createDataSet():
    group = array([[1.0,1.1],[1.0,1.0],[0,0],[0,0.1]])
    labels = ['A','A','B','B']

    return group, labels


#####說明:sortedClassCount = sorted(classCount.iteritems(),key=operator.itemgetter(1), reverse=True)

函數參數解釋:sorted(iterable[, cmp[, key[, reverse]]])

sorted第一個參數爲list(即[]序列)或者迭代器(本例)。

         cmp參數:指定排序時進行比較的函數,可以指定一個函數或者lambda函數,如:

                                    cmp接受一個函數,拿整形舉例,形式爲:

                                   def f(a,b):

                                   return a-b

                                 如果排序的元素是其他類型的,如果a邏輯小於b,函數返回負數;a邏輯等於b,函數返回0;a邏輯大於b,                                  函數返回正數就行了

            key參數:指定序列中排序的元素,這裏調用opertor.itemgetter(1),就是取classcount序列的每個元素第2個值排序。                          再如: students = [('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)],其中key=operator.itemgetter(1,2),就是表示取                                      students的每個元素的第2個值

             reverse參數:接受False 或者True 表示是否逆序

=======================================

調用

import os
os.chdir('C:\\Users\\admin\\Desktop')
import kNN


group,label=kNN.createDataSet()
t,myset,sort=kNN.classify0([0,0],group,label,3)


for key in myset:
  print(key+':')
  print(myset[key])



==================================================================

需要了解的背景知識

==============================================================

Python中的sorted函數以及operator.itemgetter函數

operator.itemgetter函數
operator模塊提供的itemgetter函數用於獲取對象的哪些維的數據,參數爲一些序號(即需要獲取的數據在對象中的序號),下面看例子。

a = [1,2,3] 
>>> b=operator.itemgetter(1)      //定義函數b,獲取對象的第1個域的值
>>> b(a) 

>>> b=operator.itemgetter(1,0)  //定義函數b,獲取對象的第1個域和第0個的值
>>> b(a) 
(2, 1)

要注意,operator.itemgetter函數獲取的不是值,而是定義了一個函數,通過該函數作用到對象上才能獲取值。

sorted函數
Python內置的排序函數sorted可以對list或者iterator進行排序,官網文檔見:http://docs.python.org/2/library/functions.html?highlight=sorted#sorted,該函數原型爲:

sorted(iterable[, cmp[, key[, reverse]]])

參數解釋:

(1)iterable指定要排序的list或者iterable,不用多說;

(2)cmp爲函數,指定排序時進行比較的函數,可以指定一個函數或者lambda函數,如:

      students爲類對象的list,沒個成員有三個域,用sorted進行比較時可以自己定cmp函數,例如這裏要通過比較第三個數據成員來排序,代碼可以這樣寫:
      students = [('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)]
      sorted(students, key=lambda student : student[2])
(3)key爲函數,指定取待排序元素的哪一項進行排序,函數用上面的例子來說明,代碼如下:
      sorted(students, key=lambda student : student[2])

      key指定的lambda函數功能是去元素student的第三個域(即:student[2]),因此sorted排序時,會以students所有元素的第三個域來進行排序。

有了上面的operator.itemgetter函數,也可以用該函數來實現,例如要通過student的第三個域排序,可以這麼寫:
sorted(students, key=operator.itemgetter(2)) 
sorted函數也可以進行多級排序,例如要根據第二個域和第三個域進行排序,可以這麼寫:
sorted(students, key=operator.itemgetter(1,2))

即先跟句第二個域排序,再根據第三個域排序。
(4)reverse參數就不用多說了,是一個bool變量,表示升序還是降序排列,默認爲false(升序排列),定義爲True時將按降序排列。

sorted函數更多的例子可以參考官網文檔:https://wiki.python.org/moin/HowTo/Sorting/。

                                            第一章 K-neans算法
1,pip list 查看安裝的包
2,os.chdir(‘’)設置工作目錄
==========================================================
3.from import 與import的區別
導入modules,import與from...import的不同之處在於,簡單說:
# 如果你想在程序中用argv代表sys.argv,
# 則可使用:from sys import argv
# 一般說來,應該避免使用from..import而使用import語句,
# 因爲這樣可以使你的程序更加易讀,也可以避免名稱的衝突
==============================================================
4.numpy.tile(A,reps)函數的使用,即數組A的重複次數reps
(1)A的類型衆多,幾乎所有類型都可以:array, list, tuple, dict, matrix以及基本數據類型int, string, float以及bool類型。
reps的類型也很多,可以是tuple,list, dict, array, int,bool.但不可以是float, string, matrix類型。
假定A的維度爲d,reps的長度爲len
(2)函數操作示例
首先給幾個示例:
>>> tile(1.3,2)
array([ 1.3,  1.3])
array([1, 2, 1, 2, 1, 2])
>>> tile((1,2,3),2)
array([1, 2, 3, 1, 2, 3])
>>> a=[[1,2,3],[4,5,5]]
>>> tile(a,2)
array([[1, 2, 3, 1, 2, 3],
       [4, 5, 5, 4, 5, 5]])
>>> tile([1,2,3],[2,2,2,2])
array([   
                 [  [[1, 2, 3, 1, 2, 3],[1, 2, 3, 1, 2, 3]], [[1, 2, 3, 1, 2, 3],[1, 2, 3, 1, 2, 3]]   ],




                 [  [[1, 2, 3, 1, 2, 3], [1, 2, 3, 1, 2, 3]],[[1, 2, 3, 1, 2, 3],[1, 2, 3, 1, 2, 3]]  ]
         ])
===========================================================================
5,數組項目的求和,比如數組A
A.sum(axis=(0或者1)),其中axis=0,表示列求和;axis=1,表示行求和   
===============================================================
6.數組的大小索引函數argsort()
舉例:  a=numpy.array([1,3,2])        a.argsort()
           輸出結果爲[0,2,1]就是每個向量的值大小的索引
舉例:   x = numpy.array([[0, 3], [2, 2]])   x.argsort()
           [[0,1],[0,0]]
   





發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章