1、线性代数库linalg

函数

描述

dot

两个数组的点积,即元素对应相乘。

vdot

两个向量的点积

inner

两个数组的内积

matmul

两个数组的矩阵积

determinant

数组的行列式

solve

求解线性矩阵方程

inv

计算矩阵的乘法逆矩阵

2、随机游走

实现1000步的随机游走:

import random
position = 0
walk = [position]
steps = 1000
for i in xrange(steps):
    step = 1 if random.randint(0, 1) else -1
    position += step
    walk.append(position)

计算1000次游走结果的累积和,大于0则取1,小于0则取-1(类似于抛硬币)

nsteps = 1000
draws = np.random.randint(0, 2, size=nsteps)
steps = np.where(draws > 0, 1, -1)
walk = steps.cumsum()

一次模拟多个随机游走:

nwalks = 5000
nsteps = 1000
draws = np.random.randint(0, 2, size=(nwalks, nsteps))
steps = np.where(draws > 0, 1, -1)
walks = steps.cumsum(1)
print(walks)

3、Matplotlib

import numpy as np 
from matplotlib import pyplot as plt 
 
x = np.arange(1,11) 
y =  2  * x +  5 
plt.title("Matplotlib demo")  //设置图表标题
plt.xlabel("x axis caption")  //设置x轴名称
plt.ylabel("y axis caption")  //设置y轴名称
plt.plot(x,y)  //绘制以x为x轴,y为y轴的图形
plt.show() //显示图形

plt.plot(x,y,"ob")

字符

描述

'-'

实线样式

'--'

短横线样式

'-.'

点划线样式

':'

虚线样式

'.'

点标记

','

像素标记

'o'

圆标记

'v'

倒三角标记

'^'

正三角标记

'<'

左三角标记

'>'

右三角标记

'1'

下箭头标记

'2'

上箭头标记

'3'

左箭头标记

'4'

右箭头标记

's'

正方形标记

'p'

五边形标记

'*'

星形标记

'h'

六边形标记 1

'H'

六边形标记 2

'+'

加号标记

'x'

X 标记

'D'

菱形标记

'd'

窄菱形标记

'|'

竖直线标记

'_'

水平线标记

                以下是颜色的缩写:如 plt.bar(x2, y2, color = 'g')

字符

颜色

'b'

蓝色

'g'

绿色

'r'

红色

'c'

青色

'm'

品红色

'y'

黄色

'k'

黑色

'w'

白色

 

同一图中绘制两个图

plt.subplot(2,  1,  1) //绘制第一个图像 
plt.plot(x, y1) 
plt.title('x-y1') //将第二个 subplot 激活,并绘制第二个图像
plt.subplot(2,  1,  2) 
plt.plot(x, y2) 
plt.title('x-y2') //展示图像
plt.show()

绘制条形图

from matplotlib import pyplot as plt 
x =  [5,8,10] 
y =  [12,16,6] 
x2 =  [6,9,11] 
y2 =  [6,15,7] 
plt.bar(x, y, align =  'center')  //绘制条形图1
plt.bar(x2, y2, color =  'g', align =  'center')  //绘制条形图2
plt.title('Bar graph')  
plt.ylabel('Y axis') 
plt.xlabel('X axis') 
plt.show()

绘制频率分布直方图

from matplotlib import pyplot as plt 
import numpy as np  
 
a = np.array([22,87,5,43,56,73,55,54,11,20,51,5,79,31,27]) 
plt.hist(a, bins =  [0,20,40,60,80,100])   // bin 数组中的连续元素用作每个 bin 的边界
plt.title("histogram") 
plt.show()