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芋簿、初識Numpy
2.1 Numpy是什么峡懈?
numpy:numeric python (數(shù)字化的python),是python中的數(shù)值計算的基礎(chǔ)包。大部分提供科學(xué)計算的包都依賴于numpy与斤。
2.2 Numpy 的特點
功能強(qiáng)大的N維數(shù)組對象肪康。
ndarray支持矢量化運算荚恶,不需要循環(huán),可以節(jié)省時間和空間磷支。
實現(xiàn)線性代數(shù)裆甩、隨機(jī)數(shù)生成以及傅里葉變換。
用C齐唆、C++等其它的代碼編寫的C API嗤栓。
利器1:Ndarray
numpy中最重要的一個形式叫ndarray n 意為是n個 d dimension 維度 array 數(shù)組
利器2:切片和索引
ndarray對象的內(nèi)容可以通過索引或切片來訪問和修改,與 Python 中 list 的切片操作一樣箍邮。ndarray 數(shù)組可以基于 0 - n 的下標(biāo)進(jìn)行索引茉帅,切片對象可以通過內(nèi)置的 slice 函數(shù),并設(shè)置 start, stop 及 step 參數(shù)進(jìn)行锭弊,從原數(shù)組中切割出一個新數(shù)組堪澎。
2.3 Numpy 數(shù)組
ndarray(N 維數(shù)組類型)是NumPy 中定義的最重要的對象,它是描述相同類型的元素集合味滞。ndarray 中的每個元素都是數(shù)據(jù)類型對象(dtype)的對象樱蛤。ndarray 中的每個元素在內(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,以此類推蚁署。每一個線性的數(shù)組稱為是一個軸(axis)便脊,也就是維度(dimensions)。
2.4 Numpy 數(shù)據(jù)類型
3光戈、今天涉及的線代
3.1 基礎(chǔ)概念
標(biāo)量:一個標(biāo)量就是一個單獨的數(shù)哪痰,一般用小寫的的變量名稱表示。
向量:一個向量就是一列數(shù)久妆,這些數(shù)是有序排列的晌杰。用過次序中的索引,我們可以確定每個單獨的數(shù)筷弦。向量看作空間中的點肋演,每個元素是不同的坐標(biāo)軸上的坐標(biāo)。
矩陣:矩陣是二維數(shù)組奸笤,其中的每一個元素被兩個索引而非一個所確定惋啃。
張量:幾何代數(shù)中定義的張量是基于向量和矩陣的推廣,通俗一點理解的話监右,我們可以將標(biāo)量視為零階張量边灭,矢量視為一階張量,那么矩陣就是二階張量健盒。 例如绒瘦,可以將任意一張彩色圖片表示成一個三階張量称簿,三個維度分別是圖片的高度、寬度和色彩數(shù)據(jù)惰帽。
秩:秩是線性代數(shù)術(shù)語憨降,在線性代數(shù)中,一個矩陣A的列秩是 A的線性無關(guān)的縱列的極大數(shù)目该酗。類似地授药,行秩是 A的線性無關(guān)的橫行的極大數(shù)目。
矩陣的列秩和行秩總是相等的呜魄,因此它們可以簡單地稱作矩陣 A的秩悔叽。通常表示為 rk(A) 或 rank A。
3.2運算規(guī)則(自己去網(wǎng)上找更清晰)
3.2.1 向量的運算
3.2.2 矩陣的運算
3.2.3 張量的運算
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)時是一個行 ? ? ? ? ? 一個列作為一組然后再去取值的趟庄。
1.2、重設(shè)形狀
reshape 可以在不改變數(shù)組數(shù)據(jù)的同時伪很,改變數(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)====>元素個數(shù):456*730*3=998640
#圖片的形狀進(jìn)行改變
#形狀可以改變虑鼎,但是元素的總量不能改變
#二維的時黑白圖片辱匿,透光率0時黑的键痛,255時白的
#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ù)組都會變成1維的數(shù)據(jù)
cat.ravel()
結(jié)果為:
array([231,?186,?131, ...,?188,95,62],?dtype=uint8)
1.3.2 級聯(lián)
np.concatenate() 級聯(lián)需要注意的點:
級聯(lián)的參數(shù)是列表:一定要加中括號或小括號
維度必須相同
形狀相符
【重點】級聯(lián)的方向默認(rèn)是shape這個tuple的第一個值所代表的維度方向
可通過axis參數(shù)改變級聯(lián)的方向絮短,默認(rèn)為0, (0表示列相連,行發(fā)生改變,表示的Y軸的事情,1表示列相連,列發(fā)生改變,X軸的事情)
cat2 = cat[:,:,::-1]
#檢查形狀
cat.shape,cat2.shape ======》((456, 730, 3), (456, 730, 3))
#第一個參數(shù)是序列數(shù)據(jù)類型
#第二個參數(shù)是拼接的方向axis=0代表列拼接
plt.imshow(np.concatenate([cat,cat2],axis=0))
結(jié)果如下圖:
cat在上昨忆,cat2在下的上下拼接丁频。
1.3.3? numpy.[hstack|vstack]
堆 做級聯(lián)
分別代表水平級聯(lián)與垂直級聯(lián),填入的參數(shù)必須被小括號或中括號包裹
vertical垂直的 horizontal水平的 stack層積
這兩個函數(shù)的值也是一個list或tuple
1.3.4 副本
所有賦值運算不會為ndarray的任何元素創(chuàng)建副本。對賦值后的對象的操作也對原來的對象生效邑贴。
可使用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就會變成黑白照片
#圖片的行列不能相加
plt.imshow(cat.max(axis=-1),cmap='gray')
#(456, 730, 3) 456:0 ? 730:1 ? 3:2 (-1代表最后一個)?
plt.imshow(cat.min(axis=-1),cmap='gray')
plt.imshow(cat.mean(axis=-1),cmap='gray')#實際中會用這個灰度化
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計數(shù)
np.argsort()返回排序后的下標(biāo)
帶有nan前綴的函數(shù)都不會計算nan
帶有arg的函數(shù)返回的是元素的下標(biāo)
1.4拢驾、軸移動
moveaxis 可以將數(shù)組的軸移動到新的位置奖磁。其方法如下:
numpy.moveaxis(a,?source,?destination)
其中:
a:數(shù)組。
source:要移動的軸的原始位置繁疤。
destination:要移動的軸的目標(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的矩陣操作
下面??代碼自己填呀
運算時注意操作對象的行列是否一致問題@D虮场!捶惜!
2.1 基本矩陣操作
加減乘除
1田藐、np.add() 求和
2、np.subtract()相減
3吱七、np.multiply() 乘積
4汽久、np.divide()相除
5、矩陣的點積 np.dot()
2.2 不同維度之間的運算
2.2.1 矩陣和向量之間的運算
矩陣乘以向量會降維
2.2.2 三維張量和矩陣(假設(shè)這個矩陣叫A)之間的點積
也會降維
張量和矩陣的運算 相當(dāng)于? 把每一個矩陣和A.T矩陣做一個點積
2.2.3 三維張量和向量運算
會降維
3踊餐、經(jīng)典排序的數(shù)組中的實現(xiàn)
冒泡景醇,選擇,插入吝岭,希爾三痰,堆,歸并窜管,快速散劫,基數(shù)
反面意義的:冒泡,選擇幕帆,復(fù)雜度高 O(n^2) 正面意義的:快速获搏,堆,歸并 O(n*log2(n))
3.2 實現(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 實現(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 實現(xiàn)希爾排序
arr3 = np.random.randint(10,100,10)
def shellSort(arr,n):
? ? # 設(shè)定步長
? ? 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 實現(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? 實現(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ù)組蜓肆,這個有點問題還沒解決哦颜凯,啊啊啊
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