1. 程式人生 > >《機器學習實戰》(第二章)中函式詳細解析

《機器學習實戰》(第二章)中函式詳細解析

本文是針對《機器學習實戰》內函式的解析。並以頁數呈現。

P19:numpy.tile(A,rep)函式

當rep為數字時,生成一個一維重複rep次的list。

當rep為元組(m,n)時,生成一個m行並且每行重複n次的矩陣。

import numpy as np
a1 = [1,2,3]
a2 = [2,3,4]
b1 = np.tile(a1,1)
b2 = np.tile(a1,(3,2))
b2_1 = np.tile(a2,(3,2))
b2_2 = b2 - b2_1
print("b1:")
print(b1)
print("b2:")
print(b2)
print("b2_2:")
print(b2_2)

b1:
[1 2 3]
b2:
[[1 2 3 1 2 3]
 [1 2 3 1 2 3]
 [1 2 3 1 2 3]]
b2_2:
[[-1 -1 -1 -1 -1 -1]
 [-1 -1 -1 -1 -1 -1]
 [-1 -1 -1 -1 -1 -1]]

P19:sqDiffMat.sum(axis=1)

axis=0表述列  axis=1表述行

P19:distances.argsort()

函式意義:將x中的元素從小到大排列提取其對應的index(索引),然後輸出到y

import numpy as np
x = np.array([-1,-2,-3,1,2,3])
y = x.argsort()
print(y)

[2 1 0 3 4 5]

P19:python字典的dict.get(key,value)

該方法是通過鍵來獲取相應的值,如果相應的鍵不存在則返回None。

預設的返回值在非返回None值情況下會被所得值替代,如果查詢失敗,則返回一個預設值。

import numpy as np
dict = {1:'one',2:'two',3:'three',4:'four'}
print(dict.get(1))
print(dict.get(4,None))
print(dict.get(4,"get"))
print(dict.get(5))
print(dict.get(5,0))

one
four
four
None
0

P19:python 字典的iteritems()函式與itemgetter()函式

items()函式,將一個字典以列表的形式返回,因為字典是無序的,所以返回的列表也是無序的。

iteritems()函式在Python3被廢除,直接使用items()函式代替。

import numpy as np
a_dict = {'1':'one','2':'two'}
b_dict = a_dict.items()
print(type(b_dict))
for i,j in b_dict:
    print(i,j)

<class 'dict_items'>
1 one
2 two

P21:readlines()函式

python中readlines()函式:讀取所有行(直到結束符 EOF)並返回列表,可以使用for...in 結構語句去處理。

如遇到結束符 “EOF” 則返回空字串。

P21:numpy.zeros(shape, dtype=float, order=’C’)

shape:int或ints序列(新陣列的形狀)

dtype:矩陣內部元素型別(預設為float)

order:{‘C’,‘F’}可選,是否在儲存器中以C或Fortran連續(按行或列方式)儲存多維資料。

import numpy as np
from numpy.ma import zeros
a1 = zeros(5)
a2 = zeros((5,3))
a3 = zeros((5,3),dtype=int)
print("a1:")
print(a1)
print("a2:")
print(a2)
print("a3:")
print(a3)


a1:
[0. 0. 0. 0. 0.]
a2:
[[0. 0. 0.]
 [0. 0. 0.]
 [0. 0. 0.]
 [0. 0. 0.]
 [0. 0. 0.]]
a3:
[[0 0 0]
 [0 0 0]
 [0 0 0]
 [0 0 0]
 [0 0 0]]

P21:strip()函式

string.strip(rm)

當rm不為空時,刪除s字串中開頭、結尾處,位於 rm刪除序列的字元

當rm為空時候,預設刪除空白符(包括'\n', '\r',  '\t',  ' ')

P22:returnMatrix[index,:] = listFromLine[0:3]

Matrix[index,:] = list[0:3]意義:將list中0,1,2中的元素賦值給index行中所有的元素

P26:matrix.shape[0]

函式作用:快速讀取矩陣的形狀,使用shape[0]讀取矩陣第一維度的長度