机器学习

This commit is contained in:
estomm
2020-09-29 10:05:30 +08:00
parent 501c49c1de
commit bb81ba3fb3
63 changed files with 1429 additions and 917 deletions

View File

@@ -1,279 +0,0 @@
# 面向对象的绘图方式
## 配置参数
* axex: 设置坐标轴边界和表面的颜色、坐标刻度值大小和网格的显示
* figure: 控制dpi、边界颜色、图形大小、和子区( subplot)设置
* font: 字体集font family、字体大小和样式设置
* grid: 设置网格颜色和线性
* legend: 设置图例和其中的文本的显示
* line: 设置线条(颜色、线型、宽度等)和标记
* patch: 是填充2D空间的图形对象如多边形和圆。控制线宽、颜色和抗锯齿设置等。
* savefig: 可以对保存的图形进行单独设置。例如,设置渲染的文件的背景为白色。
* verbose: 设置matplotlib在执行期间信息输出如silent、helpful、debug和debug-annoying。
* xticks和yticks: 为x,y轴的主刻度和次刻度设置颜色、大小、方向以及标签大小。
## 线条风格
线条风格linestyle或ls | 描述
----|---
- |实线
: |虚线
|破折线
None, , |什么都不画
-. |点划线
## 线条标记
标记maker | 描述
----|----
o |圆圈
. |点
D |菱形
s |正方形
h |六边形1
* |星号
H |六边形2
d |小菱形
_ | 水平线
v |一角朝下的三角形
8 |八边形
< | 一角朝左的三角形
p |五边形
> |一角朝右的三角形
, |像素
^ | 一角朝上的三角形
+ | 加号
\ |竖线
None,, |无
x | X
## 颜色
别名 | 颜色
---|---
b | 蓝色
g |绿色
r |红色
y |黄色
c |青色
k |黑色
m |洋红色
w |白色
## 绘图步骤
```py
#使用numpy产生数据
x=np.arange(-5,5,0.1)
y=x*3
#创建窗口、子图
#方法1先创建窗口再创建子图。一定绘制
fig = plt.figure(num=1, figsize=(15, 8),dpi=80) #开启一个窗口,同时设置大小,分辨率
ax1 = fig.add_subplot(2,1,1) #通过fig添加子图参数行数列数第几个。
ax2 = fig.add_subplot(2,1,2) #通过fig添加子图参数行数列数第几个。
print(fig,ax1,ax2)
#方法2一次性创建窗口和多个子图。空白不绘制
fig,axarr = plt.subplots(4,1) #开一个新窗口并添加4个子图返回子图数组
ax1 = axarr[0] #通过子图数组获取一个子图
print(fig,ax1)
#方法3一次性创建窗口和一个子图。空白不绘制
ax1 = plt.subplot(1,1,1,facecolor='white') #开一个新窗口创建1个子图。facecolor设置背景颜色
print(ax1)
#获取对窗口的引用,适用于上面三种方法
# fig = plt.gcf() #获得当前figure
# fig=ax1.figure #获得指定子图所属窗口
# fig.subplots_adjust(left=0) #设置窗口左内边距为0即左边留白为0。
#设置子图的基本元素
ax1.set_title('python-drawing') #设置图体plt.title
ax1.set_xlabel('x-name') #设置x轴名称,plt.xlabel
ax1.set_ylabel('y-name') #设置y轴名称,plt.ylabel
plt.axis([-6,6,-10,10]) #设置横纵坐标轴范围,这个在子图中被分解为下面两个函数
ax1.set_xlim(-5,5) #设置横轴范围,会覆盖上面的横坐标,plt.xlim
ax1.set_ylim(-10,10) #设置纵轴范围,会覆盖上面的纵坐标,plt.ylim
xmajorLocator = MultipleLocator(2) #定义横向主刻度标签的刻度差为2的倍数。就是隔几个刻度才显示一个标签文本
ymajorLocator = MultipleLocator(3) #定义纵向主刻度标签的刻度差为3的倍数。就是隔几个刻度才显示一个标签文本
ax1.xaxis.set_major_locator(xmajorLocator) #x轴 应用定义的横向主刻度格式。如果不应用将采用默认刻度格式
ax1.yaxis.set_major_locator(ymajorLocator) #y轴 应用定义的纵向主刻度格式。如果不应用将采用默认刻度格式
ax1.xaxis.grid(True, which='major') #x坐标轴的网格使用定义的主刻度格式
ax1.yaxis.grid(True, which='major') #x坐标轴的网格使用定义的主刻度格式
ax1.set_xticks([]) #去除坐标轴刻度
ax1.set_xticks((-5,-3,-1,1,3,5)) #设置坐标轴刻度
ax1.set_xticklabels(labels=['x1','x2','x3','x4','x5'],rotation=-30,fontsize='small') #设置刻度的显示文本rotation旋转角度fontsize字体大小
plot1=ax1.plot(x,y,marker='o',color='g',label='legend1') #点图marker图标
plot2=ax1.plot(x,y,linestyle='--',alpha=0.5,color='r',label='legend2') #线图linestyle线性alpha透明度color颜色label图例文本
ax1.legend(loc='upper left') #显示图例,plt.legend()
ax1.text(2.8, 7, r'y=3*x') #指定位置显示文字,plt.text()
ax1.annotate('important point', xy=(2, 6), xytext=(3, 1.5), #添加标注,参数:注释文本、指向点、文字位置、箭头属性
arrowprops=dict(facecolor='black', shrink=0.05),
)
#显示网格。which参数的值为major(只绘制大刻度)、minor(只绘制小刻度)、both默认值为major。axis为'x','y','both'
ax1.grid(b=True,which='major',axis='both',alpha= 0.5,color='skyblue',linestyle='--',linewidth=2)
axes1 = plt.axes([.2, .3, .1, .1], facecolor='y') #在当前窗口添加一个子图rect=[左, 下, 宽, 高],是使用的绝对布局,不和以存在窗口挤占空间
axes1.plot(x,y) #在子图上画图
plt.savefig('aa.jpg',dpi=400,bbox_inches='tight') #savefig保存图片dpi分辨率bbox_inches子图周边白色空间的大小
plt.show() #打开窗口对于方法1创建在窗口一定绘制对于方法2方法3创建的窗口若坐标系全部空白则不绘制
```
## plot属性
```py
属性 值类型
alpha 浮点值
animated [True / False]
antialiased or aa [True / False]
clip_box matplotlib.transform.Bbox 实例
clip_on [True / False]
clip_path Path 实例 Transform以及Patch实例
color or c 任何 matplotlib 颜色
contains 命中测试函数
dash_capstyle ['butt' / 'round' / 'projecting']
dash_joinstyle ['miter' / 'round' / 'bevel']
dashes 以点为单位的连接/断开墨水序列
data (np.array xdata, np.array ydata)
figure matplotlib.figure.Figure 实例
label 任何字符串
linestyle or ls [ '-' / '--' / '-.' / ':' / 'steps' / ...]
linewidth or lw 以点为单位的浮点值
lod [True / False]
marker [ '+' / ',' / '.' / '1' / '2' / '3' / '4' ]
markeredgecolor or mec 任何 matplotlib 颜色
markeredgewidth or mew 以点为单位的浮点值
markerfacecolor or mfc 任何 matplotlib 颜色
markersize or ms 浮点值
markevery [ None / 整数值 / (startind, stride) ]
picker 用于交互式线条选择
pickradius 线条的拾取选择半径
solid_capstyle ['butt' / 'round' / 'projecting']
solid_joinstyle ['miter' / 'round' / 'bevel']
transform matplotlib.transforms.Transform 实例
visible [True / False]
xdata np.array
ydata np.array
zorder 任何数值
```
## 多图绘制
```py
#一个窗口,多个图,多条数据
sub1=plt.subplot(211,facecolor=(0.1843,0.3098,0.3098)) #将窗口分成2行1列在第1个作图并设置背景色
sub2=plt.subplot(212) #将窗口分成2行1列在第2个作图
sub1.plot(x,y) #绘制子图
sub2.plot(x,y) #绘制子图
axes1 = plt.axes([.2, .3, .1, .1], facecolor='y') #添加一个子坐标系rect=[左, 下, 宽, 高]
plt.plot(x,y) #绘制子坐标系,
axes2 = plt.axes([0.7, .2, .1, .1], facecolor='y') #添加一个子坐标系rect=[左, 下, 宽, 高]
plt.plot(x,y)
plt.show()
```
## 极坐标
```py
fig = plt.figure(2) #新开一个窗口
ax1 = fig.add_subplot(1,2,1,polar=True) #启动一个极坐标子图
theta=np.arange(0,2*np.pi,0.02) #角度数列值
ax1.plot(theta,2*np.ones_like(theta),lw=2) #画图参数角度半径lw线宽
ax1.plot(theta,theta/6,linestyle='--',lw=2) #画图参数角度半径linestyle样式lw线宽
ax2 = fig.add_subplot(1,2,2,polar=True) #启动一个极坐标子图
ax2.plot(theta,np.cos(5*theta),linestyle='--',lw=2)
ax2.plot(theta,2*np.cos(4*theta),lw=2)
ax2.set_rgrids(np.arange(0.2,2,0.2),angle=45) #距离网格轴,轴线刻度和显示位置
ax2.set_thetagrids([0,45,90]) #角度网格轴范围0-360度
plt.show()
```
## 柱状图
```py
plt.figure(3)
x_index = np.arange(5) #柱的索引
x_data = ('A', 'B', 'C', 'D', 'E')
y1_data = (20, 35, 30, 35, 27)
y2_data = (25, 32, 34, 20, 25)
bar_width = 0.35 #定义一个数字代表每个独立柱的宽度
rects1 = plt.bar(x_index, y1_data, width=bar_width,alpha=0.4, color='b',label='legend1') #参数:左偏移、高度、柱宽、透明度、颜色、图例
rects2 = plt.bar(x_index + bar_width, y2_data, width=bar_width,alpha=0.5,color='r',label='legend2') #参数:左偏移、高度、柱宽、透明度、颜色、图例
#关于左偏移,不用关心每根柱的中心不中心,因为只要把刻度线设置在柱的中间就可以了
plt.xticks(x_index + bar_width/2, x_data) #x轴刻度线
plt.legend() #显示图例
plt.tight_layout() #自动控制图像外部边缘,此方法不能够很好的控制图像间的间隔
plt.show()
```
## 直方图
```py
fig,(ax0,ax1) = plt.subplots(nrows=2,figsize=(9,6)) #在窗口上添加2个子图
sigma = 1 #标准差
mean = 0 #均值
x=mean+sigma*np.random.randn(10000) #正态分布随机数
ax0.hist(x,bins=40,normed=False,histtype='bar',facecolor='yellowgreen',alpha=0.75) #normed是否归一化histtype直方图类型facecolor颜色alpha透明度
ax1.hist(x,bins=20,normed=1,histtype='bar',facecolor='pink',alpha=0.75,cumulative=True,rwidth=0.8) #bins柱子的个数,cumulative是否计算累加分布rwidth柱子宽度
plt.show() #所有窗口运行
```
## 散点图
```py
fig = plt.figure(4) #添加一个窗口
ax =fig.add_subplot(1,1,1) #在窗口上添加一个子图
x=np.random.random(100) #产生随机数组
y=np.random.random(100) #产生随机数组
ax.scatter(x,y,s=x*1000,c='y',marker=(5,1),alpha=0.5,lw=2,facecolors='none') #x横坐标y纵坐标s图像大小c颜色marker图片lw图像边框宽度
plt.show() #所有窗口运行
```
## 三维图
```py
fig = plt.figure(5)
ax=fig.add_subplot(1,1,1,projection='3d') #绘制三维图
x,y=np.mgrid[-2:2:20j,-2:2:20j] #获取x轴数据y轴数据
z=x*np.exp(-x**2-y**2) #获取z轴数据
ax.plot_surface(x,y,z,rstride=2,cstride=1,cmap=plt.cm.coolwarm,alpha=0.8) #绘制三维图表面
ax.set_xlabel('x-name') #x轴名称
ax.set_ylabel('y-name') #y轴名称
ax.set_zlabel('z-name') #z轴名称
plt.show()
```
## 集合图形
```py
fig = plt.figure(6) #创建一个窗口
ax=fig.add_subplot(1,1,1) #添加一个子图
rect1 = plt.Rectangle((0.1,0.2),0.2,0.3,color='r') #创建一个矩形,参数:(x,y),width,height
circ1 = plt.Circle((0.7,0.2),0.15,color='r',alpha=0.3) #创建一个椭圆,参数:中心点,半径,默认这个圆形会跟随窗口大小进行长宽压缩
pgon1 = plt.Polygon([[0.45,0.45],[0.65,0.6],[0.2,0.6]]) #创建一个多边形,参数:每个顶点坐标
ax.add_patch(rect1) #将形状添加到子图上
ax.add_patch(circ1) #将形状添加到子图上
ax.add_patch(pgon1) #将形状添加到子图上
fig.canvas.draw() #子图绘制
plt.show()
```

View File

@@ -0,0 +1,359 @@
# 面向对象的绘图方式
> 在这里的实例中,面向对象的方法与命令行的方式进行了混用,不提倡。首先运用好交互式命令行的方式进行绘图。
## 配置参数
* axex: 设置坐标轴边界和表面的颜色、坐标刻度值大小和网格的显示
* figure: 控制dpi、边界颜色、图形大小、和子区( subplot)设置
* font: 字体集font family、字体大小和样式设置
* grid: 设置网格颜色和线性
* legend: 设置图例和其中的文本的显示
* line: 设置线条(颜色、线型、宽度等)和标记
* patch: 是填充2D空间的图形对象如多边形和圆。控制线宽、颜色和抗锯齿设置等。
* savefig: 可以对保存的图形进行单独设置。例如,设置渲染的文件的背景为白色。
* verbose: 设置matplotlib在执行期间信息输出如silent、helpful、debug和debug-annoying。
* xticks和yticks: 为x,y轴的主刻度和次刻度设置颜色、大小、方向以及标签大小。
## 线条风格
线条风格linestyle或ls | 描述
----|---
- |实线
: |虚线
|破折线
None, , |什么都不画
-. |点划线
## 线条标记
标记maker | 描述
----|----
o |圆圈
. |点
D |菱形
s |正方形
h |六边形1
* |星号
H |六边形2
d |小菱形
_ | 水平线
v |一角朝下的三角形
8 |八边形
< | 一角朝左的三角形
p |五边形
> |一角朝右的三角形
, |像素
^ | 一角朝上的三角形
+ | 加号
\ |竖线
None,, |无
x | X
## 颜色
别名 | 颜色
---|---
b | 蓝色
g |绿色
r |红色
y |黄色
c |青色
k |黑色
m |洋红色
w |白色
## 绘图步骤
```py
#使用numpy产生数据
x=np.arange(-5,5,0.1)
y=x*3
#创建窗口、子图
#方法1先创建窗口再创建子图。一定绘制
fig = plt.figure(num=1, figsize=(15, 8),dpi=80)
#开启一个窗口,同时设置大小,分辨率
ax1 = fig.add_subplot(2,1,1)
#通过fig添加子图参数行数列数第几个。
ax2 = fig.add_subplot(2,1,2)
#通过fig添加子图参数行数列数第几个。
print(fig,ax1,ax2)
#方法2一次性创建窗口和多个子图。空白不绘制
fig,axarr = plt.subplots(4,1)
#开一个新窗口并添加4个子图返回子图数组
ax1 = axarr[0]
#通过子图数组获取一个子图
print(fig,ax1)
#方法3一次性创建窗口和一个子图。空白不绘制
ax1 = plt.subplot(1,1,1,facecolor='white')
#开一个新窗口创建1个子图。facecolor设置背景颜色
print(ax1)
#获取对窗口的引用,适用于上面三种方法
# fig = plt.gcf() #获得当前figure
# fig=ax1.figure #获得指定子图所属窗口
# fig.subplots_adjust(left=0)
#设置窗口左内边距为0即左边留白为0。
#设置子图的基本元素
ax1.set_title('python-drawing')
#设置图体plt.title
ax1.set_xlabel('x-name')
#设置x轴名称,plt.xlabel
ax1.set_ylabel('y-name')
#设置y轴名称,plt.ylabel
plt.axis([-6,6,-10,10])
#设置横纵坐标轴范围,这个在子图中被分解为下面两个函数
ax1.set_xlim(-5,5)
#设置横轴范围,会覆盖上面的横坐标,plt.xlim
ax1.set_ylim(-10,10)
#设置纵轴范围,会覆盖上面的纵坐标,plt.ylim
xmajorLocator = MultipleLocator(2)
#定义横向主刻度标签的刻度差为2的倍数。就是隔几个刻度才显示一个标签文本
ymajorLocator = MultipleLocator(3)
#定义纵向主刻度标签的刻度差为3的倍数。就是隔几个刻度才显示一个标签文本
ax1.xaxis.set_major_locator(xmajorLocator)
#x轴 应用定义的横向主刻度格式。如果不应用将采用默认刻度格式
ax1.yaxis.set_major_locator(ymajorLocator)
#y轴 应用定义的纵向主刻度格式。如果不应用将采用默认刻度格式
ax1.xaxis.grid(True, which='major')
#x坐标轴的网格使用定义的主刻度格式
ax1.yaxis.grid(True, which='major')
#x坐标轴的网格使用定义的主刻度格式
ax1.set_xticks([])
#去除坐标轴刻度
ax1.set_xticks((-5,-3,-1,1,3,5))
#设置坐标轴刻度
ax1.set_xticklabels(labels=['x1','x2','x3','x4','x5'],rotation=-30,fontsize='small')
#设置刻度的显示文本rotation旋转角度fontsize字体大小
plot1=ax1.plot(x,y,marker='o',color='g',label='legend1')
#点图marker图标
plot2=ax1.plot(x,y,linestyle='--',alpha=0.5,color='r',label='legend2')
#线图linestyle线性alpha透明度color颜色label图例文本
ax1.legend(loc='upper left')
#显示图例,plt.legend()
ax1.text(2.8, 7, r'y=3*x')
#指定位置显示文字,plt.text()
ax1.annotate('important point', xy=(2, 6), xytext=(3, 1.5), arrowprops=dict(facecolor='black', shrink=0.05),)
#添加标注,参数:注释文本、指向点、文字位置、箭头属性
#显示网格。which参数的值为major(只绘制大刻度)、minor(只绘制小刻度)、both默认值为major。axis为'x','y','both'
ax1.grid(b=True,which='major',axis='both',alpha= 0.5,color='skyblue',linestyle='--',linewidth=2)
axes1 = plt.axes([.2, .3, .1, .1], facecolor='y')
#在当前窗口添加一个子图rect=[左, 下, 宽, 高],是使用的绝对布局,不和以存在窗口挤占空间
axes1.plot(x,y)
#在子图上画图
plt.savefig('aa.jpg',dpi=400,bbox_inches='tight')
#savefig保存图片dpi分辨率bbox_inches子图周边白色空间的大小
plt.show()
#打开窗口对于方法1创建在窗口一定绘制对于方法2方法3创建的窗口若坐标系全部空白则不绘制
```
## plot属性
```py
属性 值类型
alpha 浮点值
animated [True / False]
antialiased or aa [True / False]
clip_box matplotlib.transform.Bbox 实例
clip_on [True / False]
clip_path Path 实例 Transform以及Patch实例
color or c 任何 matplotlib 颜色
contains 命中测试函数
dash_capstyle ['butt' / 'round' / 'projecting']
dash_joinstyle ['miter' / 'round' / 'bevel']
dashes 以点为单位的连接/断开墨水序列
data (np.array xdata, np.array ydata)
figure matplotlib.figure.Figure 实例
label 任何字符串
linestyle or ls [ '-' / '--' / '-.' / ':' / 'steps' / ...]
linewidth or lw 以点为单位的浮点值
lod [True / False]
marker [ '+' / ',' / '.' / '1' / '2' / '3' / '4' ]
markeredgecolor or mec 任何 matplotlib 颜色
markeredgewidth or mew 以点为单位的浮点值
markerfacecolor or mfc 任何 matplotlib 颜色
markersize or ms 浮点值
markevery [ None / 整数值 / (startind, stride) ]
picker 用于交互式线条选择
pickradius 线条的拾取选择半径
solid_capstyle ['butt' / 'round' / 'projecting']
solid_joinstyle ['miter' / 'round' / 'bevel']
transform matplotlib.transforms.Transform 实例
visible [True / False]
xdata np.array
ydata np.array
zorder 任何数值
```
## 多图绘制
```py
#一个窗口,多个图,多条数据
sub1=plt.subplot(211,facecolor=(0.1843,0.3098,0.3098))
#将窗口分成2行1列在第1个作图并设置背景色
sub2=plt.subplot(212)
#将窗口分成2行1列在第2个作图
sub1.plot(x,y)
#绘制子图
sub2.plot(x,y)
#绘制子图
axes1 = plt.axes([.2, .3, .1, .1], facecolor='y')
#添加一个子坐标系rect=[左, 下, 宽, 高]
plt.plot(x,y)
#绘制子坐标系,
axes2 = plt.axes([0.7, .2, .1, .1], facecolor='y')
#添加一个子坐标系rect=[左, 下, 宽, 高]
plt.plot(x,y)
plt.show()
```
## 极坐标
```py
fig = plt.figure(2)
#新开一个窗口
ax1 = fig.add_subplot(1,2,1,polar=True)
#启动一个极坐标子图
theta=np.arange(0,2*np.pi,0.02)
#角度数列值
ax1.plot(theta,2*np.ones_like(theta),lw=2)
#画图参数角度半径lw线宽
ax1.plot(theta,theta/6,linestyle='--',lw=2)
#画图参数角度半径linestyle样式lw线宽
ax2 = fig.add_subplot(1,2,2,polar=True)
#启动一个极坐标子图
ax2.plot(theta,np.cos(5*theta),linestyle='--',lw=2)
ax2.plot(theta,2*np.cos(4*theta),lw=2)
ax2.set_rgrids(np.arange(0.2,2,0.2),angle=45) #距离网格轴,轴线刻度和显示位置
ax2.set_thetagrids([0,45,90]) #角度网格轴范围0-360度
plt.show()
```
## 柱状图
```py
plt.figure(3)
x_index = np.arange(5)
#柱的索引
x_data = ('A', 'B', 'C', 'D', 'E')
y1_data = (20, 35, 30, 35, 27)
y2_data = (25, 32, 34, 20, 25)
bar_width = 0.35
#定义一个数字代表每个独立柱的宽度
rects1 = plt.bar(x_index, y1_data, width=bar_width,alpha=0.4, color='b',label='legend1')
#参数:左偏移、高度、柱宽、透明度、颜色、图例
rects2 = plt.bar(x_index + bar_width, y2_data, width=bar_width,alpha=0.5,color='r',label='legend2')
#参数:左偏移、高度、柱宽、透明度、颜色、图例
#关于左偏移,不用关心每根柱的中心不中心,因为只要把刻度线设置在柱的中间就可以了
plt.xticks(x_index + bar_width/2, x_data)
#x轴刻度线
plt.legend()
#显示图例
plt.tight_layout()
#自动控制图像外部边缘,此方法不能够很好的控制图像间的间隔
plt.show()
```
## 直方图
```py
fig,(ax0,ax1) = plt.subplots(nrows=2,figsize=(9,6))
#在窗口上添加2个子图
sigma = 1
#标准差
mean = 0
#均值
x=mean+sigma*np.random.randn(10000)
#正态分布随机数
ax0.hist(x,bins=40,normed=False,histtype='bar',facecolor='yellowgreen',alpha=0.75)
#normed是否归一化histtype直方图类型facecolor颜色alpha透明度
ax1.hist(x,bins=20,normed=1,histtype='bar',facecolor='pink',alpha=0.75,cumulative=True,rwidth=0.8)
#bins柱子的个数,cumulative是否计算累加分布rwidth柱子宽度
plt.show()
#所有窗口运行
```
## 散点图
```py
fig = plt.figure(4)
#添加一个窗口
ax =fig.add_subplot(1,1,1)
#在窗口上添加一个子图
x=np.random.random(100)
#产生随机数组
y=np.random.random(100)
#产生随机数组
ax.scatter(x,y,s=x*1000,c='y',marker=(5,1),alpha=0.5,lw=2,facecolors='none')
#x横坐标y纵坐标s图像大小c颜色marker图片lw图像边框宽度
plt.show()
#所有窗口运行
```
## 三维图
```py
fig = plt.figure(5)
ax=fig.add_subplot(1,1,1,projection='3d')
#绘制三维图
x,y=np.mgrid[-2:2:20j,-2:2:20j]
#获取x轴数据y轴数据
z=x*np.exp(-x**2-y**2)
#获取z轴数据
ax.plot_surface(x,y,z,rstride=2,cstride=1,cmap=plt.cm.coolwarm,alpha=0.8)
#绘制三维图表面
ax.set_xlabel('x-name')
#x轴名称
ax.set_ylabel('y-name')
#y轴名称
ax.set_zlabel('z-name')
#z轴名称
plt.show()
```
## 集合图形
```py
fig = plt.figure(6)
#创建一个窗口
ax=fig.add_subplot(1,1,1)
#添加一个子图
rect1 = plt.Rectangle((0.1,0.2),0.2,0.3,color='r')
#创建一个矩形,参数:(x,y),width,height
circ1 = plt.Circle((0.7,0.2),0.15,color='r',alpha=0.3)
#创建一个椭圆,参数:中心点,半径,默认这个圆形会跟随窗口大小进行长宽压缩
pgon1 = plt.Polygon([[0.45,0.45],[0.65,0.6],[0.2,0.6]])
#创建一个多边形,参数:每个顶点坐标
ax.add_patch(rect1)
#将形状添加到子图上
ax.add_patch(circ1)
#将形状添加到子图上
ax.add_patch(pgon1)
#将形状添加到子图上
fig.canvas.draw()
#子图绘制
plt.show()
```

View File

@@ -0,0 +1,135 @@
# 基本用法
## 本章知识点归纳如下:
* 导入模块import matplotlib.pyplot as plt
* 定义图像窗口plt.figure()
* 画图plt.plot(x, y)
* 定义坐标轴范围plt.xlim()/plt.ylim()
* 定义坐标轴名称plt.xlabel()/plt.ylabel()
* 定义坐标轴刻度及名称plt.xticks()/plt.yticks()
* 设置图像边框颜色ax = plt.gca() ax.spines[].set_color()
* 调整刻度位置ax.xaxis.set_ticks_position()/ax.yaxis.set_ticks_position()
* 调整边框坐标轴位置ax.spines[].set_position()
## 导入模块
* 使用import导入模块matplotlib.pyplot并简写成plt使用import导入模块numpy并简写成np
```py
import matplotlib.pyplot as plt
import numpy as np
```
* 然后创建两组数据使用np.linspace定义x范围是(-3,3)个数是50将产生一组-33内均匀分布的50个数(x,y1)表示曲线1(x,y2)表示曲线2。
```py
x = np.linspace(-3, 3, 50)
y1 = 2*x + 1
y2 = x**2
```
## 定义图像窗口并画图
* 在画图前使用plt.figure()定义一个图像窗口编号为3大小为(8, 5)这两项参数可缺省。其中num参数决定了程序运行后弹出的图像窗口名字但在klab平台下不会显示。接着我们使用plt.plot画出(x ,y2)曲线使用plt.plot画(x ,y1)曲线,曲线的颜色属性(color)为红色;曲线的宽度(linewidth)为1.0;曲线的类型(linestyle)为虚线,除了虚线外,大家还可使用以下线性:'-'、'--'、'-.'、':' 。接着我们使用plt.show()显示图像。
```py
plt.figure(num=3, figsize=(8, 5))
plt.plot(x, y2)
plt.plot(x, y1, color='red', linewidth=1.0, linestyle='--')
plt.show()
```
## 定义坐标轴名称及范围
* 使用plt.xlim设置x坐标轴范围(-1, 2) 使用plt.ylim设置y坐标轴范围(-2, 3) 使用plt.xlabel设置x坐标轴名称I am x 使用plt.ylabel设置y坐标轴名称I am y
```py
plt.figure(num=3, figsize=(8, 5),)
plt.plot(x, y2)
plt.plot(x, y1, color='red', linewidth=1.0, linestyle='--')
plt.xlim((-1, 2))
plt.ylim((-2, 3))
plt.xlabel('I am x')
plt.ylabel('I am y')
plt.show()
```
## 定义坐标轴刻度及名称
* 有时候我们的坐标轴刻度可能并不是一连串的数字而是一些文字或者我们想要调整坐标轴的刻度的稀疏这时就需要使用plt.xticks()或者plt.yticks()来进行调整首先使用np.linspace定义新刻度范围以及个数范围是(-1,2);个数是5。使用plt.xticks设置x轴刻度范围是(-1,2);个数是5。使用plt.yticks设置y轴刻度以及名称刻度为[-2, -1.8, -1, 1.22, 3];对应刻度的名称为[really bad,bad,normal,good, really good]。使用plt.show()显示图像。
```py
plt.figure(num=3, figsize=(8, 5))
plt.plot(x, y2)
plt.plot(x, y1, color='red', linewidth=1.0, linestyle='--')
plt.xlim((-1, 2))
plt.ylim((-2, 3))
plt.xlabel('I am x')
plt.ylabel('I am y')
new_ticks = np.linspace(-1, 2, 5)
print(new_ticks)
plt.xticks(new_ticks)
plt.yticks([-2, -1.8, -1, 1.22, 3],[r'$really\ bad$', r'$bad$', r'$normal$', r'$good$', r'$really\ good$'])
plt.show()
[-1. -0.25 0.5 1.25 2. ]
```
## 设置图像边框颜色
* 细心的小伙伴可能会注意到我们的图像坐标轴总是由上下左右四条线组成我们也可以对它们进行修改首先使用plt.gca()获取当前坐标轴信息。使用.spines设置边框使用.set_color设置边框颜色
```py
plt.figure(num=3, figsize=(8, 5))
plt.plot(x, y2)
plt.plot(x, y1, color='red', linewidth=1.0, linestyle='--')
plt.xlim((-1, 2))
plt.ylim((-2, 3))
plt.xticks(new_ticks)
plt.yticks([-2, -1.8, -1, 1.22, 3],[r'$really\ bad$', r'$bad$', r'$normal$', r'$good$', r'$really\ good$'])
ax = plt.gca()
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
plt.show()
```
调整刻度及边框位置
使用.xaxis.set_ticks_position设置x坐标刻度数字或名称的位置bottom.所有位置topbottombothdefaultnone使用.spines设置边框x轴使用.set_position设置边框位置y=0的位置位置所有属性outwardaxesdata
plt.figure(num=3, figsize=(8, 5))
plt.plot(x, y2)
plt.plot(x, y1, color='red', linewidth=1.0, linestyle='--')
plt.xlim((-1, 2))
plt.ylim((-2, 3))
plt.xticks(new_ticks)
plt.yticks([-2, -1.8, -1, 1.22, 3],[r'$really\ bad$', r'$bad$', r'$normal$', r'$good$', r'$really\ good$'])
ax = plt.gca()
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.spines['bottom'].set_position(('data', 0))
plt.show()
使用.yaxis.set_ticks_position设置y坐标刻度数字或名称的位置left.所有位置leftrightbothdefaultnone 使用.spines设置边框y轴使用.set_position设置边框位置x=0的位置位置所有属性outwardaxesdata 使用plt.show显示图像.
plt.figure(num=3, figsize=(8, 5))
plt.plot(x, y2)
plt.plot(x, y1, color='red', linewidth=1.0, linestyle='--')
plt.xlim((-1, 2))
plt.ylim((-2, 3))
plt.xticks(new_ticks)
plt.yticks([-2, -1.8, -1, 1.22, 3],[r'$really\ bad$', r'$bad$', r'$normal$', r'$good$', r'$really\ good$'])
ax = plt.gca()
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.spines['bottom'].set_position(('data', 0))
ax.yaxis.set_ticks_position('left')
ax.spines['left'].set_position(('data',0))
plt.show()
练一练
小伙伴们以上就是matplotlib的基本用法是不是比较简单呢现在请根据上述所学内容画出直线 y = x-1, 线型为虚线线宽为1纵坐标范围-21横坐标范围-12横纵坐标在00坐标点相交。横坐标的 [-1,-0.5,1] 分别对应 [bad, normal, good]。请一定自己尝试一番再看下面的答案噢~
#答案
x = np.linspace(-1, 2, 50)
y = x - 1
plt.figure()
plt.plot(x,y, linewidth=1.0, linestyle='--')
plt.xlim((-1,2))
plt.ylim((-2,2))
plt.xticks([-1,-0.5,1],['bad', 'normal', 'good'])
ax = plt.gca()
ax.spines['top'].set_color('none')
ax.spines['right'].set_color('none')
ax.spines['left'].set_position(('data',0))
ax.spines['bottom'].set_position(('data',0))
plt.show()

View File

@@ -0,0 +1,33 @@
# changshi
import numpy as np
import matplotlib.pyplot as plt
# 定义数据集
x = np.linspace(-3,3,50)
y1 = 2*x+1
y2 = x**2
# 绘制图像
plt.figure(num=3,figsize=(10,10))
plt.plot(x,y1)
plt.plot(x,y2,color='red',linewidth=1,linestyle='--')
# 定义坐标轴的范围及名称
plt.xlim((-5,5))
plt.ylim((0,10))
plt.xlabel('i am x')
plt.ylabel('i am y')
# 刻度
ticks = np.linspace(-1,2,5)
plt.xticks(ticks)
plt.yticks([-2,-1.8,-1,1.22,3],[r'$really\ bad$', r'$bad$', r'$normal$', r'$good$', r'$really\ good$'])
# 设置边框颜色
ax = plt.gca()
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
# 展示图像
plt.show()

703
Python/numpy/20随机数.md Normal file
View File

@@ -0,0 +1,703 @@
# 使用numpy产生随机数
numpy中的random模块包含了很多方法可以用来产生随机数这篇文章将对random中的一些常用方法做一个总结。
## 1、numpy.random.rand(d0, d1, ..., dn)
* 作用产生一个给定形状的数组其实应该是ndarray对象或者是一个单值数组中的值服从[0, 1)之间的均匀分布。
* 参数d0, d, ..., dn : int可选。如果没有参数则返回一个float型的随机数该随机数服从[0, 1)之间的均匀分布。
* 返回值ndarray对象或者一个float型的值
例子:
```py
# [0, 1)之间均匀分布的随机数3行2列
a = np.random.rand(3, 2)
print(a)
# 不提供形状
b = np.random.rand()
print(b)
输出
[[0.26054323 0.28184468]
[0.7783674 0.71733674]
[0.90302256 0.49303252]]
0.6022098740124009
```
## 2、numpy.random.uniform(low=0.0, high=1.0, size=None)
* 作用:返回一个在区间[low, high)中均匀分布的数组size指定形状。
* 参数:
* low, highfloat型或者float型的类数组对象。指定抽样区间为[low, high)low的默认值为0.0hign的默认值为1.0
* sizeint型或int型元组。指定形状如果不提供size则返回一个服从该分布的随机数。
例子:
```py
# 在[1, 10)之间均匀抽样数组形状为3行2列
a = np.random.uniform(1, 10, (3, 2))
print(a)
# 不提供size
b = np.random.uniform(1, 10)
print(b)
输出
[[5.16545387 6.3769087 ]
[9.98964899 7.88833885]
[1.37173855 4.19855075]]
3.899250175275188
```
## 3、numpy.random.randn(d0, d1, ..., dn)
* 作用返回一个指定形状的数组数组中的值服从标准正态分布均值为0方差为1
* 参数d0, d, ..., dn : int可选。如果没有参数则返回一个服从标准正态分布的float型随机数。
* 返回值ndarray对象或者float
例子:
```py
# 3行2列
a = np.random.randn(3, 2)
print(a)
# 不提供形状
b = np.random.randn()
print(b)
输出
[[-1.46605527 0.35434705]
[ 0.43408199 0.02689309]
[ 0.48041554 1.62665755]]
-0.6291254375915813
```
## 4、numpy.random.normal(loc=0.0, scale=1.0, size=None)
* 作用返回一个由size指定形状的数组数组中的值服从 μ=loc,σ=scale 的正态分布。
* 参数:
* loc : float型或者float型的类数组对象指定均值 μ
* scale : float型或者float型的类数组对象指定标准差 σ
* size : int型或者int型的元组指定了数组的形状。如果不提供size且loc和scale为标量不是类数组对象则返回一个服从该分布的随机数。
* 输出ndarray对象或者一个标量
例子:
```py
# 标准正态分布3行2列
a = np.random.normal(0, 1, (3, 2))
print(a)
# 均值为1标准差为3
b = np.random.normal(1, 3)
print(b)
输出
[[ 0.34912031 -0.08757564]
[-0.99753101 0.37441719]
[ 2.68072286 -1.03663963]]
5.770831320998463
```
## 5、numpy.random.randint(low, high=None, size=None, dtype='l')
* 作用:返回一个在区间[low, high)中离散均匀抽样的数组size指定形状dtype指定数据类型。
* 参数:
* low, highint型指定抽样区间[low, high)
* sizeint型或int型的元组指定形状
* dypte可选参数指定数据类型比如int,int64等默认是np.int
* 返回值如果指定了size则返回一个int型的ndarray对象否则返回一个服从该分布的int型随机数。
例子:
```py
# 在[1, 10)之间离散均匀抽样数组形状为3行2列
a = np.random.randint(1, 10, (3, 2))
print(a)
# 不提供size
b = np.random.randint(1, 10)
print(b)
# 指定dtype
c = np.random.randint(1, 10, dtype=np.int64)
print(c)
type(c)
输出
[[3 1]
[3 3]
[5 8]]
6
2
numpy.int64
```
## 6、numpy.random.random(size=None)
* 作用:返回从[0, 1)之间均匀抽样的数组size指定形状。
* 参数:
* sizeint型或int型的元组如果不提供则返回一个服从该分布的随机数
* 返回值float型或者float型的ndarray对象
* 例子:
```py
# [0, 1)之间的均匀抽样3行2列
a = np.random.random((3, 2))
print(a)
# 不指定size
b = np.random.random()
print(b)
输出
[[0.80136714 0.63129059]
[0.04556679 0.04433006]
[0.09643599 0.53312761]]
0.32828505898057136
```
# numpy API
## 简单的随机数据
<div id="cnblogs_post_body" class="blogpost-body">
<h1>随机抽样&nbsp;(<tt class="xref py py-mod docutils literal"><span class="pre">numpy.random</span></tt>)</h1>
<div id="simple-random-data" class="section">
<h2><a name="t1"></a>简单的随机数据</h2>
<table class="longtable docutils" border="1"><colgroup><col width="40%"><col width="60%"></colgroup>
<tbody valign="top">
<tr class="row-odd">
<td>
<p><a class="reference internal" title="numpy.random.rand" href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.random.rand.html#numpy.random.rand" target="_blank"><tt class="xref py py-obj docutils literal"><span class="pre">rand</span></tt></a>(d0,&nbsp;d1,&nbsp;...,&nbsp;dn)</p>
</td>
<td>
<p>随机值</p>
<div class="cnblogs_code">
<pre>&gt;&gt;&gt; np.random.rand(3,2)
array([[ 0.14022471, 0.96360618], #random
[ 0.37601032, 0.25528411], #random
[ 0.49313049, 0.94909878]]) #random</pre>
</div>
</td>
</tr>
<tr class="row-even">
<td>
<p><a class="reference internal" title="numpy.random.randn" href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.random.randn.html#numpy.random.randn" target="_blank"><tt class="xref py py-obj docutils literal"><span class="pre">randn</span></tt></a>(d0,&nbsp;d1,&nbsp;...,&nbsp;dn)</p>
</td>
<td>
<p>返回一个样本,具有标准正态分布。</p>
<p class="rubric">Notes</p>
<p>For random samples from&nbsp;<img class="math" src="http://docs.scipy.org/doc/numpy/_images/math/93af1f49bf6bbf05f549f49609becdb5f7039538.png" alt="技术分享">, use:</p>
<div class="cnblogs_code">
<pre>sigma * np.random.randn(...) + mu</pre>
</div>
<p class="rubric">Examples</p>
<div class="cnblogs_code">
<pre>&gt;&gt;&gt; np.random.randn()
2.1923875335537315 #random</pre>
</div>
<p>Two-by-four array of samples from N(3, 6.25):</p>
<div class="cnblogs_code">
<pre>&gt;&gt;&gt; 2.5 * np.random.randn(2, 4) + 3
array([[-4.49401501, 4.00950034, -1.81814867, 7.29718677], #random
[ 0.39924804, 4.68456316, 4.99394529, 4.84057254]]) #random</pre>
</div>
</td>
</tr>
<tr class="row-odd">
<td>
<p><a class="reference internal" title="numpy.random.randint" href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.random.randint.html#numpy.random.randint" target="_blank"><tt class="xref py py-obj docutils literal"><span class="pre">randint</span></tt></a>(low[,&nbsp;high,&nbsp;size])</p>
</td>
<td>
<p>返回随机的整数,位于半开区间 [low, high)。</p>
<div class="cnblogs_code">
<pre>&gt;&gt;&gt; np.random.randint(2, size=10)
array([1, 0, 0, 0, 1, 1, 0, 0, 1, 0])
&gt;&gt;&gt; np.random.randint(1, size=10)
array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0])</pre>
</div>
<p>Generate a 2 x 4 array of ints between 0 and 4, inclusive:</p>
<div class="cnblogs_code">
<pre>&gt;&gt;&gt; np.random.randint(5, size=(2, 4))
array([[4, 0, 2, 1],
[3, 2, 2, 0]])</pre>
</div>
</td>
</tr>
<tr class="row-even">
<td>
<p><a class="reference internal" title="numpy.random.random_integers" href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.random.random_integers.html#numpy.random.random_integers" target="_blank"><tt class="xref py py-obj docutils literal"><span class="pre">random_integers</span></tt></a>(low[,&nbsp;high,&nbsp;size])</p>
</td>
<td>
<p>返回随机的整数,位于闭区间 [low, high]。</p>
<p class="rubric">Notes</p>
<p>To sample from N evenly spaced floating-point numbers between a and b, use:</p>
<div class="cnblogs_code">
<pre>a + (b - a) * (np.random.random_integers(N) - 1) / (N - 1.)</pre>
</div>
<p>Examples</p>
<div class="cnblogs_code"><div class="cnblogs_code_toolbar"><span class="cnblogs_code_copy"><a href="javascript:void(0);" onclick="copyCnblogsCode(this)" title="复制代码"><img src="//common.cnblogs.com/images/copycode.gif" alt="复制代码"></a></span></div>
<pre>&gt;&gt;&gt; np.random.random_integers(5)
4
&gt;&gt;&gt; type(np.random.random_integers(5))
&lt;type int&gt;
&gt;&gt;&gt; np.random.random_integers(5, size=(3.,2.))
array([[5, 4],
[3, 3],
[4, 5]])</pre>
<div class="cnblogs_code_toolbar"><span class="cnblogs_code_copy"><a href="javascript:void(0);" onclick="copyCnblogsCode(this)" title="复制代码"><img src="//common.cnblogs.com/images/copycode.gif" alt="复制代码"></a></span></div></div>
<p>Choose five random numbers from the set of five evenly-spaced numbers between 0 and 2.5, inclusive (<em>i.e.</em>, from the set&nbsp;<img class="math" src="http://docs.scipy.org/doc/numpy/_images/math/260812782a8a4f35a929d637a38520175045eaa2.png" alt="技术分享">):</p>
<div class="cnblogs_code">
<pre>&gt;&gt;&gt; 2.5 * (np.random.random_integers(5, size=(5,)) - 1) / 4.
array([ 0.625, 1.25 , 0.625, 0.625, 2.5 ])</pre>
</div>
<p>Roll two six sided dice 1000 times and sum the results:</p>
<div class="cnblogs_code">
<pre>&gt;&gt;&gt; d1 = np.random.random_integers(1, 6, 1000)
&gt;&gt;&gt; d2 = np.random.random_integers(1, 6, 1000)
&gt;&gt;&gt; dsums = d1 + d2</pre>
</div>
<p>Display results as a histogram:</p>
<div class="cnblogs_code">
<pre>&gt;&gt;&gt; import matplotlib.pyplot as plt
&gt;&gt;&gt; count, bins, ignored = plt.hist(dsums, 11, normed=True)
&gt;&gt;&gt; plt.show()</pre>
</div>
<p>&nbsp;</p>
</td>
</tr>
<tr class="row-odd">
<td>
<p><a class="reference internal" title="numpy.random.random_sample" href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.random.random_sample.html#numpy.random.random_sample" target="_blank"><tt class="xref py py-obj docutils literal"><span class="pre">random_sample</span></tt></a>([size])</p>
</td>
<td>
<p>返回随机的浮点数,在半开区间 [0.0, 1.0)。</p>
<p>To sample&nbsp;<img class="math" src="http://docs.scipy.org/doc/numpy/_images/math/e9a05a99f961e8f094b3869fcddd366857d7b0d9.png" alt="技术分享">&nbsp;multiply the output of&nbsp;<a class="reference internal" title="numpy.random.random_sample" href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.random.random_sample.html#numpy.random.random_sample" target="_blank"><tt class="xref py py-obj docutils literal"><span class="pre">random_sample</span></tt></a>&nbsp;by&nbsp;<em class="xref py py-obj">(b-a)</em>&nbsp;and add&nbsp;<em class="xref py py-obj">a</em>:</p>
<div class="cnblogs_code">
<pre>(b - a) * random_sample() + a</pre>
</div>
<p>Examples</p>
<div class="cnblogs_code">
<pre>&gt;&gt;&gt; np.random.random_sample()
0.47108547995356098
&gt;&gt;&gt; type(np.random.random_sample())
&lt;type float&gt;
&gt;&gt;&gt; np.random.random_sample((5,))
array([ 0.30220482, 0.86820401, 0.1654503 , 0.11659149, 0.54323428])</pre>
</div>
<p>Three-by-two array of random numbers from [-5, 0):</p>
<div class="cnblogs_code">
<pre>&gt;&gt;&gt; 5 * np.random.random_sample((3, 2)) - 5
array([[-3.99149989, -0.52338984],
[-2.99091858, -0.79479508],
[-1.23204345, -1.75224494]])</pre>
</div>
<p>&nbsp;</p>
</td>
</tr>
<tr class="row-even">
<td>
<p><a class="reference internal" title="numpy.random.random" href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.random.random.html#numpy.random.random" target="_blank"><tt class="xref py py-obj docutils literal"><span class="pre">random</span></tt></a>([size])</p>
</td>
<td>
<p>返回随机的浮点数,在半开区间 [0.0, 1.0)。</p>
<p>官网例子与random_sample完全一样</p>
</td>
</tr>
<tr class="row-odd">
<td>
<p><a class="reference internal" title="numpy.random.ranf" href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.random.ranf.html#numpy.random.ranf" target="_blank"><tt class="xref py py-obj docutils literal"><span class="pre">ranf</span></tt></a>([size])</p>
</td>
<td>
<p>返回随机的浮点数,在半开区间 [0.0, 1.0)。</p>
<p>官网例子与random_sample完全一样</p>
</td>
</tr>
<tr class="row-even">
<td>
<p><a class="reference internal" title="numpy.random.sample" href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.random.sample.html#numpy.random.sample" target="_blank"><tt class="xref py py-obj docutils literal"><span class="pre">sample</span></tt></a>([size])</p>
</td>
<td>
<p>返回随机的浮点数,在半开区间 [0.0, 1.0)。</p>
<p>官网例子与random_sample完全一样</p>
</td>
</tr>
<tr class="row-odd">
<td>
<p><a class="reference internal" title="numpy.random.choice" href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.random.choice.html#numpy.random.choice" target="_blank"><tt class="xref py py-obj docutils literal"><span class="pre">choice</span></tt></a>(a[,&nbsp;size,&nbsp;replace,&nbsp;p])</p>
</td>
<td>
<p>生成一个随机样本,从一个给定的一维数组</p>
<p class="rubric">Examples</p>
<p>Generate a uniform random sample from np.arange(5) of size 3:</p>
<div class="cnblogs_code">
<pre>&gt;&gt;&gt; np.random.choice(5, 3)
array([0, 3, 4])
&gt;&gt;&gt; #This is equivalent to np.random.randint(0,5,3)</pre>
</div>
<p>Generate a non-uniform random sample from np.arange(5) of size 3:</p>
<div class="cnblogs_code">
<pre>&gt;&gt;&gt; np.random.choice(5, 3, p=[0.1, 0, 0.3, 0.6, 0])
array([3, 3, 0])</pre>
</div>
<p>Generate a uniform random sample from np.arange(5) of size 3 without replacement:</p>
<div class="cnblogs_code">
<pre>&gt;&gt;&gt; np.random.choice(5, 3, replace=False)
array([3,1,0])
&gt;&gt;&gt; #This is equivalent to np.random.permutation(np.arange(5))[:3]</pre>
</div>
<p>Generate a non-uniform random sample from np.arange(5) of size 3 without replacement:</p>
<div class="cnblogs_code">
<pre>&gt;&gt;&gt; np.random.choice(5, 3, replace=False, p=[0.1, 0, 0.3, 0.6, 0])
array([2, 3, 0])</pre>
</div>
<p>Any of the above can be repeated with an arbitrary array-like instead of just integers. For instance:</p>
<div class="cnblogs_code">
<pre>&gt;&gt;&gt; aa_milne_arr = [pooh, rabbit, piglet, Christopher]
&gt;&gt;&gt; np.random.choice(aa_milne_arr, 5, p=[0.5, 0.1, 0.1, 0.3])
array([pooh, pooh, pooh, Christopher, piglet],
dtype=|S11)</pre>
</div>
<p>&nbsp;</p>
</td>
</tr>
<tr class="row-even">
<td>
<p><a class="reference internal" title="numpy.random.bytes" href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.random.bytes.html#numpy.random.bytes" target="_blank"><tt class="xref py py-obj docutils literal"><span class="pre">bytes</span></tt></a>(length)</p>
</td>
<td>
<p>返回随机字节。</p>
<div class="cnblogs_code">
<pre>&gt;&gt;&gt; np.random.bytes(10)
eh\x85\x022SZ\xbf\xa4 #random</pre>
</div>
<p>&nbsp;</p>
</td>
</tr>
</tbody>
</table>
</div>
<div id="permutations" class="section">
<h2><a name="t2"></a>排列</h2>
<table class="longtable docutils" border="1"><colgroup><col width="40%"><col width="60%"></colgroup>
<tbody valign="top">
<tr class="row-odd">
<td>
<p><a class="reference internal" title="numpy.random.shuffle" href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.random.shuffle.html#numpy.random.shuffle" target="_blank"><tt class="xref py py-obj docutils literal"><span class="pre">shuffle</span></tt></a>(x)</p>
</td>
<td>
<p>现场修改序列,改变自身内容。(类似洗牌,打乱顺序)</p>
<div class="cnblogs_code">
<pre>&gt;&gt;&gt; arr = np.arange(10)
&gt;&gt;&gt; np.random.shuffle(arr)
&gt;&gt;&gt; arr
[1 7 5 2 9 4 3 6 0 8]</pre>
</div>
<p>&nbsp;</p>
<p>This function only shuffles the array along the first index of a multi-dimensional array:</p>
<div class="cnblogs_code">
<pre>&gt;&gt;&gt; arr = np.arange(9).reshape((3, 3))
&gt;&gt;&gt; np.random.shuffle(arr)
&gt;&gt;&gt; arr
array([[3, 4, 5],
[6, 7, 8],
[0, 1, 2]])</pre>
</div>
<p>&nbsp;</p>
</td>
</tr>
<tr class="row-even">
<td>
<p><a class="reference internal" title="numpy.random.permutation" href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.random.permutation.html#numpy.random.permutation" target="_blank"><tt class="xref py py-obj docutils literal"><span class="pre">permutation</span></tt></a>(x)</p>
</td>
<td>
<p>返回一个随机排列</p>
<div class="cnblogs_code">
<pre>&gt;&gt;&gt; np.random.permutation(10)
array([1, 7, 4, 3, 0, 9, 2, 5, 8, 6])</pre>
</div>
<div class="cnblogs_code">
<pre>&gt;&gt;&gt; np.random.permutation([1, 4, 9, 12, 15])
array([15, 1, 9, 4, 12])</pre>
</div>
<div class="cnblogs_code">
<pre>&gt;&gt;&gt; arr = np.arange(9).reshape((3, 3))
&gt;&gt;&gt; np.random.permutation(arr)
array([[6, 7, 8],
[0, 1, 2],
[3, 4, 5]])</pre>
</div>
<p>&nbsp;</p>
</td>
</tr>
</tbody>
</table>
</div>
<div id="distributions" class="section">
<h2><a name="t3"></a><span class="web-item">分布</span></h2>
<table class="longtable docutils" border="1"><colgroup><col width="40%"><col width="60%"></colgroup>
<tbody valign="top">
<tr class="row-odd">
<td>
<p><a class="reference internal" title="numpy.random.beta" href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.random.beta.html#numpy.random.beta" target="_blank"><tt class="xref py py-obj docutils literal"><span class="pre">beta</span></tt></a>(a,&nbsp;b[,&nbsp;size])</p>
</td>
<td>贝塔分布样本,在&nbsp;<tt class="docutils literal"><span class="pre">[0,&nbsp;<span class="pre">1]</span></span></tt>内。</td>
</tr>
<tr class="row-even">
<td>
<p><a class="reference internal" title="numpy.random.binomial" href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.random.binomial.html#numpy.random.binomial" target="_blank"><tt class="xref py py-obj docutils literal"><span class="pre">binomial</span></tt></a>(n,&nbsp;p[,&nbsp;size])</p>
</td>
<td>二项分布的样本。</td>
</tr>
<tr class="row-odd">
<td>
<p><a class="reference internal" title="numpy.random.chisquare" href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.random.chisquare.html#numpy.random.chisquare" target="_blank"><tt class="xref py py-obj docutils literal"><span class="pre">chisquare</span></tt></a>(df[,&nbsp;size])</p>
</td>
<td>卡方分布样本。</td>
</tr>
<tr class="row-even">
<td>
<p><a class="reference internal" title="numpy.random.dirichlet" href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.random.dirichlet.html#numpy.random.dirichlet" target="_blank"><tt class="xref py py-obj docutils literal"><span class="pre">dirichlet</span></tt></a>(alpha[,&nbsp;size])</p>
</td>
<td>狄利克雷分布样本。</td>
</tr>
<tr class="row-odd">
<td>
<p><a class="reference internal" title="numpy.random.exponential" href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.random.exponential.html#numpy.random.exponential" target="_blank"><tt class="xref py py-obj docutils literal"><span class="pre">exponential</span></tt></a>([scale,&nbsp;size])</p>
</td>
<td>指数分布</td>
</tr>
<tr class="row-even">
<td>
<p><a class="reference internal" title="numpy.random.f" href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.random.f.html#numpy.random.f" target="_blank"><tt class="xref py py-obj docutils literal"><span class="pre">f</span></tt></a>(dfnum,&nbsp;dfden[,&nbsp;size])</p>
</td>
<td>F分布样本。</td>
</tr>
<tr class="row-odd">
<td>
<p><a class="reference internal" title="numpy.random.gamma" href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.random.gamma.html#numpy.random.gamma" target="_blank"><tt class="xref py py-obj docutils literal"><span class="pre">gamma</span></tt></a>(shape[,&nbsp;scale,&nbsp;size])</p>
</td>
<td>伽马分布</td>
</tr>
<tr class="row-even">
<td>
<p><a class="reference internal" title="numpy.random.geometric" href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.random.geometric.html#numpy.random.geometric" target="_blank"><tt class="xref py py-obj docutils literal"><span class="pre">geometric</span></tt></a>(p[,&nbsp;size])</p>
</td>
<td>几何分布</td>
</tr>
<tr class="row-odd">
<td>
<p><a class="reference internal" title="numpy.random.gumbel" href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.random.gumbel.html#numpy.random.gumbel" target="_blank"><tt class="xref py py-obj docutils literal"><span class="pre">gumbel</span></tt></a>([loc,&nbsp;scale,&nbsp;size])</p>
</td>
<td>耿贝尔分布。</td>
</tr>
<tr class="row-even">
<td>
<p><a class="reference internal" title="numpy.random.hypergeometric" href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.random.hypergeometric.html#numpy.random.hypergeometric" target="_blank"><tt class="xref py py-obj docutils literal"><span class="pre">hypergeometric</span></tt></a>(ngood,&nbsp;nbad,&nbsp;nsample[,&nbsp;size])</p>
</td>
<td>超几何分布样本。</td>
</tr>
<tr class="row-odd">
<td>
<p><a class="reference internal" title="numpy.random.laplace" href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.random.laplace.html#numpy.random.laplace" target="_blank"><tt class="xref py py-obj docutils literal"><span class="pre">laplace</span></tt></a>([loc,&nbsp;scale,&nbsp;size])</p>
</td>
<td>拉普拉斯或双指数分布样本</td>
</tr>
<tr class="row-even">
<td>
<p><a class="reference internal" title="numpy.random.logistic" href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.random.logistic.html#numpy.random.logistic" target="_blank"><tt class="xref py py-obj docutils literal"><span class="pre">logistic</span></tt></a>([loc,&nbsp;scale,&nbsp;size])</p>
</td>
<td>Logistic分布样本</td>
</tr>
<tr class="row-odd">
<td>
<p><a class="reference internal" title="numpy.random.lognormal" href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.random.lognormal.html#numpy.random.lognormal" target="_blank"><tt class="xref py py-obj docutils literal"><span class="pre">lognormal</span></tt></a>([mean,&nbsp;sigma,&nbsp;size])</p>
</td>
<td>对数正态分布</td>
</tr>
<tr class="row-even">
<td>
<p><a class="reference internal" title="numpy.random.logseries" href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.random.logseries.html#numpy.random.logseries" target="_blank"><tt class="xref py py-obj docutils literal"><span class="pre">logseries</span></tt></a>(p[,&nbsp;size])</p>
</td>
<td>对数级数分布。</td>
</tr>
<tr class="row-odd">
<td>
<p><a class="reference internal" title="numpy.random.multinomial" href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.random.multinomial.html#numpy.random.multinomial" target="_blank"><tt class="xref py py-obj docutils literal"><span class="pre">multinomial</span></tt></a>(n,&nbsp;pvals[,&nbsp;size])</p>
</td>
<td>多项分布</td>
</tr>
<tr class="row-even">
<td>
<p><a class="reference internal" title="numpy.random.multivariate_normal" href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.random.multivariate_normal.html#numpy.random.multivariate_normal" target="_blank"><tt class="xref py py-obj docutils literal"><span class="pre">multivariate_normal</span></tt></a>(mean,&nbsp;cov[,&nbsp;size])</p>
</td>
<td>
<p>多元正态分布。</p>
<div class="cnblogs_code">
<pre>&gt;&gt;&gt; mean = [0,0]
&gt;&gt;&gt; cov = [[1,0],[0,100]] # diagonal covariance, points lie on x or y-axis</pre>
</div>
<div class="cnblogs_code">
<pre>&gt;&gt;&gt; import matplotlib.pyplot as plt
&gt;&gt;&gt; x, y = np.random.multivariate_normal(mean, cov, 5000).T
&gt;&gt;&gt; plt.plot(x, y, x); plt.axis(equal); plt.show()</pre>
</div>
<p>&nbsp;</p>
</td>
</tr>
<tr class="row-odd">
<td>
<p><a class="reference internal" title="numpy.random.negative_binomial" href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.random.negative_binomial.html#numpy.random.negative_binomial" target="_blank"><tt class="xref py py-obj docutils literal"><span class="pre">negative_binomial</span></tt></a>(n,&nbsp;p[,&nbsp;size])</p>
</td>
<td>负二项分布</td>
</tr>
<tr class="row-even">
<td>
<p><a class="reference internal" title="numpy.random.noncentral_chisquare" href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.random.noncentral_chisquare.html#numpy.random.noncentral_chisquare" target="_blank"><tt class="xref py py-obj docutils literal"><span class="pre">noncentral_chisquare</span></tt></a>(df,&nbsp;nonc[,&nbsp;size])</p>
</td>
<td>非中心卡方分布</td>
</tr>
<tr class="row-odd">
<td>
<p><a class="reference internal" title="numpy.random.noncentral_f" href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.random.noncentral_f.html#numpy.random.noncentral_f" target="_blank"><tt class="xref py py-obj docutils literal"><span class="pre">noncentral_f</span></tt></a>(dfnum,&nbsp;dfden,&nbsp;nonc[,&nbsp;size])</p>
</td>
<td>非中心F分布</td>
</tr>
<tr class="row-even">
<td>
<p><a class="reference internal" title="numpy.random.normal" href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.random.normal.html#numpy.random.normal" target="_blank"><tt class="xref py py-obj docutils literal"><span class="pre">normal</span></tt></a>([loc,&nbsp;scale,&nbsp;size])</p>
</td>
<td>
<p>正态(高斯)分布</p>
<p class="rubric">Notes</p>
<p>The probability density for the Gaussian distribution is</p>
<div class="math">
<p><img src="http://docs.scipy.org/doc/numpy/_images/math/2f8a02ce155191ed5a4ea8d776aa15fcaef26e1f.png" alt="技术分享"></p>
</div>
<p>where&nbsp;<img class="math" src="http://docs.scipy.org/doc/numpy/_images/math/fb6d665bbe0c01fc1af5c5f5fa7df40dc71331d7.png" alt="技术分享">&nbsp;is the mean and&nbsp;<img class="math" src="http://docs.scipy.org/doc/numpy/_images/math/bb6e1902efeb0b3704c6191ddce1f02707ab7d4b.png" alt="技术分享">&nbsp;the standard deviation. The square of the standard deviation,&nbsp;<img class="math" src="http://docs.scipy.org/doc/numpy/_images/math/dd3f23ceebfef553bff1607f84667d5cc6af7587.png" alt="技术分享">, is called the variance.</p>
<p>The function has its peak at the mean, and its “spread” increases with the standard deviation (the function reaches 0.607 times its maximum at&nbsp;<img class="math" src="http://docs.scipy.org/doc/numpy/_images/math/ad6d5400fce43a299a35b53a9661e54a284f1bad.png" alt="技术分享">&nbsp;and&nbsp;<img class="math" src="http://docs.scipy.org/doc/numpy/_images/math/fa3af8846dae3eb1c8913dace238ff110abb64b2.png" alt="技术分享"><a id="id3" class="reference internal" href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.random.normal.html#r217" target="_blank">&nbsp;[R217]</a>).</p>
<p>&nbsp;</p>
<p class="rubric">Examples</p>
<p>Draw samples from the distribution:</p>
<div class="cnblogs_code">
<pre>&gt;&gt;&gt; mu, sigma = 0, 0.1 # mean and standard deviation
&gt;&gt;&gt; s = np.random.normal(mu, sigma, 1000)</pre>
</div>
<p>Verify the mean and the variance:</p>
<div class="cnblogs_code">
<pre>&gt;&gt;&gt; abs(mu - np.mean(s)) &lt; 0.01
True
&gt;&gt;&gt; abs(sigma - np.std(s, ddof=1)) &lt; 0.01
True</pre>
</div>
<p>Display the histogram of the samples, along with the probability density function:</p>
<div class="cnblogs_code">
<pre>&gt;&gt;&gt; import matplotlib.pyplot as plt
&gt;&gt;&gt; count, bins, ignored = plt.hist(s, 30, normed=True)
&gt;&gt;&gt; plt.plot(bins, 1/(sigma * np.sqrt(2 * np.pi)) *
... np.exp( - (bins - mu)**2 / (2 * sigma**2) ),
... linewidth=2, color=r)
&gt;&gt;&gt; plt.show()</pre>
</div>
<p>&nbsp;</p>
</td>
</tr>
<tr class="row-odd">
<td>
<p><a class="reference internal" title="numpy.random.pareto" href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.random.pareto.html#numpy.random.pareto" target="_blank"><tt class="xref py py-obj docutils literal"><span class="pre">pareto</span></tt></a>(a[,&nbsp;size])</p>
</td>
<td>帕累托Lomax分布</td>
</tr>
<tr class="row-even">
<td>
<p><a class="reference internal" title="numpy.random.poisson" href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.random.poisson.html#numpy.random.poisson" target="_blank"><tt class="xref py py-obj docutils literal"><span class="pre">poisson</span></tt></a>([lam,&nbsp;size])</p>
</td>
<td>泊松分布</td>
</tr>
<tr class="row-odd">
<td>
<p><a class="reference internal" title="numpy.random.power" href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.random.power.html#numpy.random.power" target="_blank"><tt class="xref py py-obj docutils literal"><span class="pre">power</span></tt></a>(a[,&nbsp;size])</p>
</td>
<td>Draws samples in [0, 1] from a power distribution with positive exponent a - 1.</td>
</tr>
<tr class="row-even">
<td>
<p><a class="reference internal" title="numpy.random.rayleigh" href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.random.rayleigh.html#numpy.random.rayleigh" target="_blank"><tt class="xref py py-obj docutils literal"><span class="pre">rayleigh</span></tt></a>([scale,&nbsp;size])</p>
</td>
<td>Rayleigh&nbsp;分布</td>
</tr>
<tr class="row-odd">
<td>
<p><a class="reference internal" title="numpy.random.standard_cauchy" href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.random.standard_cauchy.html#numpy.random.standard_cauchy" target="_blank"><tt class="xref py py-obj docutils literal"><span class="pre">standard_cauchy</span></tt></a>([size])</p>
</td>
<td>标准柯西分布</td>
</tr>
<tr class="row-even">
<td>
<p><a class="reference internal" title="numpy.random.standard_exponential" href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.random.standard_exponential.html#numpy.random.standard_exponential" target="_blank"><tt class="xref py py-obj docutils literal"><span class="pre">standard_exponential</span></tt></a>([size])</p>
</td>
<td>标准的指数分布</td>
</tr>
<tr class="row-odd">
<td>
<p><a class="reference internal" title="numpy.random.standard_gamma" href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.random.standard_gamma.html#numpy.random.standard_gamma" target="_blank"><tt class="xref py py-obj docutils literal"><span class="pre">standard_gamma</span></tt></a>(shape[,&nbsp;size])</p>
</td>
<td>标准伽马分布</td>
</tr>
<tr class="row-even">
<td>
<p><a class="reference internal" title="numpy.random.standard_normal" href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.random.standard_normal.html#numpy.random.standard_normal" target="_blank"><tt class="xref py py-obj docutils literal"><span class="pre">standard_normal</span></tt></a>([size])</p>
</td>
<td>标准正态分布&nbsp;(mean=0, stdev=1).</td>
</tr>
<tr class="row-odd">
<td>
<p><a class="reference internal" title="numpy.random.standard_t" href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.random.standard_t.html#numpy.random.standard_t" target="_blank"><tt class="xref py py-obj docutils literal"><span class="pre">standard_t</span></tt></a>(df[,&nbsp;size])</p>
</td>
<td>Standard Students t distribution with df degrees of freedom.</td>
</tr>
<tr class="row-even">
<td>
<p><a class="reference internal" title="numpy.random.triangular" href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.random.triangular.html#numpy.random.triangular" target="_blank"><tt class="xref py py-obj docutils literal"><span class="pre">triangular</span></tt></a>(left,&nbsp;mode,&nbsp;right[,&nbsp;size])</p>
</td>
<td>三角形分布</td>
</tr>
<tr class="row-odd">
<td>
<p><a class="reference internal" title="numpy.random.uniform" href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.random.uniform.html#numpy.random.uniform" target="_blank"><tt class="xref py py-obj docutils literal"><span class="pre">uniform</span></tt></a>([low,&nbsp;high,&nbsp;size])</p>
</td>
<td>均匀分布</td>
</tr>
<tr class="row-even">
<td>
<p><a class="reference internal" title="numpy.random.vonmises" href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.random.vonmises.html#numpy.random.vonmises" target="_blank"><tt class="xref py py-obj docutils literal"><span class="pre">vonmises</span></tt></a>(mu,&nbsp;kappa[,&nbsp;size])</p>
</td>
<td>von Mises分布</td>
</tr>
<tr class="row-odd">
<td>
<p><a class="reference internal" title="numpy.random.wald" href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.random.wald.html#numpy.random.wald" target="_blank"><tt class="xref py py-obj docutils literal"><span class="pre">wald</span></tt></a>(mean,&nbsp;scale[,&nbsp;size])</p>
</td>
<td>瓦尔德(逆高斯)分布</td>
</tr>
<tr class="row-even">
<td>
<p><a class="reference internal" title="numpy.random.weibull" href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.random.weibull.html#numpy.random.weibull" target="_blank"><tt class="xref py py-obj docutils literal"><span class="pre">weibull</span></tt></a>(a[,&nbsp;size])</p>
</td>
<td>Weibull&nbsp;分布</td>
</tr>
<tr class="row-odd">
<td>
<p><a class="reference internal" title="numpy.random.zipf" href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.random.zipf.html#numpy.random.zipf" target="_blank"><tt class="xref py py-obj docutils literal"><span class="pre">zipf</span></tt></a>(a[,&nbsp;size])</p>
</td>
<td>齐普夫分布</td>
</tr>
</tbody>
</table>
</div>
<h2><a name="t4"></a>随机数生成器</h2>
<table class="longtable docutils" border="1"><colgroup><col width="40%"><col width="60%"></colgroup>
<tbody valign="top">
<tr class="row-odd">
<td>
<p><a class="reference internal" title="numpy.random.RandomState" href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.random.RandomState.html#numpy.random.RandomState" target="_blank"><tt class="xref py py-obj docutils literal">RandomState</tt></a></p>
</td>
<td>Container for the Mersenne Twister pseudo-random number generator.</td>
</tr>
<tr class="row-even">
<td>
<p><a class="reference internal" title="numpy.random.seed" href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.random.seed.html#numpy.random.seed" target="_blank"><tt class="xref py py-obj docutils literal"><span class="pre">seed</span></tt></a>([seed])</p>
</td>
<td>Seed the generator.</td>
</tr>
<tr class="row-odd">
<td>
<p><a class="reference internal" title="numpy.random.get_state" href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.random.get_state.html#numpy.random.get_state" target="_blank"><tt class="xref py py-obj docutils literal"><span class="pre">get_state</span></tt></a>()</p>
</td>
<td>Return a tuple representing the internal state of the generator.</td>
</tr>
<tr class="row-even">
<td>
<p><a class="reference internal" title="numpy.random.set_state" href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.random.set_state.html#numpy.random.set_state" target="_blank"><tt class="xref py py-obj docutils literal"><span class="pre">set_state</span></tt></a>(state)</p>
</td>
<td>Set the internal state of the generator from a tuple.</td>
</tr>
</tbody>
</table>
</div>

BIN
aa.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 701 KiB

View File

@@ -1,8 +0,0 @@
# 智能系统中的弱电系统
## 弱电系统与物联网
* 直流1.5V$\sim$ 36V
*
##

View File

@@ -1,3 +0,0 @@
# 综合布线图的工程技术
##

View File

@@ -1,22 +0,0 @@
# 课程概要
## 课程安排
## 考核标准
### 1+4+11个投名状4个单元作业1考试
* 投名状作业:提交一份设计图及项目说明。投名状啥的。路线图、结构图。
* 每个单元一个可选的作业:设计布线图,户型图+智慧家居的布线图+或者+综述性作业
* 每个单元包含一个设计作业。共4个设计作业选三个完成设计作业。
* 选一个单元,综合成一篇论文。
* 作业提交eai2019@126.com
## 主要内容
1. 物联网
2. 网络
3. 分析设计
4. 大数据后端

View File

@@ -1 +0,0 @@
##

View File

@@ -1,4 +1,3 @@
今天要做的事情:
# 主机配置-服务器搭建
## 需要了解的事情

View File

@@ -0,0 +1,24 @@
# 学习安排
## 具体的学习计划
* 每天早上一周的课程python实现
* 每天下午一周的课程python实现
* 每天晚上:阅读论文并总结。
## 方法
1. 涉及到基础知识进行补充,例如线性代数
2. 涉及到的编程知识进行补充例如Numpy、scikitlearn、scipy等。
也就是说,现在要同时学习三个东西。机器学习,机器学习依赖的数学基础,机器学习实现的编程基础。降低速度,尽量在一个月内,实现初步认知。
## 补充
应该对matplotlib和scipy的教程进行补充。教程部分只完成简单的说明即可。所有的例子手动运行敲一遍。教程该出简单的实例然后手动实现实例。
具体的内容,等到实践过程中进行学习。

View File

@@ -0,0 +1,16 @@
# 组会的PPT结构
## 情报利用的现状
## 联邦学习的现状
## 机器学习在情报利用领域可能的应用路径
## 拟打算应用的机器学习算法
## 面临的难题
## 解决问题的具体规划
## 最近做的界面的事情

View File

@@ -0,0 +1 @@
# 看论文工具与方法

View File

@@ -1,3 +1,4 @@
# 情报威胁与联邦学习
## 研究方向
* 情报威胁----定义系统的应用场景,包括输入输出。

View File

@@ -1,3 +1,4 @@
# 供应链金融
## 时间安排
上午:完成供应链金融的调查报告

View File

@@ -1,12 +1,20 @@
当前的主要任务:
# 机器学习
## 当前的主要任务:
现在处在研究的第一和第二阶段。关于第一阶段联邦学习的应用场景,主要由蒋师兄完成。第二阶段,学习联邦学习关联的基础知识,为第三阶段机器学习算法的实现和框架的搭建做好准备。
看完相关的文章和博客。然后开始学习用两周时间学习完成基础知识。在学习基础知识的时候使用tensorflow框架进行算法的运行。
-------------------
## 长久的时间计划:
* 必须在十一月份之前完成学习工作。那就到10月30号把。还有五本需要看的书。10月30号之前完全搞懂该领域的内容。
* 十一月份,进行调研,寻找大量相关的研究工作。
* 十二月份,对相关领域的算法进行实现。对算法进行改进。
> 感觉时间不够了啊,兄弟。你这需要做的事情有点多。国庆节,尽量恶补完成大部分机器学习的基础知识和主要的算法,然后国庆节后开始看论文。
--------------
学习路线
## 学习路线
### Python系列一周

View File

@@ -45,7 +45,7 @@ easy-window小程序。
### 工程部署使用nodejs封装工具发布。
* 使用electron-package对工程进行打包√
* 使用electron-build或者electron-asar对工程进行发布。创建安装程序。
* 使用electron-build或者electron-asar对工程进行发布。创建安装程序。
## 3 解决的bug问题

21
工作日志/总结.md Normal file
View File

@@ -0,0 +1,21 @@
## 第一周9.1-9.6
* 阅读漏洞利用的相关知识,证明了漏洞利用的不可行。
* 更换了开题的方向,转向联邦学习
## 第二周9.7-9.13
* 对联邦学习进行了一周的调研,了解了联邦学习是什么。
* 对情报利用的方式进行了讨论,对情报可能的利用方向进行了总结。
* 与公司进行对话,了解了情报利用利于相关的内容。
## 第三周9.14-9.20
* 完成了界面设计的一套方案。nodejs-electron-html/js/css-Cmakemake打通了界面设计的技术路径。
## 第四周9.21-9.27
* 机器学习任务的开始。明确了机器学习的学习路径。
* 完成了python3-numpy-scipy-matplotlib-pandas机器学习系列工具的学习。需要通过具体的编程项目进行熟练。
## 第五周9.28-10.4
* 吴恩达课程完成。
* 机器学习相关工具的熟练。

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

After

Width:  |  Height:  |  Size: 298 KiB

View File

@@ -0,0 +1,21 @@
# 使用numpy实现线性回归
import numpy as np
import matplotlib.pyplot as plt
# 尝试使用matplot画了一个三维图像。
x_1 = np.arange(0,10,0.1)
x_1 = np.expand_dims(x_1,0)
x_1 = np.repeat(x_1,100,axis=0)
x_2= np.arange(0,10,0.1)
x_2 = np.expand_dims(x_2,1)
x_2 = np.repeat(x_2,100,axis=1)
y = ((x_1+x_2-10)**2)
print(x_1.flatten())
ax = plt.axes(projection='3d')
ax.scatter3D(x_1.flatten(),x_2.flatten(),y.flatten(),c=y, cmap='Greens')
plt.show()

View File

@@ -0,0 +1,26 @@
# 吴恩达线性回归第一部分
# 这是第一个线性回归(机器学习算法)用来预测房价,感觉有点神奇。
import numpy as np
# 构造了样本数据集
x = np.arange(0,100,1)
loss = np.random.rand(100)-0.5
y = 2*x+6+loss
# 对样本数据集进行线性回归y=a0+a1x
# 给出参数的初始值
a0 = -10
a1 = -10
w = 0.0001 # 表示梯度下降速度
# 对a0进行梯度下降
for i in range(1000):
a0 = a0-100*w*(1/100)*np.sum(a0+a1*x-y)
a1 = a1-w*(1/100)*np.sum((a0+a1*x-y)*x)
print(a0,a1)

View File

@@ -1,3 +0,0 @@
# 用来实现吴恩达的机器学习课程

View File

@@ -1,3 +1,4 @@
## 机器学习分类
* 有监督的学习:给出了正确答案
* 回归问题:预测连续的数值输出。(输出是连续的,一条曲线)
* 分类问题:预测离散的值输出。(输出局限于几个类别,有界离散的输出)
@@ -7,14 +8,6 @@
* 聚类问题:将相同主体的新闻聚集到一块。社交网络划分为不同的圈子。结果不是事先给出的,通过机器学习,发现数据的内部结构。
## 典型问题
* 房屋面积-房屋价格:回归问题

View File

@@ -0,0 +1,50 @@
# 线性回归
## 房价问题
* 数据集构成
* 训练集
* 样本数量m
* 样本特征$x_i$
* 目标变量y
## 假设函数
* 假设函数
$$h(x)=\theta_0+\theta_1 x$$
* 模型参数$\theta_0,\theta_1$
## 代价函数
* 损失函数、代价函数loss/cost function:平方误差代价函数
$$
J(\theta_0,\theta_1)=\frac{1}{2m}\sum_1^m(h(x_i)-y_i)^2
$$
* 目标函数:
$$
minimize_{\theta_0,\theta_1} J(\theta_0,\theta_1)
$$
## 梯度下降
* 目标
$$
min_{\theta_1,\theta_2,\dots}J(\theta_1,\theta_2,\dots)
$$
* 给定$\theta$的初始值。不断修改$\theta$的值,使代价函数最小。统计学上使用全局的最小二乘法实现参数估计,计算机科学上使用局部迭代的梯度下降算法实现参数估计。
* 梯度下降算法的公式
$$
\theta_j = \theta_j - \alpha\frac{\partial}{\partial \theta_j}J(\theta_1,\theta_2,\dots)
$$
* 吴恩达给出了梯度下降函数的解释,当导数为正时,表示函数递增,此时自变量减去一个正值,自变量减小,函数值下降。当导数为负时,表示函数递减,此时自变量减去一个负值,自变量增加,函数值增加。
## batch梯度下降
* 每一步都遍历了样本中所有的数据。
## 梯度下降算法与最小二乘法区别
* 给出假设函数(这是拟合的函数)
* 使用最小二乘算法进行参数估计。这个是统计学的方法,利用样本的统计学特征,一次性全局计算准确的最小损失函数。
* 使用梯度下降算法,进行参数估计。这是一个迭代的方法,利用每一条数据,更新参数。

Binary file not shown.

Before

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 38 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 116 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 70 KiB

View File

@@ -1,42 +0,0 @@
# 绪论
## 1 语言
### 语言的一般特性
* 媒体性
* 规范性
* 演进性
* 抽象性
* 冗余多义性
### 程序设计语言的特性
* 程序设计语言是人工语言
* 主要通信对象是机器
* 用于表达软件
### 程序设计语言的作用(为什么研究)
* 计算机软硬件技术的窗口
* 人们研究计算表达的形势
* 它和计算机理论研究联系最为密切
* 研究有利于与提高软件开发人员的素质
* 有利于开发专用用语言或界面语言
* 有利于新领域语言的发展
* 有利于通用语言的标准化规范化
## 2 程序设计语言的定义与处理器
> 一个程序设计语言的实际存在是《语言规格说明书》。一个程序设计语言的实际存在是改语言程序的处理器。
### 解释器
解释器读入一段相对完整源代码(多数情况下是一句)翻译为目标代码后,立即解释执行。
### 编译器
编译器读入一个独立的编译单元(程序的逻辑单元,如主程序 、函数,子程序。或若干个逻辑单元组成的编译单元,如文件、模块、包) 翻译为可执行的目标代码单元,经过连接必要的库支持例程成为可执行内存映象,加载到内存中运行,由于是按单元翻译,可以经过上下文分析作若干次优化,目标代码质量高。
### 元语言(metalanguage)
表达每一个语法特征
* 字符集、词条表由它们提供标识符、运算符、关键字、空格、限制符、各种数字量、字符串常量等语法概念。
* 注释 注释符号之内(或以后)的符号串是为人们阅读,处理器要略去的。
* 语法结构定义,定义以上符号组合的合法结构。它给出语句、表达式、程序单元、块(如FORTRAN的循环域)、作用域、嵌套与结合等语法概念。

View File

@@ -1,117 +0,0 @@
# 发展与分类
## 1 历史
![](\image/发展历史.png)
### 程序设计语言简史
* 1945 ENIAC 真空管计算机
* 1946 冯诺依曼机构UNIVAC-1计算机
* 50年代 FORTRAN ALGOL COBOL
* 60年代 APL SNOBOL LOGO PASCAL
* 70年代 C LISP Perlog Edison
* 80年代 面向对象Smalltalk C++ SQL
## 2 分类
### 对机器依赖程度
* 低级语言:机器语言和汇编语言
* 中级语言:编程操纵机器硬件,不涉及地址码和操作码。
* 高级语言:独立于机器
### 应用领域
* 商用语言
* 科学计算
* 系统程序设计
* 模拟预演
* 正文处理
* 实时处理
* 嵌入式应用
* 人工智能应用
* 查询和命令语言
* 教学语言
* 打印专用
* 专用与某种数据结构
```
/*
引入外部文件进行构建
能够定义文本的名字,实现文本与排版的分离
能够进行文本与文本的嵌套,支持嵌套处理
能够使用反斜杠转义特殊符号
支持链式处理
全局默认控制对象env
定义新的处理函数默认一个文本输入对象,默认一个文本输出对象。前边的函数可以覆盖处理前边的函数。内部函数的优先级更高。
能够定义函数所处的模块。
自顶向下的设计过程。从全局到局部。所以后边可以覆盖前边,细节覆盖总体布局。
链式处理,是对原来文本的处理,不是生成新的文本
定义引用,引用编号,自动引用
*/
import another_name.pp
import another_progrom.pp
//paper 模块的leftboder函数
env.paper.leftborder(29)
textname={i am a good man}
textname.fix(delete)
text1,text2,text3.fix()
pic1,pic2.middle()
{zhesh 'pic.hello()' iwe\alpha nben}.hello(middle,big).world(45size).print()
def newp(hello,txt):
this is content
enddef
```
### 实现计算方式
* 编译型语言
* 解释型语言
### 使用方式
* 交互式语言
* 非交互式语言
### 程序设计范型
单范型语言:程序组织和实现计算的模式
* 命令式语言
* 面向对象语言
* 数据流语言
* 函数式语言
* 逻辑式语言
* 并发程序设计语言
多范型语言:
包含多种范型的程序设计语言。
### 断代
* 第一代:机器语言
* 第二代:汇编语言
* 第三代:高级语言
* 第四代:非过程语言
* 第五代:自然语言(人工智能)
## 3 形式语言与图灵机
### 形式语言特点
* 符号集
* 转换规则
### 图灵机五元组
$$(q_i,S_j,S_k,(R,L,N),q_j)$$
机器当前状态读入$S_j$后写入$S_k$,进行操作$R/L/N$,转换为装填$q_j$。
### 指令系统
* CISC(reduced instruction set computer)。指令复杂,执行较慢。不利于大规模集成电路设计。
* RISC(complex instruction set computer)。简化了指令系统,适合大规模集成电路设计。执行速度快。提供高级程序设计语言支持,简化了编程设计过程。
## 4 发展过程
* 汇编语言。与机器指令一一对应。
* 虚拟机,在计算机机器语言之上,虚拟各种不同语言的计算机环境。
* 语言要求Go、Python、Scala。

View File

@@ -1,274 +0,0 @@
# 设计概述
## 1 表示与抽象
### 表达与抽象的概念
* 表示是对事物抽象的表达。
* 抽象是对论题本质的提取。
* 同一个事物在不同抽象层次上的表示。自然语言描述、高级语言表示、汇编语言表示、机器语言表示。
* 上层抽象可以用多种下层抽象的实现。
### 不同抽象层次
* 客观世界自然语言描述
* 数学模型数学语言描述
* 程序设计程序语言描述
* 机器指令机器语言描述
### 显示表示和隐式表示
* 显示表示float n=3.14指明n的类型。
* 隐式表示 n=3.14缺省为浮点类型。
### 聚合表示和分散表示。
* 分散表示。整型,浮点型等数据之间的+运算使用不同的运算符。
* 聚合表示。所有类型的+运算都可以使用+运算符实现。或者同一个函数实现。
## 2 设计目标
### 具体目标
定义一组能表示某种范型的特征集,每个特征有严格定义并可在机器上高效实现,程序员可灵活运用这些特征表达它所希望的任何计算。
### 评价标准
* 模型有力 Model Power
* 语义清晰 Semantic Clarity
* 移植性好 Portability
* 可读性好 Readability
* 程序质量 Quality
* 安全性
* 并发
* 方便 Convenience
* 简单 Simplicity
* 高效 Efficiency
* 灵活性 Flexibility
* 可扩充性 Extensible
* 可重用性 Reusable
## 3 设计准则
### 具体准则
* 频度准则:越常用越简单
* 结构一致:程序结构和计算的逻辑结构一致,可读、方便
* 局部性 Locality
- 只有全局变量 Basic
- 不鼓励全局变量 Pascal, C
- 无全局变量函数式 Java
* 词法内聚 Lexical Coherence : 变量在使用处就近声明Pascal 声明和语句严格分开)
* 语法一致性
* 安全性Security
* 正交性和正规性
* 数据隐藏。封装,以名字封装内部数据设计者可见使用者不可见
* 抽象表达
## 4 规格说明
### 概述
规格说明用来定义一个语言文本的语法和语义。用于表达程序设计语言的的语言成为元语言。
* 形式语法:以形式结构规则的语言元素组合规则。
* 微语法词法Lexicon
* 宏语法:定义特征规则
### 字符集
* 允许出现在语言的程序里出现的字符的全体
### 词法分析
由程序的字符序列得到词法元素序列的过程就是词法分析。编译器处理表示源程序的字符序列,根据词法规则做词法分析,将 源程序切分为符合词法的段识别出源程序的有意义单词token) 。词法分析得到一个(表达被分析的源程序的)单词流,流中各单词 标明了词法类别。词法分析中抛弃所有无保留价值的分隔符(如空白符)和噪声词。
词法分析通常采用最长可能原则,确定可能成为单词的最长字符串。
词法分类主要包括以下内容
* 标识符:文字形式的词法对象,用于表示程序对象的名字。
* 关键字:语言规定了特殊意义的标识符
* 运算符:有预定义意义的特殊字符或特殊字符序列
* 分隔符:用于分隔程序里的不同词法元素的特殊符号或标识符。空格,换行和制表符等,通常作为语法元素的分隔符。
### 语法分析
* 语法分析定义
语法规定位于词法层次之上的程序结构。
语法用于确定一个输入序列是否合法的程序。程序存在多个不同层次的合法性问题:
局部结构 例C程序里的if 之后是不是左括号,括号是否配对
上下文关系 例:变量使用前是否有定义,使用是否符合类型的要求
深层问题 例:使用变量的值之前,变量是否已经初始化
* 语法分析图
![](image/语法分析图.png)
其中方框为非终结符,圆和椭圆形为终结符。箭头指向构造流向。每个非终结符又可开始一个语法图(一条产生式规则) 。与EBNF完全对应[ ]以'短路'绕道表示,{ }以迥环表示,小圆弧是有意义的,表示流向。有的语法图在环线上注上数字表示最多转几次。
* 语法分析分类
* “自顶向下” 释义则从文法的起始符开始,按可能产生的表达式寻 找语句相同的结构匹配。每一步都产生下一个可能的源符号串,找到再 往下走。
* “由底向上”释义则相反,它先查找源代码的各个符号串,看它能 否匹配归结为产生式左边的非终结符如果有含混则向前多读入k个符 号串,为此归约下去,一个短语一个短语,最后到达起始符号串,归约 的过程就形成了释义树。
### 语义分析
> 在最后再详细补充
程序通常要在计算机上执行,因此按照程序的运行步骤或操作来说明程序设计语言是很自然的,这就是所谓的操作语义学。大多数程序设计语言的非形式化语义都是用这种方式说明的。例如 Pascal中while命令的操作语义可说明如下
```
执行命令while E do C其步骤为
(1) 对表达式E求值产生一个真假值。
(2) 如果值为true则执行命令C然后从(1)开始重复。
(3) 如果值为false终止。
```
* 指称语义。为每个程序短语指派一数学实体(指称)为其意义。典型情况是将其输入映射为输出的函数。例如,一个表达式的指称是将环境和存储映射为值的函数。一个命令的指称是将环境、初始存储映射为最终存储的函数。
```
execute 〖while E do C〗 =
let execute-while env sto =
let truth-value tr=evaluate〖E〗 env sto in
if tr
then execute-while env (execute 〖C〗 env sto)
else sto
in
execute-while
```
* 公理语义。它只定义证明规则(公理及推理规则),以此证明程序的某些性质。这些证明规则在某种意义上就是抽象的语义。公理语义主要用于程序验证,语言理解,语言规范/标准化等方面,对编译 、解释器的 没有直接的作用。把语言的公理描述看作是该语言的一个理论,该理论由三部分组成:
* 公理集 元语言描述的不加证明的公理集如:|- 0 succ 0 即自然数0的后继大于0是一个定理(由|-表示)也是一条公理。
* 语法规划集 以它来确定什么是合式公式。
* 推理规则集 从已确立的定理演绎新定理。
* 代数语义。代数语义把语义模型的集合看成是一个代数结构,模型簇 对应为代数系统。
## 5 上下文无关文法
### 文法Grammar
文法可导出该语言所有可能的句子形式地一个文法G是一个四元组
$$
G=(S,N,T,P)
$$
* 其中T是终结符号串的有限集。
* N是非终结符号串的有限集是文法中提供的成分概念相当于英语动词短语、名词短语或定语从句等句子成分的符号表示。
* T∩N = Φ,即它们是不相交的。
* S是起始符号串S∈N。
* P是产生式一般形式是:α→β α,β∈(TN)*。“→”表示左端可推导出右端,如α→β,α→Υ,α→δ则可写为: α→β|Υ
如果产生式将语言的非终结符中的每一个标记都推得为终结符号,则这一组产生式集即为该语言的全部文法。
### 文法的递归表示
文法的递归表示在形式文法中是必须的。例2-1 整数的产生式表示法:
```
<digit>→0|1|2|3|4|5|6|7|8|9
<Integer>→<digit> 一位数字是整数
<Integer>→<digit><digit> 两位数字也是整数
<Integer>→<digit>…<digit> n位数字也是整数
可以写成:
<Integer>→<digit>|<Integer><digit>|<digit> <Integer>
```
> α→αβ是左递归产生式,而α→βα是右递归产生式,也叫尾递归的。不同型式的产生式决定了不同型式的文法。
### Chomsky文法
> 希腊字母是终结符。大写字母是非终结符。
* **0型文法**如果对产生式α→β左端和右端不加任何限制:
```
α∈(NT) ,β∈(NT)*
```
这种文法对应的语言是递归可枚举语言。在编译理论中,图灵机(或双向下推机)可以识别这种语言。
* **1型文法**如果产生式形如:
```
αAβ→αα,β∈(NT)* A∈N B∈(NT)
```
则叫做上下文相关文法,对应的语言是上下文敏感语言。线性有界自动机可识别这种语言。(因为左端含有非终结符,每一个推导式与左右两边的非终结符有关,所以是上下文有关文法)
* **2型文法**如果产生式形如:
```
A→α α∈ (NT)* A∈N
```
左端不含终结符且只有一个非终结符。这种文法叫上下文无关文法。对应的语言即上下文无关语言。非确定下推机能识别这种语言。
* 3型文法 如果产生式形如:
```
A→ αB|Bα α∈T* AB ∈N
```
左端不含终结符且只有一个非终结符。右端最多也只有一个非终结符且不在最左就在最右端。这种文法叫做正则文法,对应为正则语言。有限自动机可识别这种语言。显然,这种文法经置换可消除右端非终结符,使每一产生式均可用一终结符的正则表达式表达。
例2-2 所有产生式的非终结符均可置换为终结符表达式。
```
设产生式是:
N={SR, Q}, T={abc}
P={S→Ra S→Q R→Qb Q→c}
则有:
S→Ra→Qba→cba|S→Q→c
R→Qb→cb
Q→c
```
![](image/chomsky文法的关系.png)
### BNF和EBNF
BNF就是上下文无关文法的表示法。
* ::= '定义为',即产生式中的“→”符号。
* < > 表示所括符号串是非终结符号串。
* | '或者'表示左右两边符号串序列是可替换的。终结符、关键字、标点符号直接写在产生式中。
BNF示例
```
<unsigned integer> ::= <digit>
| <unsigned integer> <digit>
<integer> ::= +<unsigned integer>
|-<unsigned integer>
|<unsigned integer>
<identifier> ::= <letter>
| <idenfitier> < digit>
| <identifier> <letter>
```
增加更多内容
* "[ ]"表示括号内的内容是可选的。
* "{ }"表示括号内的内容可重复0至多次。
* "*"是指可以重复多次。
* "+"是指可以出现多次
* "?"意思是操作符左边的符号或括号中的一组符号是可选项可以出现0到多次
```
<integer> ::= [ +|-]<unsigned integer>
<identifier> ::= <letter> {<digit> | <letter>}
<unsigned integer> ::= <digit>
<identifier> ::= <letter> {<digit> | < letter>}*
```
EBNF将BNF与正则表达式结合起来
* 其元语符号变动是: 增加[ ]、{ } 、( )(表示成组)、.(表示产生式终结)。[ ] 、{ } 意义同前,旨在消除或减少递归表达。
* 取消非终结符的尖括号,至少是产生式左端,为此符号串中空白用'_'连接。
* 为区别元符号和程序符号(程序中也有[ ]、 、()、.),程序中的终结符加引号,如'(' ')' '.'。
```
program ::= <program_heading> '' <program_block> '.'.
program_heading ::= 'program' <identifier>[ '('<program_parameters> ')'].
program_parameters ::= <identifier_list>.
identifier_list ::= <identifier> {'' <identifier>} .
program_block ::= <block>.
block ::= <label_declaration_part> <constant_declaration_part>
<type_declaration_part><variable_declaration_part>
<procedure_and_function_declaration_part><statement_part>.
variable_declaration_part ::= ['var' <variable_declaration> ''
{<variabe_declaration> '' }].
variable_declaration ::= <identifier_list> '' <type_denoter>.
statement_part ::= compound_statement.
compound_statement ::= 'begin' <statement_sequence> 'end'.
statement_sequence ::= <statement> {'' <statement>}.
statement::=[<label> ''](<simple_statement>|<structured_statement>).
simple_statement ::= <empty_statement> | <assignment_statement> |
<procedure_statement> | < goto_statement>.
structured_statement ::= <compound_statement>|<conditional_statement>
|<repetitive_statement> | <with_statement>.
```

View File

@@ -1,19 +0,0 @@
# 过程式程序设计语言
## 1 值与类型
### 值与类型
* 值是对事物性态的表征和度量,而表征和度量总是在某个论域的某个抽象层次上,讨论问题的抽象层次不同取值也不同。
* 对值进行分类。每一个值都属于一个类型。
* 主要包括以下类型:
* 基本类型:整型实型浮点类型字符型真值型枚举型
* 以简单的基本类型可以构造结构类型:元组、数组、记录、结构、表
* 还可进一步组合成更复杂的复合类型:串、其他专用或更复杂的类型。
### 字面量、变量常量
* 字面量也称直接量,约定它的表示(名)就是它的值,且从它的表示可以得知其类型, 如1231.23e10's'"stock"TRUEdec
* 变量是代表任何值的标识符。一旦声明该标识符是什么类型,它在程序中只可取得该类型的某个值。变量只是一个数据的名字,它的值随时可变。
* 常量也可以是标识符。一旦某标识符声明为某类型的常量,则必须给它赋初值,且在程序中不得改变,它就成了某个值的代名词。

View File

@@ -1,20 +0,0 @@
# 指称语义的原理与应用
## 1 指称语义原理
### 指称语义定义
φ〖p〗→d (p∈Pd∈D)。
φ为短语p的语义函数D为语义域。语义域D中的数学实体d, 或以辅助函数表达的复杂数学实体d',称为该短语的数学指称物,即短语在语义函数下的指称语义。这样,程序的行为可以完全以数学实体表达。
### 语义函数
语义函数的变元是语法中的短语(当然可以是代表整个程序的短语如PROGRAM),其映射指称物即语义。
## 2 指称语义实例
## 3 程序抽象的语义描述
## 4 指称语义应用

View File

@@ -1,87 +0,0 @@
# 程序设计语言规格说明
## 1 语言字符集
允许出现在语言的程序里出现的字符的全体
## 2 词法
### 词法定义
构成程序的基本词法元素包括标识符、运算符、字面量、注释等。复杂的词需要明确定义的构词法,即词法
### 词法元素
* 标识符:文字形式的词法对象,用于表示语言里的关键字、程序对象的名字
* 关键字:语言规定了特殊意义的标识符
* 保留字语言中规定了特殊意义而且不允许程序员用于其他用途的标识符C语言中的关键字都是保留字。
* 运算符:有预定义意义的特殊字符或特殊字符序列。语言定义的运算、算术运算、逻辑运算
* 分隔符:用于分隔程序里的不同词法元素的特殊符号或标识符。空格,换行和制表符
### 词法分析
* 由程序的字符序列得到词法元素序列的过程就是词法分析。
* 编译器处理表示源程序的字符序列,根据词法规则做词法分析,将 源程序切分为符合词法的段,识别出源程序的有意义单词
* 词法分析得到一个(表达被分析的源程序的)单词流,流中各单词 标明了词法类别。
* 词法分析中抛弃所有无保留价值的分隔符(如空白符)和噪声词
* 词法分析通常采用最长可能原则,确定可能成为单词的最长字符串。
### 词法分析语法分析总过程
![](\image/词法分析.png)
## 3 语法
### 语法定义
语法用于确定一个输入序列是否合法的程序。程序存在多个不同层次的合法性问题:局部结构、上下文关系(静态语法结构)、深层问题(动态语法结构)。静态语法结构可以在编译过程中进行检查,动态语法结构只能在程序执行过程中检查合法性。
### 文法定义
文法产生符合语法的语言规则。
### 文法描述
$$
G=(S,N,T,P) S∈N,T∩N=Φ^*
$$
* T是终结符号串的有限集。
* N是非终结符号串的有限集。T∩N = Φ,即它们是不相交的。
* S是起始符号串 S∈N。
* P是产生式
$$
α→β \\α,β∈(TN)^*
$$
* “→”表示左端可推导出右端,如α→β, α→Υ, α→δ则可写为:α→β|Υ
* 如果产生式将语言的非终结符中的每一个标记都推得为终结符号, 则这一组产生式集即为该语言的全部文法。
## 4 Chomsky的四种文法
产生式左符号集→右符号集,由左符号集推导出右符号集。
### 0型文法
$$
α→β α∈(NT)+,β∈(NT)*
$$
递归可枚举语言 图灵机可以识别
### 1型文法
$$
αAβ→αα,β∈(NT)*A∈N B∈(NT)+
$$
上下文相关文法上下文敏感语言 线性有界自动机可识别
### 2型文法
$$
A→α α∈(NUT)*,A∈N
$$
上下文无关文法语言 非确定下推自动机可识别
### 3型文法
$$
A→αBBα α∈T*, A, B∈N
$$
正则文法、正则语言、有限自动机可以识别可消除右端非终法符P可以成为终结符表达式。

View File

@@ -1,24 +0,0 @@
# 课程概要
## 1 课程安排
## 2 考核标准
### 大作业
* 3-5人一组设计一门程序设计语言。包括语言的类型系统、模块划分、编程范式等。包括标准库和内建方法、高级特性、进程和线程、异常处理。
* 用lex、Yacc、Antlr等工具实现编译器。
* 提交内容:语言的设计文档,所涉及语言的代码示例。部分实现的编译器。
### 考核标准
* 习题作业50%其中大作业15%
* 考试50%
## 3 主要内容
* 编程语言概述、形式语法复习
* 编程语言泛型
* 语义理论

View File

@@ -13,7 +13,7 @@
是同一个东西的不同表述。
线性方程的系数表示的输入向量,多组$[x_1,\cdots,x_n]$表示多组算子。$[y_1,y_2,\cdots,y_n]$表示变换后的结果。
线性方程的系数表示的输入向量,多组$[x_1,\cdots,x_n]$表示多组算子。$[y_1,y_2,\cdots,y_n]$表示变换后的结果。(后续补充:感觉系数像是算子,未知量像解空间)
向量空间。由多个线性无关的向量组成的向量组,称为向量空间。每一个向量表示一个算子。
@@ -34,11 +34,11 @@ $$
1. 向量在变换后仍然是直线,不会被扭曲;
2. 原点不会发生移动。
### 5 线性变换和线性映射的区别
## 5 线性变换和线性映射的区别
线性映射( linear mapping是从一个向量空间V到另一个向量空间W的映射且保持加法运算和数量乘法运算而线性变换linear transformation是线性空间V到其自身的线性映射。
### 6 线性代数
## 6 线性代数
每一组线性方程的值,每一组线性无关的向量,每一组基底,都可以构成一个矩阵,统一为一个算子。所以线性代数主要讲了两件事。什么是线性变换。如何用矩阵工具解决线性变换问题。
@@ -64,16 +64,35 @@ $$
*
## 3 矩阵变换
> 明白矩阵变换的实际意义和矩阵变换前后保留的性质。
> 明白矩阵变换的实际意义和矩阵变换前后保留的性质。初等矩阵是由单位矩阵经过一次变换得到的矩阵。由初等矩阵的组合可以表示任何初等变换。
### 初等变换
* 对调
$$
A=\left[\begin{array}{cc}
0 & 1\\
1 & 0
\end{array}\right]
$$
* 数乘
* 对调数乘
$$
A=\left[\begin{array}{cc}
\lambda & 0\\
0 & \lambda
\end{array}\right]
$$
* 倍加
$$
B=A
A=\left[\begin{array}{cc}
1 & 0\\
k & 1
\end{array}\right]
$$
> 保留的性质:
> * 线性方程组的解不变。
> * 矩阵的秩不变

1
线性代数/附录1.md Normal file
View File

@@ -0,0 +1 @@
# 线性代数的本质理解