[Python] 01 - Number and Matrix

故事背景


1、大纲

以下,chapter4 是个概览,以后才是具体讲解。html

 

2、 编译过程

Ref: http://www.dsf.unica.it/~fiore/LearningPython.pdfpython


 

 



 

 

 

 

 

 

3、 四个概念

145/1594linux

Python programs can be decomposed into modules, statements, expressions, and objects, as follows: express

1. Programs are composed of modules. 数组

2. Modules contain statements. app

3. Statements contain expressions. dom

4. Expressions create and process objects.ide

 

4、变量类型

Python’s Core Data Types函数


 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

5、枚举类

From: 使用枚举类post

使用默认值

from enum import Enum
# 定义 Month
= Enum('Month', ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'))
# 遍历
for name, member in Month.__members__.items(): print(name, '=>', member, ',', member.value)

 

自定义值

@unique装饰器能够帮助咱们检查保证没有重复值,这里使用了“类”。

from enum import Enum, unique

@unique
class Weekday(Enum):
    Sun = 0 # Sun的value被设定为0
    Mon = 1
    Tue = 2
    Wed = 3
    Thu = 4
    Fri = 5
    Sat = 6

 

 

 

 

让咱们开始


1、 表达形式

 

   

2、大数

超长显示 

总之,问题不大。

 

Python 3.5.2 |Anaconda custom (64-bit)| (default, Jul 2 2016, 17:53:06)

[GCC 4.4.7 20120313 (Red Hat 4.4.7-1)] on linux

Type "help", "copyright", "credits" or "license" for more information.

 

>>> len(str(2**1000))

302
length

>>> 2**1000

10715086071862673209484250490600018105614048117055336074437503883703510511249361224931983788156958581275946729175531468251871452856923140435984577574698574803934567774824230985421074605062371141877954182153046474983581941267398767559165543946077062914571196477686542167660429831652624386837205668069376
较长

>>> 2**10000 # Are you serious? 

19950631168807583848837421626835850838234968318861924548520089498529438830221946631919961684036194597899331129423209124271556491349413781117593785932096323957855730046793794526765246551266059895520550086918193311542508608460618104685509074866089624888090489894838009253941633257850621568309473902556912388065225096643874441046759871626985453222868538161694315775629640762836880760732228535091641476183956381458969463899410840960536267821064621427333394036525565649530603142680234969400335934316651459297773279665775606172582031407994198179607378245683762280037302885487251900834464581454650557929601414833921615734588139257095379769119277800826957735674444123062018757836325502728323789270710373802866393031428133241401624195671690574061419654342324638801248856147305207431992259611796250130992860241708340807605932320161268492288496255841312844061536738951487114256315111089745514203313820202931640957596464756010405845841566072044962867016515061920631004186422275908670900574606417856951911456055068251250406007519842261898059237118054444788072906395242548339221982707404473162376760846613033778706039803413197133493654622700563169937455508241780972810983291314403571877524768509857276937926433221599399876886660808368837838027643282775172273657572744784112294389733810861607423253291974813120197604178281965697475898164531258434135959862784130128185406283476649088690521047580882615823961985770122407044330583075869039319604603404973156583208672105913300903752823415539745394397715257455290510212310947321610753474825740775273986348298498340756937955646638621874569499279016572103701364433135817214311791398222983845847334440270964182851005072927748364550578634501100852987812389473928699540834346158807043959118985815145779177143619698728131459483783202081474982171858011389071228250905826817436220577475921417653715687725614904582904992461028630081535583308130101987675856234343538955409175623400844887526162643568648833519463720377293240094456246923254350400678027273837755376406726898636241037491410966718557050759098100246789880178271925953381282421954028302759408448955014676668389697996886241636313376393903373455801407636741877711055384225739499110186468219696581651485130494222369947714763069155468217682876200362777257723781365331611196811280792669481887201298643660768551639860534602297871557517947385246369446923087894265948217008051120322365496288169035739121368338393591756418733850510970271613915439590991598154654417336311656936031122249937969999226781732358023111862644575299135758175008199839236284615249881088960232244362173771618086357015468484058622329792853875623486556440536962622018963571028812361567512543338303270029097668650568557157505516727518899194129711337690149916181315171544007728650573189557450920330185304847113818315407324053319038462084036421763703911550639789000742853672196280903477974533320468368795868580237952218629120080742819551317948157624448298518461509704888027274721574688131594750409732115080498190455803416826949787141316063210686391511681774304792596709376
超长

 

 

3、小数

Question:一个比较麻烦的问题,如何解决?

 

print() 函数

数字显示问题,版本变高自动改善,或者经过print做为替代方案。




 

print等价于str,表示:以读者但愿的形式表达出来。

In [92]: decimal.Decimal(str(1/3))
Out[92]: Decimal('0.3333333333333333')

In [93]: decimal.Decimal(1/3)
Out[93]: Decimal('0.333333333333333314829616256247390992939472198486328125')

 

decimal 方法

>>> 1 / 3 # Floating-point (add a .0 in Python 2.X)
0.3333333333333333
>>> (2/3) + (1/2)
1.1666666666666665

>>> import decimal # Decimals: fixed precision >>> d = decimal.Decimal('3.141') >>> d + 1 Decimal('4.141')
>>> decimal.getcontext().prec = 2                    // 精度设置 >>> decimal.Decimal('1.00') / decimal.Decimal('3.00')        // 小数计算 Decimal('0.33')

 

fractions 方法

>>> from fractions import Fraction # Fractions: numerator+denominator
>>> f = Fraction(2, 3)
>>> f + 1
Fraction(5, 3)
>>> f + Fraction(1, 2)
Fraction(7, 6)
In [2]: (2.55).as_integer_ratio()
Out[2]: (2871044762448691, 1125899906842624) # 精算?哈哈~

 

 

4、专业数学计算

四个经常使用专业库

更是有专业的库提供方案 纯数计算,可能有必要单独篇章总结。

import math
import random
import statistics
import numpy as np

  

高数课程

The math module gives access to the underlying C library functions for floating point math:

>>> import math >>> math.cos(math.pi / 4) 0.70710678118654757 >>> math.log(1024, 2) 10.0 

 

统计课程

The random module provides tools for making random selections:

>>> import random >>> random.choice(['apple', 'pear', 'banana']) 'apple' >>> random.sample(range(100), 10) # sampling without replacement [30, 83, 16, 4, 8, 81, 41, 50, 18, 33] >>> random.random() # random float 0.17970987693706186 >>> random.randrange(6) # random integer chosen from range(6) 4 

The statistics module calculates basic statistical properties (the mean, median, variance, etc.) of numeric data:

>>> import statistics >>> data = [2.75, 1.75, 1.25, 0.25, 0.5, 1.25, 3.5] >>> statistics.mean(data) 1.6071428571428572 >>> statistics.median(data) 1.25 >>> statistics.variance(data) 1.3720238095238095

 

 

 

numpy - Quickstart tutorial


Ref: https://docs.scipy.org/doc/numpy/user/quickstart.html

 

1、矩阵 (Matrix) 

初始化

NumPy’s array class is called ndarray. 若干例子:

# 初始化

>>> import numpy as np

# (1) 描述型初始化
>>> a = np.arange(15).reshape(3, 5) >>> a array([[ 0, 1, 2, 3, 4], [ 5, 6, 7, 8, 9], [10, 11, 12, 13, 14]])

# (2) 直接赋值初始化
a = np.array([2,3,4])            # 一维
b = np.array([(1.5,2,3), (4,5,6)]) # 多维

# (3) 制定初始化
np.zeros( (3,4) )               # 多维
np.ones( (2,3,4), dtype=np.int16 ) # 多维
np.empty( (2,3) ) # 多维
np.arange( 10, 30, 5 ) # 一维:均匀点-间隔法
np.linspace( 0, 2, 9 ) # 一维:均匀点-个数法
See also
numpy.random.randnumpy.random.randn
fromfunctionfromfile 

------------------------------------
# 形状和维度
>>>a.shape (3, 5) >>>a.ndim 2

>>> a.size 15

------------------------------------
# 内部成员属性
>>> type(a)
<type 'numpy.ndarray'>

>>> a.dtype.name
'int64'

>>> a.itemsize
8

 

Basic Operations

知足基本的矩阵性质,略。

>>> import numpy as np
>>> a = np.arange(15).reshape(3,5)
>>> a
array([[ 0,  1,  2,  3,  4],
       [ 5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14]])
>>> b = np.arange(15).reshape(3,5)
>>> a*b
array([[  0,   1,   4,   9,  16],
       [ 25,  36,  49,  64,  81],
       [100, 121, 144, 169, 196]])

 

Universal Functions

Available: https://numpy.org/devdocs/user/quickstart.html

allanyapply_along_axis 矩阵对比,元素全同样 只要有一个同样 lamdba 处理某维元素
argmaxargminargsortaveragebincount 第几维的最大值 第几维的最小值 某一维排序 某一维均值  基数排序
ceilclipconjcorrcoefcov 取右 "天花板" 设置“左右天花板” 求共轭 协方差[-1, 1] 协方差
crosscumprodcumsumdiffdot 向量积 累积乘 累计加 相邻元素差值 点积
floorinnerinvlexsortmax 取左 "地板” 相似“点积” 逆矩阵 向量排序 向量中的最大值
maximummeanmedianminminimum 向量中元素与一个值的最大值 mean
median 向量中的最小值 向量中元素与一个值的最小值
nonzeroouterprodreround 非零元素的全部坐标 向量1的各元素与向量2相乘  元素的乘积 正则  四舍五入
sortstdsumtracetranspose 按照某一个维度排序 计算全局标准差 某维度求和   对角线元素的和  矩阵转置
varvdotvectorizewhere  方差 点积  将函数向量化: lamdba 符合某一条件的下标函数  

 

Here is a list of some useful NumPy functions and methods names ordered in categories. See Routines for the full list.

Array Creation arangearraycopyemptyempty_likeeyefromfilefromfunctionidentitylinspacelogspacemgridogridonesones_likerzeroszeros_like
Conversions ndarray.astypeatleast_1datleast_2datleast_3dmat
Manipulations array_splitcolumn_stackconcatenatediagonaldsplitdstackhsplithstackndarray.itemnewaxisravelrepeatreshaperesizesqueezeswapaxestaketransposevsplit,vstack
Questions allanynonzerowhere
Ordering argmaxargminargsortmaxminptpsearchsortedsort
Operations choosecompresscumprodcumsuminnerndarray.fillimagprodputputmaskrealsum
Basic Statistics covmeanstdvar
Basic Linear Algebra crossdotouterlinalg.svdvdot


2、矩阵操做

矩阵下标

index 表示范围

#coding:utf-8
import numpy as np
a=np.array([[1,2,3],[4,5,6]])
print(a.shape)      #(2,3)
print(a[:][0])      #这样写,不管先后,只遍历第一行
print(a[0][:])
print(a[:][1])
print(a[1][:])
############################
print(a[:,0])      #这样写才是遍历第一列,先后有区别
print(a[0,:])
print(a[:,1])
print(a[1,:])
print(a[:,2])
############################
print(a[0:3][0])    #[:]范围明明是3个,拆开写就不对,要符合实际状况
print(a[0][0])
print(a[1][0])

 

下标表示范围内的“间隔”

>>> a[:6:2] = -1000    # equivalent to a[0:6:2] = -1000; from start to position 6, exclusive, set every 2nd element to -1000
>>> a
array([-1000,     1, -1000,    27, -1000,   125,   216,   343,   512,   729])

 

矩阵遍历

传统遍历 - 规则数组 

list2d = [[1,2,3],[4,5,6]]
sum = 0
for i in range(len(list2d)):
    for j in range(len(list2d[0])):
        sum += list2d[i][j]

 

句柄遍历 - 不规则数组

list2d = [[1,2,3],[4,5]]
sum = 0
for i in list2d:
    for j in i:
        sum += j

 

矩阵取整

取左地板值

# np.floor取整
>>> a = np.floor(10*np.random.random((3,4))) >>> a array([[ 2., 8., 0., 6.], [ 4., 5., 1., 1.], [ 8., 9., 3., 6.]]) >>> a.shape (3, 4)

 

仅保留整数位

math.trunc(-2.5) 更人性化,return -2; 而不是floor的-3。

 

四舍五入

round(2.45):四舍五入

 

 

3、矩阵形变

扁平化

彻底扁平

>>> a.ravel()  # returns the array, flattened
array([ 2.,  8.,  0.,  6.,  4.,  5.,  1.,  1.,  8.,  9.,  3.,  6.])

 

自定义扁平

>>> a.reshape(6,2)  # returns the array with a modified shape
array([[ 2.,  8.],
       [ 0.,  6.],
       [ 4.,  5.],
       [ 1.,  1.],
       [ 8.,  9.],
       [ 3.,  6.]])

-----------------------------------------------------------------------

>>> a.resize((2,6))  # this method modifies the array itself!
>>> a
array([[ 2.,  8.,  0.,  6.,  4.,  5.],
       [ 1.,  1.,  8.,  9.,  3.,  6.]])

 

转置

>>> a.T  # returns the array, transposed
array([[ 2.,  4.,  8.],
       [ 8.,  5.,  9.],
       [ 0.,  1.,  3.],
       [ 6.,  1.,  6.]])
>>> a.T.shape
(4, 3)
>>> a.shape
(3, 4)

    

堆叠

总体对接

Stacking together different arrays.

>>> a = np.floor(10*np.random.random((2,2)))
>>> a
array([[ 8.,  8.],
       [ 0., 0.]])
>>> b = np.floor(10*np.random.random((2,2)))
>>> b
array([[ 1.,  8.],
       [ 0., 4.]])

>>> np.vstack((a,b))  # 第一维度的粘结,更深 array([[ 8., 8.], [ 0., 0.], [ 1., 8.], [ 0., 4.]])
>>> np.hstack((a,b))  # 第二维度的对接,更宽 array([[ 8., 8., 1., 8.], [ 0., 0., 0., 4.]])

 

各取出一个配对

column_stack & row_stack.

>>> np.hstack([np.array([1, 2, 3]), np.array([4, 5, 6])])
array([1, 2, 3, 4, 5, 6])

>>> np.column_stack([np.array([1, 2, 3]), np.array([4, 5, 6])])  # 按照列的顺序,各自拿出一个,组合在一块儿
array([[1, 4],
       [2, 5],
       [3, 6]])
>>> np.vstack([np.array([1, 2, 3]), np.array([4, 5, 6])])
array([[1, 2, 3],
       [4, 5, 6]])

>>> np.row_stack([np.array([1, 2, 3]), np.array([4, 5, 6])])    # 按照行的顺序,各自拿出一个,组合在一块儿
array([[1, 2, 3],
       [4, 5, 6]])

  

元素自增长一维度

>>> from numpy import newaxis
>>> a = np.array([4.,2.]) >>> b = np.array([2.,8.])
>>> a[: ,newaxis] # This allows to have a 2D columns vector array([[ 4.], [ 2.]])   # 可见,自增长了维度的效果

>>> np.column_stack((a[:,newaxis],b[:,newaxis]))  // 两个一维数组的合并和两个数字合并,本质上是同样的:由于一个数字其实就是“默认一维” array([[ 4., 2.], [ 2., 8.]])

>>> np.vstack((a[:,newaxis],b[:,newaxis])) # The behavior of vstack is different array([[ 4.], [ 2.], [ 2.], [ 8.]])

 

拆分

注意:能够经过定义 “分割点” 来分割高维矩阵。

Splitting one array into several smaller ones.

>>> a = np.floor(10*np.random.random((2,12)))
>>> a
array([[ 9.,  5.,  6.,  3.,  6.,  8.,  0.,  7.,  9.,  7.,  2.,  7.],
       [ 1.,  4.,  9.,  2.,  2.,  1.,  0.,  6.,  2.,  2.,  4.,  0.]])

>>> np.hsplit(a,3)   # Split a into 3
[array([[ 9.,  5.,  6.,  3.], [ 1.,  4.,  9.,  2.]]), 
array([[ 6., 8., 0., 7.], [ 2., 1., 0., 6.]]),
array([[ 9., 7., 2., 7.], [ 2., 2., 4., 0.]])]
>>> np.hsplit(a, (3,4)) # Split a after the third and the fourth column 看样子像是"分割点" [array([[ 9., 5., 6.], [ 1., 4., 9.]]), array([[ 3.], [ 2.]] ), array([[ 6., 8., 0., 7., 9., 7., 2., 7.], [ 2., 1., 0., 6., 2., 2., 4., 0.]])] >>> np.vsplit(a,(3,4)) [array([[ 2., 9., 0., 4., 3., 2., 8., 0., 6., 2., 0., 4.], [ 8., 0., 5., 3., 4., 9., 5., 0., 3., 4., 4., 5.]]), array([], shape=(0, 12), dtype=float64), array([], shape=(0, 12), dtype=float64)]

 

np.split更灵活,任意分割!

>>> x = np.arange(8.0)
>>> np.split(x, [3, 5, 6, 10]) [array([ 0., 1., 2.]), array([ 3., 4.]), array([ 5.]), array([ 6., 7.]), array([], dtype=float64)]

其余:numpy.array_split 【彷佛用处不大】

 

 

4、矩阵拷贝

引用,非拷贝

No Copy at All, 引用

>>> b = a            # no new object is created
>>> id(a)            # id is a unique identifier of an object

 

映射关系 view

虽 id 不一样,但base指向对方。

view矩阵虽然形状变了,但每一个元素仍是跟原来的“有映射关系”,改变某值,对应的"原位置的值"改变。

>>> c = a.view()
>>> c is a
False
>>> c.base is a                        # c is a view of the data owned by a <---- 理解这句话!
True
>>> c.flags.owndata False
>>> c.shape = 2,6 # a's shape doesn't change >>> a.shape (3, 4) >>> c[0,4] = 1234 # a's data changes >>> a array([[ 0, 1, 2, 3], [1234, 5, 6, 7], [ 8, 9, 10, 11]])

 

Deep Copy , 深拷贝

>>> d = a.copy()                          # a new array object with new data is created
>>> d is a
False
>>> d.base is a                           # d doesn't share anything with a
False
>>> d[0,0] = 9999
>>> a
array([[   0,   10,   10,    3],
       [1234,   10,   10,    7],
       [   8,   10,   10,   11]])

 

 

5、统计采样

Ref: Numpy随机抽样

 

正态分布

#均匀分布
np.random.rand(2,5)  // shape

#正态分布
np.random.randn(1,10) // shape

#均匀分布 - 半开半闭区间 - 整数 【nice】
np.random.randint(2, 5, 10)       // interval
np.random.randint(2, 5, (6,6))    // interval

#均匀分布 - 闭区间 - 整数 【nice】
np.random.random_integers(2, 5, 10)

#均匀分布 - 半开半闭区间 - 百分比
np.random.random_sample((6,6))

#均匀分布 - 闭区间 - 整数
np.random.choice(10, 5)

  

其余分布

random.beta(a,b,size):从 Beta 分布中生成随机数。 random.binomial(n, p, size):从二项分布中生成随机数。 random.chisquare(df,size):从卡方分布中生成随机数。 random.dirichlet(alpha,size):从 Dirichlet 分布中生成随机数。 random.exponential(scale,size):从指数分布中生成随机数。 random.f(dfnum,dfden,size):从 F 分布中生成随机数。 random.gamma(shape,scale,size):从 Gamma 分布中生成随机数。 random.geometric(p,size):从几何分布中生成随机数。 random.gumbel(loc,scale,size):从 Gumbel 分布中生成随机数。 random.hypergeometric(ngood, nbad, nsample, size):从超几何分布中生成随机数。 random.laplace(loc,scale,size):从拉普拉斯双指数分布中生成随机数。 random.logistic(loc,scale,size):从逻辑分布中生成随机数。 random.lognormal(mean,sigma,size):从对数正态分布中生成随机数。 random.logseries(p,size):从对数系列分布中生成随机数。 random.multinomial(n,pvals,size):从多项分布中生成随机数。 random.multivariate_normal(mean, cov, size):从多变量正态分布绘制随机样本。 random.negative_binomial(n, p, size):从负二项分布中生成随机数。 random.noncentral_chisquare(df,nonc,size):从非中心卡方分布中生成随机数。 random.noncentral_f(dfnum, dfden, nonc, size):从非中心 F 分布中抽取样本。 random.normal(loc,scale,size):从正态分布绘制随机样本。 random.pareto(a,size):从具备指定形状的 Pareto II 或 Lomax 分布中生成随机数。 random.poisson(lam,size):从泊松分布中生成随机数。 random.power(a,size):从具备正指数 a-1 的功率分布中在 0,1 中生成随机数。 random.rayleigh(scale,size):从瑞利分布中生成随机数。 random.standard_cauchy(size):从标准 Cauchy 分布中生成随机数。 random.standard_exponential(size):从标准指数分布中生成随机数。 random.standard_gamma(shape,size):从标准 Gamma 分布中生成随机数。 random.standard_normal(size):从标准正态分布中生成随机数。 random.standard_t(df,size):从具备 df 自由度的标准学生 t 分布中生成随机数。 random.triangular(left,mode,right,size):从三角分布中生成随机数。 random.uniform(low,high,size):从均匀分布中生成随机数。 random.vonmises(mu,kappa,size):从 von Mises 分布中生成随机数。 random.wald(mean,scale,size):从 Wald 或反高斯分布中生成随机数。 random.weibull(a,size):从威布尔分布中生成随机数。 random.zipf(a,size):从 Zipf 分布中生成随机数。

再结合取整便可:np.floor(<list>) 

   

End.

相关文章
相关标签/搜索