機器學(xué)習(xí)實戰(zhàn) chapter2 筆記

Numpy包

mat( )函數(shù)可以將數(shù)組轉(zhuǎn)化為矩陣

randMat=mat(random.rand(4,4))

.I表示求逆

randMat.I

from numpy import *

import operator

tile用法:

Signature:?tile(A,?reps)Docstring:

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)``.

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).

Note?:?Although?tile?may?be?used?for?broadcasting,?it?is?strongly

recommended?to?use?numpy's?broadcasting?operations?and?functions.

Parameters

----------

A?:?array_like

The?input?array.

reps?:?array_like

The?number?of?repetitions?of?`A`?along?each?axis.

Returns

-------

c?:?ndarray

The?tiled?output?array.

See?Also

--------

repeat?:?Repeat?elements?of?an?array.

broadcast_to?:?Broadcast?an?array?to?a?new?shape

Examples

--------

>>>?a?=?np.array([0,?1,?2])

>>>?np.tile(a,?2)

array([0,?1,?2,?0,?1,?2])

>>>?np.tile(a,?(2,?2))

array([[0,?1,?2,?0,?1,?2],

[0,?1,?2,?0,?1,?2]])

>>>?np.tile(a,?(2,?1,?2))

array([[[0,?1,?2,?0,?1,?2]],

[[0,?1,?2,?0,?1,?2]]])

>>>?b?=?np.array([[1,?2],?[3,?4]])

>>>?np.tile(b,?2)

array([[1,?2,?1,?2],

[3,?4,?3,?4]])

>>>?np.tile(b,?(2,?1))

array([[1,?2],

[3,?4],

[1,?2],

[3,?4]])

>>>?c?=?np.array([1,2,3,4])

>>>?np.tile(c,(4,1))

array([[1,?2,?3,?4],

[1,?2,?3,?4],

[1,?2,?3,?4],

[1,?2,?3,?4]])

File:? ? ? d:\anaconda3\lib\site-packages\numpy\lib\shape_base.py

Type:? ? ? function

argsort用法:

Signature:?argsort(a,?axis=-1,?kind='quicksort',?order=None)Docstring:

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.

Parameters

----------

a?:?array_like

Array?to?sort.

axis?:?int?or?None,?optional

Axis?along?which?to?sort.? The?default?is?-1?(the?last?axis).?If?None,

the?flattened?array?is?used.

kind?:?{'quicksort',?'mergesort',?'heapsort'},?optional

Sorting?algorithm.

order?:?str?or?list?of?str,?optional

When?`a`?is?an?array?with?fields?defined,?this?argument?specifies

which?fields?to?compare?first,?second,?etc.? A?single?field?can

be?specified?as?a?string,?and?not?all?fields?need?be?specified,

but?unspecified?fields?will?still?be?used,?in?the?order?in?which

they?come?up?in?the?dtype,?to?break?ties.

Returns

-------

index_array?:?ndarray,?int

Array?of?indices?that?sort?`a`?along?the?specified?axis.

If?`a`?is?one-dimensional,?``a[index_array]``?yields?a?sorted?`a`.

See?Also

--------

sort?:?Describes?sorting?algorithms?used.

lexsort?:?Indirect?stable?sort?with?multiple?keys.

ndarray.sort?:?Inplace?sort.

argpartition?:?Indirect?partial?sort.

Notes

-----

See?`sort`?for?notes?on?the?different?sorting?algorithms.

As?of?NumPy?1.4.0?`argsort`?works?with?real/complex?arrays?containing

nan?values.?The?enhanced?sort?order?is?documented?in?`sort`.

Examples

--------

One?dimensional?array:

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

>>>?np.argsort(x)

array([1,?2,?0])

Two-dimensional?array:

>>>?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]])

Sorting?with?keys:

>>>?x?=?np.array([(1,?0),?(0,?1)],?dtype=[('x',?'

>>>?x

array([(1,?0),?(0,?1)],

dtype=[('x',?'

>>>?np.argsort(x,?order=('x','y'))

array([1,?0])

>>>?np.argsort(x,?order=('y','x'))

array([0,?1])

File:? ? ? d:\anaconda3\lib\site-packages\numpy\core\fromnumeric.py

Type:? ? ? function

?operator.itemgetter:

Init?signature:?operator.itemgetter(self,?/,?*args,?**kwargs)Docstring:

itemgetter(item,?...)?-->?itemgetter?object

Return?a?callable?object?that?fetches?the?given?item(s)?from?its?operand.

After?f?=?itemgetter(2),?the?call?f(r)?returns?r[2].

After?g?=?itemgetter(2,?5,?3),?the?call?g(r)?returns?(r[2],?r[5],?r[3])

File:? ? ? ? ? ?d:\anaconda3\lib\operator.py

Type:? ? ? ? ? ?type

sorted:

Signature:?sorted(iterable,?/,?*,?key=None,?reverse=False)Docstring:

Return?a?new?list?containing?all?items?from?the?iterable?in?ascending?order.

A?custom?key?function?can?be?supplied?to?customize?the?sort?order,?and?the

reverse?flag?can?be?set?to?request?the?result?in?descending?order.

Type:? ? ? builtin_function_or_method

?classCount={}

花括號表示字典

? ? for i in range(3):

? ? ? ? voteIlabel = labels[sortedDistIndicies[i]]

? ? ? ? classCount[voteIlabel] = classCount.get(voteIlabel,0)+1

AttributeError: 'dict' object has no attribute 'iteritems'

Python3.5中:iteritems變?yōu)閕tems

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

文件讀取

def file2matrix(filename):

? ? fr = open(filename)

? ? arrayOlines=fr.readlines()

? ? numberOfLines = len(arrayOlines)

? ? returnMat = zeros((numberOfLines,3))

? ? classLabelVector = []

? ? index = 0

? ? for line in arrayOlines:

? ? ? ? line = line.strip()

? ? ? ? listFromLine = line.split('\t')

? ? ? ? returnMat[index,:]=listFromLine[0:3]

? ? ? ? classLabelVector.append(int(listFromLine[-1]))

? ? ? ? index += 1

? ? return returnMat,classLabelVector

line = line.strip():截掉回車符

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

使用Matplotlib制作原始數(shù)據(jù)的散點圖:

import matplotlib

import matplotlib.pyplot as plt

fig = plt.figure()

ax = fig.add_subplot(111)

ax.scatter(datingDataMat[:,1],datingDataMat[:,2])

plt.show()

=========

ax.scatter(datingDataMat[:,1],datingDataMat[:,2],15.0*array(datingLabels),15.0*array(datingLabels))

使區(qū)分

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

def autoNorm(dataSet):

? ? minVals = dataSet.min(0)

? ? maxVals = dataSet.max(0)

? ? ranges = maxVals - minVals

? ? normDataSet = zeros(shape(dataSet))

? ? m = dataSet.shape[0]

? ? normDataSet = dataSet - tile(minVals, (m,1))

? ? normDataSet = normDataSet/tile(ranges,(m,1))

? ? return normDataSet,ranges,minVals

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

normDataSet = normDataSet/tile(ranges,(m,1))不是矩陣除法,在NumPy庫中紊搪,矩陣除法需要使用函數(shù)linalg.solve(matA,matB)

========

reload:

import importlib

importlib.reload(kNN)

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

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子疫诽,更是在濱河造成了極大的恐慌,老刑警劉巖决侈,帶你破解...
    沈念sama閱讀 218,607評論 6 507
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件史飞,死亡現(xiàn)場離奇詭異,居然都是意外死亡瓷翻,警方通過查閱死者的電腦和手機聚凹,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,239評論 3 395
  • 文/潘曉璐 我一進店門割坠,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人妒牙,你說我怎么就攤上這事彼哼。” “怎么了湘今?”我有些...
    開封第一講書人閱讀 164,960評論 0 355
  • 文/不壞的土叔 我叫張陵敢朱,是天一觀的道長。 經(jīng)常有香客問我摩瞎,道長蔫饰,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,750評論 1 294
  • 正文 為了忘掉前任愉豺,我火速辦了婚禮篓吁,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘蚪拦。我一直安慰自己杖剪,他們只是感情好,可當(dāng)我...
    茶點故事閱讀 67,764評論 6 392
  • 文/花漫 我一把揭開白布驰贷。 她就那樣靜靜地躺著盛嘿,像睡著了一般。 火紅的嫁衣襯著肌膚如雪括袒。 梳的紋絲不亂的頭發(fā)上次兆,一...
    開封第一講書人閱讀 51,604評論 1 305
  • 那天,我揣著相機與錄音锹锰,去河邊找鬼芥炭。 笑死,一個胖子當(dāng)著我的面吹牛恃慧,可吹牛的內(nèi)容都是我干的园蝠。 我是一名探鬼主播,決...
    沈念sama閱讀 40,347評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼痢士,長吁一口氣:“原來是場噩夢啊……” “哼彪薛!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起怠蹂,我...
    開封第一講書人閱讀 39,253評論 0 276
  • 序言:老撾萬榮一對情侶失蹤善延,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后城侧,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體易遣,經(jīng)...
    沈念sama閱讀 45,702評論 1 315
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,893評論 3 336
  • 正文 我和宋清朗相戀三年赞庶,在試婚紗的時候發(fā)現(xiàn)自己被綠了训挡。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片澳骤。...
    茶點故事閱讀 40,015評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖澜薄,靈堂內(nèi)的尸體忽然破棺而出为肮,到底是詐尸還是另有隱情,我是刑警寧澤肤京,帶...
    沈念sama閱讀 35,734評論 5 346
  • 正文 年R本政府宣布颊艳,位于F島的核電站,受9級特大地震影響忘分,放射性物質(zhì)發(fā)生泄漏棋枕。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,352評論 3 330
  • 文/蒙蒙 一妒峦、第九天 我趴在偏房一處隱蔽的房頂上張望重斑。 院中可真熱鬧,春花似錦肯骇、人聲如沸窥浪。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,934評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽漾脂。三九已至,卻和暖如春胚鸯,著一層夾襖步出監(jiān)牢的瞬間骨稿,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,052評論 1 270
  • 我被黑心中介騙來泰國打工姜钳, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留坦冠,地道東北人。 一個月前我還...
    沈念sama閱讀 48,216評論 3 371
  • 正文 我出身青樓傲须,卻偏偏與公主長得像蓝牲,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子泰讽,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,969評論 2 355

推薦閱讀更多精彩內(nèi)容

  • 機器學(xué)習(xí)實戰(zhàn)之K-近鄰算法(二) 2-1 K-近鄰算法概述 簡單的說,K-近鄰算法采用測量不同特征值之間的距離方法...
    凌岸_ing閱讀 1,698評論 0 6
  • 一.NumPy的引入 標(biāo)準(zhǔn)安裝的Python中用列表(list)保存一組值昔期,可以用來當(dāng)作數(shù)組使用已卸,不過由于列...
    wlj1107閱讀 1,019評論 0 2
  • 最近在寫個性化推薦的論文,經(jīng)常用到Python來處理數(shù)據(jù)硼一,被pandas和numpy中的數(shù)據(jù)選取和索引問題繞的比較...
    shuhanrainbow閱讀 4,559評論 6 19
  • “請大當(dāng)家把二當(dāng)家交出來般贼±⒂矗” 這有些諷刺奥吩。 “你叫我什么?” “大當(dāng)家蕊梧∠己眨” “你讓大當(dāng)家交出二當(dāng)家?” 木昭想了一...
    悟空和孔乙己閱讀 330評論 0 0
  • 我不知道最近為什么心情會這樣的壞旅东,雖然看到葉子在藍色天空印襯下舒展得那么美麗,我還是開心不起來十艾。 秋來了...
    張不識閱讀 545評論 19 8