機器學習實戰第一二章筆記

python 中一些函數的含義:

1 tile

例:

(1)

a = array([0, 1, 2])
b = tile(a, 2)
print(b)

//結果爲
[0, 1, 2, 0, 1, 2]

(2)

a = array([0, 1, 2])
b = tile(a, (2, 1))
print(b)

//結果爲
[[0, 1, 2],  
 [0, 1, 2]]

2 **

a**2 ==>求a的平方

a**3 ==>求a的立方

3 sum axis

sum應該是默認的axis=0 就是普通的矩陣或者數組對應相加

而當加入axis=1以後就是將一個矩陣的每一行向量相加

c = np.array([[0, 2, 1], [3, 5, 6], [0, 1, 1]])

print c.sum()
print c.sum(axis=0)
print c.sum(axis=1)

結果分別是:19, [3 8 8], [ 3 14  2]

         (2)keepdims

                  import numpy as np a = np.array([[1,2],[3,4]])

                  # 按行相加,並且保持其二維特性

                  print(np.sum(a, axis=1, keepdims=True))

                  # 按行相加,不保持其二維特性

                  print(np.sum(a, axis=1))

                  結果:

                  array([[3], [7]])

                  array([3, 7])

4 argsort

argsort函數返回的是數組值從小到大的索引值

>>> x = np.array([3, 1, 2])

>>> np.argsort(x)

array([1, 2, 0])

 

>>> x = np.array([[0, 3], [2, 2]])
>>> x
array([[0, 3],
[2, 2]])

>>> np.argsort(x, axis=0) #按列排序
array([[0, 1],
[1, 0]])

>>> np.argsort(x, axis=1) #按行排序
array([[0, 1],
[0, 1]])

 

>>> x = np.array([3, 1, 2])
>>> np.argsort(x) #按升序排列
array([1, 2, 0])
>>> np.argsort(-x) #按降序排列
array([0, 2, 1])

>>> x[np.argsort(x)] #通過索引值排序後的數組
array([1, 2, 3])
>>> x[np.argsort(-x)]
array([3, 2, 1])
 

二、

書中第一個程序的代碼:

from numpy import *
import operator

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

group,labels = createDataSet()


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
    sortedDisIndicies = distances.argsort()
    classCount = {}
    print(sortedDisIndicies)
    for i in range(k):
        voteIlabel = labels[sortedDisIndicies[i]]
        classCount[voteIlabel] = classCount.get(voteIlabel,0) + 1
    sortedClassCount = sorted(classCount.items(), key=operator.itemgetter(1), reverse=True)
    return sortedClassCount[0][0]


print(classify0([0,0],group,labels,3))

書中有一處 classCount.iteritems(),報錯,將其換成 classCount.items() 

原因是:iteritems是爲python2環境中dict的函數,我用的python3.6

 

三、

關於數據,鏈接:https://pan.baidu.com/s/1JcwnwBitChL01_sJnfb8CA 
提取碼:sx8x

四、

在約會網站預測函數代碼中 raw_input在python3中已經不存在

Python3將raw_input和input進行整合成了input....去除了raw_input()函數....

其接受任意輸入, 將所有輸入默認爲字符串處理,並返回字符串類型

percentTats = float(input("percentage of time spent playing video games?"))

五、

KNN算法在數據量很大的時候,效率較低。爲了改進,《統計學習方法》中對應的章節有kd樹方法。

 

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