Numpy入門

1 、Jupiter基本操作

常用快捷鍵

代碼執(zhí)行:control+enter,alt+enter執(zhí)行并再開始新的一行。

shift+ tab 查看函數(shù)的具體信息

綠色:編輯狀態(tài),enter

藍(lán)色:命令狀態(tài),esc

命令狀態(tài)下,按m是由代碼模式轉(zhuǎn)換成markdown模式,按y則是由markdown模式轉(zhuǎn)換成代碼模式。

命令狀態(tài)下:b是向下插入一行,a是向上插入一行。

2、初識(shí)Numpy

2.1 Numpy是什么?

numpy:numeric python (數(shù)字化的python),是python中的數(shù)值計(jì)算的基礎(chǔ)包。大部分提供科學(xué)計(jì)算的包都依賴于numpy。

2.2 Numpy 的特點(diǎn)

功能強(qiáng)大的N維數(shù)組對(duì)象。

ndarray支持矢量化運(yùn)算,不需要循環(huán),可以節(jié)省時(shí)間和空間。

實(shí)現(xiàn)線性代數(shù)、隨機(jī)數(shù)生成以及傅里葉變換。

用C、C++等其它的代碼編寫的C API。

利器1:Ndarray

numpy中最重要的一個(gè)形式叫ndarray n 意為是n個(gè) d dimension 維度 array 數(shù)組

利器2:切片和索引

ndarray對(duì)象的內(nèi)容可以通過索引或切片來訪問和修改,與 Python 中 list 的切片操作一樣。ndarray 數(shù)組可以基于 0 - n 的下標(biāo)進(jìn)行索引,切片對(duì)象可以通過內(nèi)置的 slice 函數(shù),并設(shè)置 start, stop 及 step 參數(shù)進(jìn)行,從原數(shù)組中切割出一個(gè)新數(shù)組。

2.3 Numpy 數(shù)組

ndarray(N 維數(shù)組類型)是NumPy 中定義的最重要的對(duì)象,它是描述相同類型的元素集合。ndarray 中的每個(gè)元素都是數(shù)據(jù)類型對(duì)象(dtype)的對(duì)象。ndarray 中的每個(gè)元素在內(nèi)存中使用相同大小的塊。

numpy.array(object,?dtype=None,?copy=True,?order='K',?subok=False,?ndmin=0)

參數(shù)描述


2.3.1 Numpy數(shù)組屬性

NumPy 數(shù)組的維度(又稱維數(shù))稱為秩(rank),一維數(shù)組的秩為 1,二維數(shù)組的秩為 2,以此類推。每一個(gè)線性的數(shù)組稱為是一個(gè)軸(axis,也就是維度(dimensions。


2.4 Numpy 數(shù)據(jù)類型


3、今天涉及的線代

3.1 基礎(chǔ)概念

標(biāo)量:一個(gè)標(biāo)量就是一個(gè)單獨(dú)的數(shù),一般用小寫的的變量名稱表示。

向量:一個(gè)向量就是一列數(shù),這些數(shù)是有序排列的。用過次序中的索引,我們可以確定每個(gè)單獨(dú)的數(shù)。向量看作空間中的點(diǎn),每個(gè)元素是不同的坐標(biāo)軸上的坐標(biāo)。

矩陣:矩陣是二維數(shù)組,其中的每一個(gè)元素被兩個(gè)索引而非一個(gè)所確定。

張量:幾何代數(shù)中定義的張量是基于向量和矩陣的推廣,通俗一點(diǎn)理解的話,我們可以將標(biāo)量視為零階張量,矢量視為一階張量,那么矩陣就是二階張量。 例如,可以將任意一張彩色圖片表示成一個(gè)三階張量,三個(gè)維度分別是圖片的高度、寬度和色彩數(shù)據(jù)。

秩:秩是線性代數(shù)術(shù)語,在線性代數(shù)中,一個(gè)矩陣A的列秩是 A線性無關(guān)的縱列的極大數(shù)目。類似地,行秩是 A的線性無關(guān)的橫行的極大數(shù)目。

矩陣的列秩和行秩總是相等的,因此它們可以簡(jiǎn)單地稱作矩陣 A的秩。通常表示為 rk(A) 或 rank A。

3.2運(yùn)算規(guī)則(自己去網(wǎng)上找更清晰)

3.2.1 向量的運(yùn)算

3.2.2 矩陣的運(yùn)算

3.2.3 張量的運(yùn)算

4、Numpy 數(shù)組的基本操作

1、Numpy 數(shù)組的基本操作

1.1、索引

一維與列表完全一致

li = [[1,2,3,],[4,5,6]]

li[1][0] ? ? ? ? ? ? ? ? #結(jié)果為4

import numpy as np

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

? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? [4, 5, 6]])

arr[1,0]/arr[1][0] ? =======>結(jié)果為4

array支持list和tuple類型的索引

#arr[y,x]

arr[1,0]

?

arr[[1,1,1]] ==========》array([[4,?5,?6],

[4,?5,?6],

[4,?5,?6]])

arr[[1,0,1],[1,2,0]] ====>array([5,?3,?4])

|?|

|?|

?行的下標(biāo)列的下標(biāo)?# 行列的下標(biāo)數(shù)目要一致,它取下標(biāo)時(shí)是一個(gè)行 ? ? ? ? ? 一個(gè)列作為一組然后再去取值的。

1.2、重設(shè)形狀

reshape 可以在不改變數(shù)組數(shù)據(jù)的同時(shí),改變數(shù)組的形狀。其中,numpy.reshape() 等效于 ndarray.reshape()。

reshape(a,?newshape,?order='C')

Givesanewshapetoanarraywithoutchangingitsdata.


Parameters

----------

a:?array_like

Arraytobereshaped.

newshape:?intortupleofints

Thenewshapeshouldbecompatiblewiththeoriginalshape.?If

aninteger,?thentheresultwillbea1-Darrayofthatlength.

Oneshapedimensioncanbe-1.Inthiscase,?thevalueis

inferredfromthelengthofthearrayandremainingdimensions.

order: {'C',?'F',?'A'},?optional

Readtheelementsof`a`?usingthisindexorder,?andplacethe

elementsintothereshapedarrayusingthisindexorder.'C'

meanstoread/writetheelementsusingC-likeindexorder,

withthelastaxisindexchangingfastest,?backtothefirst

axisindexchangingslowest.?'F'meanstoread/writethe

elementsusingFortran-likeindexorder,?withthefirstindex

changingfastest,?andthelastindexchangingslowest.?Notethat

the'C'and'F'optionstakenoaccountofthememorylayoutof

theunderlyingarray,?andonlyrefertotheorderofindexing.

'A'meanstoread/writetheelementsinFortran-likeindex

orderif`a`?isFortran*contiguous*inmemory,?C-likeorder

otherwise.


Returns

-------

reshaped_array:?ndarray

Thiswillbeanewviewobjectifpossible;?otherwise,?itwill

beacopy.Notethereisnoguaranteeofthe*memorylayout*(C-or

Fortran-contiguous)?ofthereturnedarray.

?

eg:

?>>>a=?np.zeros((10,?2))

?# A transpose makes the array non-contiguous

?>>>b=?a.T

?# Taking a view makes it possible to modify the shape without modifying

?# the initial object.

?>>>c=?b.view()

?>>>c.shape= (20)

?AttributeError:?incompatibleshapeforanon-contiguousarray


The`order`?keywordgivestheindexorderingbothfor*fetching*thevalues

from`a`,?andthen*placing*thevaluesintotheoutputarray.

Forexample,?let's say you have an array:


>>>a=?np.arange(6).reshape((3,?2))

>>>a

array([[0,?1],

[2,?3],

[4,?5]])


Youcanthinkofreshapingasfirstravelingthearray(usingthegiven

indexorder),?theninsertingtheelementsfromtheraveledarrayintothe

newarrayusingthesamekindofindexorderingaswasusedforthe

raveling.


>>>np.reshape(a, (2,?3))?# C-like index ordering

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

[3,?4,?5]])

>>>np.reshape(np.ravel(a), (2,?3))?# equivalent to C ravel then C reshape

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

[3,?4,?5]])

>>>np.reshape(a, (2,?3),?order='F')?# Fortran-like index ordering

array([[0,?4,?3],

[2,?1,?5]])

>>>np.reshape(np.ravel(a,?order='F'), (2,?3),?order='F')

array([[0,?4,?3],

[2,?1,?5]])


Examples

--------

>>>a=?np.array([[1,2,3], [4,5,6]])

>>>np.reshape(a,?6)

array([1,?2,?3,?4,?5,?6])

>>>np.reshape(a,?6,?order='F')

array([1,?4,?2,?5,?3,?6])


>>>np.reshape(a, (3,-1))?# the unspecified value is inferred to be 2

array([[1,?2],

[3,?4],

[5,?6]])

importmatplotlib.pyplotasplt

cat=?plt.imread('cat.jpg')

cat.shape=====>(456,?730,?3)====>元素個(gè)數(shù):456*730*3=998640

#圖片的形狀進(jìn)行改變

#形狀可以改變,但是元素的總量不能改變

#二維的時(shí)黑白圖片,透光率0時(shí)黑的,255時(shí)白的

#a.reshape(shape, order='C') newshape : int or tuple of ints

plt.imshow(cat.reshape(456,730*3),cmap='gray')

(456,?2190)=====>456*2190=998640

#在形狀改變中 -1 代表的是剩余的元素總和

cat.reshape(cat.shape[0],-1).shape

#將數(shù)組展開成一維

cat.reshape(-1)

#把數(shù)組轉(zhuǎn)換成 多行一列

cat.reshape(-1,1).shape

1.3.1 數(shù)組展開

ravel 的目的是將任意形狀的數(shù)組扁平化,變?yōu)?1 維數(shù)組。ravel 方法如下:

不管是幾維的數(shù)組都會(huì)變成1維的數(shù)據(jù)

cat.ravel()

結(jié)果為:

array([231,?186,?131, ...,?188,95,62],?dtype=uint8)

1.3.2 級(jí)聯(lián)

np.concatenate() 級(jí)聯(lián)需要注意的點(diǎn):

級(jí)聯(lián)的參數(shù)是列表:一定要加中括號(hào)或小括號(hào)

維度必須相同

形狀相符

【重點(diǎn)】級(jí)聯(lián)的方向默認(rèn)是shape這個(gè)tuple的第一個(gè)值所代表的維度方向

可通過axis參數(shù)改變級(jí)聯(lián)的方向,默認(rèn)為0, (0表示列相連,行發(fā)生改變,表示的Y軸的事情,1表示列相連,列發(fā)生改變,X軸的事情)

cat2 = cat[:,:,::-1]

#檢查形狀

cat.shape,cat2.shape ======》((456, 730, 3), (456, 730, 3))

#第一個(gè)參數(shù)是序列數(shù)據(jù)類型

#第二個(gè)參數(shù)是拼接的方向axis=0代表列拼接

plt.imshow(np.concatenate([cat,cat2],axis=0))

結(jié)果如下圖:


cat在上,cat2在下的上下拼接。

1.3.3? numpy.[hstack|vstack]

堆 做級(jí)聯(lián)

分別代表水平級(jí)聯(lián)與垂直級(jí)聯(lián),填入的參數(shù)必須被小括號(hào)或中括號(hào)包裹

vertical垂直的 horizontal水平的 stack層積

這兩個(gè)函數(shù)的值也是一個(gè)list或tuple

1.3.4 副本

所有賦值運(yùn)算不會(huì)為ndarray的任何元素創(chuàng)建副本。對(duì)賦值后的對(duì)象的操作也對(duì)原來的對(duì)象生效。

可使用ndarray.copy()函數(shù)創(chuàng)建副本

1.3.5 ndarray的聚合函數(shù)

1. 累加np.sum

ndarray.sum(axis),axis不寫則為所有的元素求和,為0表示行求和,1表示列求和

axis是軸的方向

2. 最大最小值:nd.max/ nd.min

#列中的最大值

A.max(axis=0)

3.平均值:nd.mean()

#行方向求平均值

A.mean(axis=1)

灰度化

cat.shape

#彩色圖片去除RGB就會(huì)變成黑白照片

#圖片的行列不能相加

plt.imshow(cat.max(axis=-1),cmap='gray')

#(456, 730, 3) 456:0 ? 730:1 ? 3:2 (-1代表最后一個(gè))?

plt.imshow(cat.min(axis=-1),cmap='gray')

plt.imshow(cat.mean(axis=-1),cmap='gray')#實(shí)際中會(huì)用這個(gè)灰度化

4.其他聚合操作

FunctionNameNaN-safeVersionDescription

np.sumnp.nansumComputesumofelements

np.prodnp.nanprodComputeproductofelements

np.meannp.nanmeanComputemeanofelements

np.stdnp.nanstdComputestandarddeviation

np.varnp.nanvarComputevariance

np.minnp.nanminFindminimumvalue

np.maxnp.nanmaxFindmaximumvalue

np.argminnp.nanargminFindindexofminimumvalue找到最小數(shù)的下標(biāo)

np.argmaxnp.nanargmaxFindindexofmaximumvalue找到最大數(shù)的下標(biāo)

np.mediannp.nanmedianComputemedianofelements

np.percentilenp.nanpercentileComputerank-basedstatisticsofelements

np.anyN/AEvaluatewhetheranyelementsaretrue

np.allN/AEvaluatewhetherallelementsaretrue

np.powersquare

np.argwhere(nd1<0)

np.bincount計(jì)數(shù)

np.argsort()返回排序后的下標(biāo)

帶有nan前綴的函數(shù)都不會(huì)計(jì)算nan

帶有arg的函數(shù)返回的是元素的下標(biāo)

1.4、軸移動(dòng)

moveaxis 可以將數(shù)組的軸移動(dòng)到新的位置。其方法如下:

numpy.moveaxis(a,?source,?destination)

其中:

a:數(shù)組。

source:要移動(dòng)的軸的原始位置。

destination:要移動(dòng)的軸的目標(biāo)位置。

1.5、軸交換

和 moveaxis 不同的是,swapaxes 可以用來交換數(shù)組的軸。其方法如下:

numpy.swapaxes(a,?axis1,?axis2)?

其中:

a:數(shù)組。

axis1:需要交換的軸 1 位置。

axis2:需要與軸 1 交換位置的軸 1 位置。

moveaxis是在指定位置后面插入

而s...是直接交換,它倆都是一次只能換一次

1.6、數(shù)組轉(zhuǎn)置

4.5 數(shù)組轉(zhuǎn)置

transpose 類似于矩陣的轉(zhuǎn)置,它可以將 2 維數(shù)組的水平軸和垂直交換。其方法如下:

numpy.transpose(a, axes=None)?

其中:

a:數(shù)組。

axis:該值默認(rèn)為 none,表示轉(zhuǎn)置。如果有值,那么則按照值替換軸。

1.7、數(shù)組'循環(huán)'

數(shù)組元素的循環(huán)

tile 與 repeat沒啥意思

np.tile([[1,2,3],[4,5,6]],3)

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

? ? ? [4, 5, 6, 4, 5, 6, 4, 5, 6]])

np.repeat([[2,1,3],[4,5,6]],3,axis=0)

array([[2, 1, 3],

? ? ? [2, 1, 3],

? ? ? [2, 1, 3],

? ? ? [4, 5, 6],

? ? ? [4, 5, 6],

? ? ? [4, 5, 6]])

2、ndarray的矩陣操作

下面??代碼自己填呀

運(yùn)算時(shí)注意操作對(duì)象的行列是否一致問題?。。。?/p>

2.1 基本矩陣操作

加減乘除

1、np.add() 求和

2、np.subtract()相減

3、np.multiply() 乘積

4、np.divide()相除

5、矩陣的點(diǎn)積 np.dot()

2.2 不同維度之間的運(yùn)算

2.2.1 矩陣和向量之間的運(yùn)算

矩陣乘以向量會(huì)降維

2.2.2 三維張量和矩陣(假設(shè)這個(gè)矩陣叫A)之間的點(diǎn)積

也會(huì)降維

張量和矩陣的運(yùn)算 相當(dāng)于? 把每一個(gè)矩陣和A.T矩陣做一個(gè)點(diǎn)積

2.2.3 三維張量和向量運(yùn)算

會(huì)降維

3、經(jīng)典排序的數(shù)組中的實(shí)現(xiàn)

冒泡,選擇,插入,希爾,堆,歸并,快速,基數(shù)

反面意義的:冒泡,選擇,復(fù)雜度高 O(n^2) 正面意義的:快速,堆,歸并 O(n*log2(n))

3.2 實(shí)現(xiàn)冒泡排序

arr1 = np.random.randint(0,20,10)

for j in range(len(arr1)-1):

? ? for i in range(0,len(arr1)-1-j):

? ? ? ? if arr1[i] > arr1[i+1]:

? ? ? ? ? ? arr1[i],arr1[i+1] = arr1[i+1],arr1[i]

3.2 實(shí)現(xiàn)快速排序

def quickSort(a, left, right):

? ? if left>right:

? ? ? ? return -1

? ? temp=a[left]

? ? i=left

? ? j=right

? ? while i!=j:

? ? ? ? while a[j]>=temp and i<j:

? ? ? ? ? ? j-=1

? ? ? ? while a[i]<=temp and i<j:

? ? ? ? ? ? i+=1

? ? ? ? if i<j:

? ? ? ? ? ? a[i],a[j]=a[j],a[i]

? ? a[left]=a[i]

? ? a[i]=temp? ?

? ? quickSort(a,left,i-1)

? ? quickSort(a,i+1,right)


arr2 = np.random.randint(12,64,10)

quickSort(arr2,0,arr2.shape[0]-1)

arr2

3.3 實(shí)現(xiàn)希爾排序

arr3 = np.random.randint(10,100,10)

def shellSort(arr,n):

? ? # 設(shè)定步長(zhǎng)

? ? step = int(n/2)

? ? while step > 0:

? ? ? ? for i in range(step, n):

? ? ? ? ? ? while i >= step and arr[i-step] > arr[i]:

? ? ? ? ? ? ? ? arr[i], arr[i-step] = arr[i-step], arr[i]

? ? ? ? ? ? ? ? i -= step

? ? ? ? step = int(step/2)

? ? return arr

shellSort(arr3,arr3.shape[0])

3.4 實(shí)現(xiàn)插入排序

def insertionSort(arr,n):

? ? for i in range(1, n):


? ? ? ? k = arr[i]


? ? ? ? j = i-1

? ? ? ? while j >=0 and k < arr[j] :

? ? ? ? ? ? ? ? arr[j+1] = arr[j]

? ? ? ? ? ? ? ? j -= 1

? ? ? ? arr[j+1] = k

? ? return arr

arr3=np.random.randint(10,60,10)

insertionSort(arr3,arr3.shape[0])

3.5? 實(shí)現(xiàn)歸并排序

#列表

def mergeSort(arr):

? ? mid = len(arr) // 2

? ? n = len(arr)

? ? if n <= 1:

? ? ? ? return arr

? ? lft = mergeSort(arr[:mid])

? ? rgt = mergeSort(arr[mid:])

? ? res = []

? ? while lft and rgt:

? ? ? ? if lft[-1] >= rgt[-1]:

? ? ? ? ? ? res.append(lft.pop())

? ? ? ? else:

? ? ? ? ? ? res.append(rgt.pop())

? ? res.reverse()

? ? return lft + rgt + res

#數(shù)組,這個(gè)有點(diǎn)問題還沒解決哦,啊啊啊

def mergeSort(arr):

? ? n = arr.shape[0]

? ? mid = int(n // 2)

? ? if n <= 1:

? ? ? ? return arr

? ? lft = mergeSort(arr[:mid])

? ? print(lft)

? ? rgt = mergeSort(arr[mid:])

? ? print(rgt)

? ? res = []

? ? while lft.shape[0] and rgt.shape[0]:

? ? ? ? if lft[-1] >= rgt[-1]:

? ? ? ? ? ? res.append(lft[-1])

? ? ? ? ? ? lft = lft[:-1]

? ? ? ? else:

? ? ? ? ? ? res.append(rgt[-1])

? ? ? ? ? ? rgt = rgt[:-1]

? ? a = res[::-1]

? ? res = np.array(a)

? ? arr_s = np.hstack((lft, rgt, res))

? ? return arr_s

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容