1. 程式人生 > >《機器學習實戰》學習筆記——k近鄰算法

《機器學習實戰》學習筆記——k近鄰算法

eating 元組 切片 文件 維度 mage python str eric

1.numpy中一些函數的用法學習

  • shape()用法:

shape : tuple of ints

The elements of the shape tuple give the lengths of the corresponding array dimensions.。

  shape返回一個元組,依次為各維度的長度。shape[0]:第一維長度,shape[1]:第二維長度。

  技術分享

  • tile()用法:

numpy.tile(A, reps)

Construct an array by repeating A the number of times given by reps.

If reps has length d, the result will have dimension of max(d, A.ndim). (A.ndim表示A矩陣的維度)

If A.ndim < d, A is promoted to be d-dimensional by prepending new axes. So a shape (3,) array is promoted to (1, 3) for 2-D replication, or shape (1, 1, 3) for 3-D replication. If this is not the desired behavior, promote A

to d-dimensions manually before calling this function.

If A.ndim > d, reps is promoted to A.ndim by pre-pending 1’s to it. Thus for an A of shape (2, 3, 4, 5), a reps of (2, 2) is treated as (1, 1, 2, 2).

  tile()用法理解有一點難度。假設reps=(2,3,3), 2、3、3分別代表在第一、二、三個維度的重復次數,通俗來說就是第一、二、三個中括號內的元素。若A的維度小於reps,則增加維度為3;若A的維度大於3(假設為4),則默認reps=(1,2,3,3).

  技術分享

  • numpy.array()的切片

  對於一維數組,切片用法與python相同;對於多維數組(矩陣)來說,A[x1,x2:x3,x4]中x1表示選取第一維度中的下標x1(矩陣就是第x1行),x2表示從第二個維度中下標為x2開始選取,如下:

  技術分享技術分享

  註意:x2不允許單獨出現,即不能出現A[,x2:],否則會報錯。同理,x3表示行下標(第一維),x4表示列下標(第二維)。x3表示選取到哪一行為止(不包含x3),x4表示選取x4這一列。

  技術分享 技術分享

  • argsort()用法

  numpy.argsort(a, axis=-1, kind=‘quicksort‘, order=None)

  Returns the indices that would sort an array.

  Perform an indirect sort along the given axis using the algorithm specified by the kind keyword. It returns an array of indices of the same shape as a that index data along the given axis in sorted order.

  返回一個數組由小到大排序之後的下標。axis表示要比較的維度,默認為最後一個維度。

 

2.python中的一些函數學習

  reload()函數,需要從imp模塊中引入:from imp import reload

  在python3.x後raw_input()重命名為input()

  os模塊中listdir(),列出路徑下所有文件名組成的一個列表。

3.代碼分析(待補充)

《機器學習實戰》學習筆記——k近鄰算法