python一对一辅导教程:Computational Problems for Physics chapter 1-B Code Listings 1.7 - 1.11

基于YOLOv5的隧道衬砌缺陷智能检测系统 计算机视觉在工程检测领域正发挥越来越重要的作用,特别是目标检测技术通过深度学习算法实现了对复杂场景的智能分析。YOLOv5作为当前主流的目标检测框架,通过改进网络结构和训练策略,可以显著提升检测精度和效率。在隧道工程领域,结合通道注意力机制和多尺度特征融合技术,能够有效解决衬砌缺陷识别中的小目标检测难题。这种AI检测系统相比传统人工判读地质雷达图像,不仅将效率提升20倍,还能将识别准确率提高到92.3%,特别适用于3cm以上结构缺陷的自动化检测。系统通过深度可分离卷积等优化,实现了模型轻量化,便于在边缘计算 阅读详情

作者自我介绍:大爽歌, b站小UP主 ,直播编程+红警三 ,python1对1辅导老师 。
本博客为一对一辅导学生python代码的教案, 获得学生允许公开。
具体辅导内容为《Computational Problems for Physics With Guided Solutions Using Python》,第一章(Chapter 1 Computational Basics for Physics)的 Code Listings
由于代码较多,第一章内容分为三部分
A(1.1 - 1.6)
B(1.7 - 1.11)
C(1.12 - 1.17)

1 - 1.7 PondMatPlot.py

1 subplots

Create a figure and a set of subplots.
subplots() without arguments returns a Figure and a single Axes.

创建一个图形(figure)和一组子图(ax)。
如果没有参数,返回单个图形和单个轴。

ax: an .axes.Axes or array of Axes

2 .axes.Axes 的方法

官方文档: axes_api

  • set_xlabel
  • set_ylabel

这两个方法很简单,就是设置标签,只不过这里用到了一个参数fontsize,代表标签字体大小。
详细参数列表见Text的 Valid keyword arguments

  • set_xlim
  • set_ylim

设置x轴,y轴视图限制。即设置轴的范围(两个端点大小)

支持以下写法(set_ylim同理),以下两种写法一个意思。

set_xlim(left, right)
set_xlim((left, right))
  • set_xticks(ticks) 设置xaxis的刻度位置。

ticks: List of tick locations(floats).

  • set_xticklabels(labels) 用字符串标签列表设置xaxis的标签。

labels: list of label texts(str).

补充说明:set_xticklabels使用前,必须先调用set_xticks,且ticks和labels元素个数要一致。

3 PondMatPlot 绘制效果
import numpy as np, matplotlib.pyplot as plt

N = 100;   Npts = 3000;  analyt = np.pi**2                                      
x1 = np.arange(0, 2*np.pi+2*np.pi/N,2*np.pi/N)   
xi = [];  yi = [];  xo = [];  yo = []   
fig,ax = plt.subplots()
y1 = x1 * np.sin(x1)**2                           # Integrand
ax.plot(x1, y1, 'c', linewidth=4)      
ax.set_xlim ((0, 2*np.pi))
ax.set_ylim((0, 5))
ax.set_xticks([0, np.pi, 2*np.pi])     
ax.set_xticklabels(['0', '$\pi$','2$\pi$'])
ax.set_ylabel('$f(x) = x\,\sin^2 x$', fontsize=20) 
ax.set_xlabel('x',fontsize=20)
fig.patch.set_visible(False)
   
def fx(x):   return x*np.sin(x)**2                  # Integrand
            
j = 0                                    # Inside curve counter
xx = 2.* np.pi * np.random.rand(Npts)          # 0 =< x <= 2pi
yy = 5*np.random.rand(Npts)                      # 0 =< y <= 5
for i in range(1,Npts):            
    if (yy[i] <= fx(xx[i])):                     # Below curve
        if (i <=100): xi.append(xx[i])               
        if (i <=100): yi.append(yy[i])
        j +=1                            
    else:                           
        if (i <=100): yo.append(yy[i])               
        if (i <=100): xo.append(xx[i])
    boxarea = 2. * np.pi *5.                         # Box area 
    area = boxarea*j/(Npts-1)                # Area under curve

ax.plot(xo,yo,'bo',markersize=3)
ax.plot(xi,yi,'ro',markersize=3)
ax.set_title('Answers: Analytic = %5.3f, MC = %5.3f'%(analyt,area))
plt.show()

效果如图

4 PondMatPlot 逐行解析
N = 100;   Npts = 3000;  analyt = np.pi**2                                      
x1 = np.arange(0, 2*np.pi+2*np.pi/N,2*np.pi/N)  

x1 是从0到(2+2/N)pi,等分取的N+1个值组成的数组

ax.plot(x1, y1, 'c', linewidth=4)

绘制颜色为cyan(青色),线宽为4的曲线

fig.patch.set_visible(False)

将fig背景设为透明,在窗口上看起来和白色没区别,保存成png能看到效果。

def fx(x):   return x*np.sin(x)**2

定义一个函数,对应上面绘制的曲线,方便计算对应的值。

xx = 2.* np.pi * np.random.rand(Npts)  # 0 =< x <= 2pi
yy = 5*np.random.rand(Npts)  

np.random.rand(d0, d1, ..., dn)
创建给定形状的数组,并用[0,1)中均匀分布的随机样本填充它。

d0, d1, …, dn, 有几个,数组就是几维。
每个维度的长度由对应的di决定。

所以上面两行代码是在对应的区间内,Npts个[0,1)之中的随机值组成的一维数组。

for i in range(1,Npts):            
    if (yy[i] <= fx(xx[i])):                     # Below curve
        if (i <=100): xi.append(xx[i])               
        if (i <=100): yi.append(yy[i])
        j +=1                            
    else:                           
        if (i <=100): yo.append(yy[i])               
        if (i <=100): xo.append(xx[i])

遍历刚才生成的随机数,如果一组x,y在曲线下面(包括曲线),就放到xi, yi 中。

同时计数器j加1。(j用于统计有多个在曲线下的点)

如果一组x,y在曲线上面,就放到xo, yo中。

boxarea = 2. * np.pi *5.                         # Box area 
area = boxarea*j/(Npts-1)                # Area under curve

根据随机生成的点中,在曲线下的点的数量占比,因为数量足够多,可近似认为其为面积占比。

去计算曲线下的区域面积。

ax.plot(xo,yo,'bo',markersize=3)
ax.plot(xi,yi,'ro',markersize=3)

曲线上的点用蓝色圆点进行绘制,曲线下面的点用红色圆点进行绘制。
圆点的尺寸设置为3。

2 - 1.8 PondMatPlot.py

1 PondMatPlot绘制效果

代码如下

import numpy as np
# from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt

def randrange(n, vmin, vmax):
    return (vmax-vmin)*np.random.rand(n) + vmin

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
n = 100
for c, m, zl, zh in [('r', 'o', -50, -25), ('b', '^', -30, -5)]:
    xs = randrange(n, 23, 32)
    ys = randrange(n, 0, 100)
    zs = randrange(n, zl, zh)
    ax.scatter(xs, ys, zs, c=c, marker=m)
ax.set_xlabel('X Label')
ax.set_ylabel('Y Label')
ax.set_zlabel('Z Label')
plt.show()

绘制效果如图

2 fig.add_subplot
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

fig.add_subplot
常见参数写法为

  • (nrows, ncols, index, **kwargs)
  • (add_subplot(pos, **kwargs)

这里遇到的就是第二种,pos是111,等价于第一种的
nrows=1, ncols=1, index=1。

projection设置子图轴(subplot Axes)的投影类型(projection type)。
这里值为3d代表轴的类型为Axes3D

补充,轴的投影类型,可取值和对应的类型如下

{
    None: "use default",  # The default None results in a 'rectilinear' projection.
    'rectilinear': axes.Axes, 
    'aitoff': AitoffAxes,
    'hammer': HammerAxes, 
    'lambert': LambertAxes, 
    'mollweide': MollweideAxes, 
    'polar': PolarAxes, 
    '3d': Axes3D, 
    str:  "a custom projection",  # see projections. 
}
3 代码逐行解析
def randrange(n, vmin, vmax):
    return (vmax-vmin)*np.random.rand(n) + vmin

定义一个函数,返回一个一维n元,在[vmin, vmax)区间随机分布的数组

n = 100
for c, m, zl, zh in [('r', 'o', -50, -25), ('b', '^', -30, -5)]:
    xs = randrange(n, 23, 32)
    ys = randrange(n, 0, 100)
    zs = randrange(n, zl, zh)
    ax.scatter(xs, ys, zs, c=c, marker=m)

遇到这种循环不好看明白的话,就把这拆开看

n = 100

c, m, zl, zh = ('r', 'o', -50, -25)
xs = randrange(n, 23, 32)
ys = randrange(n, 0, 100)
zs = randrange(n, zl, zh)
ax.scatter(xs, ys, zs, c=c, marker=m)


c, m, zl, zh = ('b', '^', -30, -5)
xs = randrange(n, 23, 32)
ys = randrange(n, 0, 100)
zs = randrange(n, zl, zh)
ax.scatter(xs, ys, zs, c=c, marker=m)

可以看到,就是绘制了两次散点图,

相同点

  • xs范围相同,23 - 32 之间随机取出n个
  • ys范围相同,0 - 100 之间随机取出n个

不同点

  • zs范围不同,
    第一次在-50, -25之间随机取出n个;
    第二次是在-30, -5之间随机取出n个。
  • c不同(color不同)
    第一次是r红色;
    第二次是b蓝色。
  • marker不同
    第一次是o小圆点
    第二次是^小三角。

3 - Vpython 再解读

1 canvas

对应Vpython6中的display

scene=canvas(heigth=600,width=600,range=380)

doc: https://www.glowscript.org/docs/VPythonDocs/canvas.html
Creates a canvas with the specified attributes, makes it the selected canvas, and returns it.

创建具有指定属性的画布,使其成为选中的画布,并返回它。

  • range: The extent of the region of interest to the left or right of center.
    受关注区域到中心左右侧的距离

官方文档示意图如下

2 curve

doc: https://www.glowscript.org/docs/VPythonDocs/curve.html
The curve object displays straight lines between points, and if the points are sufficiently close together you get the appearance of a smooth curve.
curve展示点组成的直线。

以下写法效果相同,都会绘制v1到v2的曲线(v1, v2为三维坐标向量)

# 1)
c = curve(v1,v2)

# 2)
c = curve([v1,v2])

# 3)
c = curve(pos=[v1,v2])

# 4)
c = curve(v1)
c.append(v2)

# 5)
c = curve()
c.append(v1,v2)

curve还支持设置一些属性,比如

  • color
  • radius
3 cylinder

doc: https://www.glowscript.org/docs/VPythonDocs/cylinder.html
cylinder展示一个圆柱体(杆)。

示例

rod = cylinder(pos=vector(0,2,1), axis=vector(5,0,0), radius=1)
  • pos: the center of one end of the cylinder; default = vector(0,0,0)
    圆柱体底端的中心
  • axis: The axis points from pos to the other end of the cylinder, default = vector(1,0,0). Setting the axis makes length and size.x equal to the magnitude of the axis.
    轴从pos点指向圆柱的另一端,设置轴的大小可以决定length和size.x。

官方文档示例图如下

用cylinder创建实例后,可以通过修改实例的属性值,修改其状态,
比如修改其pos和axis。

其他属性(代码中用到的)

  • color
  • radius
4 arrow

doc: https://www.glowscript.org/docs/VPythonDocs/arrow.html

创建一端带有箭头的盒形直轴的箭头对象。
示例

pointer = arrow(pos=vector(0,2,1), axis=vector(5,0,0))
  • pos
  • axis

两参数效果见下官方示意图

5 label

doc: https://www.glowscript.org/docs/VPythonDocs/label.html

使用label对象,可以在一个框中显示文本,
示例

label(pos=vec(0,0.25,0), text='Hello!', box=0)
  • text: 标签框中的文本,字符串,支持html语法。
  • pos: 用于标签框底部中间位置(xoffset, yoffset为0时)
  • box: 默认为True,代表方框应该被绘制。False则不会绘制,(0等价于False,1为True)

参数详细官方示意图如下

生成label实例后,可修改实例的属性,调整对应标签的展示效果。

6 local_light

doc: https://www.glowscript.org/docs/VPythonDocs/lights.html
You can light a scene with distant lights (which act like point-like lamps far from the scene) and/or local lights (point-like lamps near the scene).

可以使用远光源(其作用类似于远离场景的点光源)和/或局部光源(靠近场景的点光源)照亮场景。

scene的默认灯光设置scene.lights如下

[distant_light(direction=vector( 0.22,  0.44,  0.88),       color=color.gray(0.8)),
 distant_light(direction=vector(-0.88, -0.22, -0.44),       color=color.gray(0.3))]

创建局部光源代码示例

lamp = local_light(pos=vector(x,y,z), color=color.yellow)

这里举一个展示光源移动的效果代码

from vpython import *

scene=canvas(heigth=600,width=600,range=380)
sball = sphere(pos=vector(100, 100, 0), radius=50, color=color.yellow)

X = -300
lamp = local_light(pos=vector(X, 0, 0), color=color.red)   # light

for t in arange(0.,100.0,0.2):
    rate(50)
    MX = X + t * 6
    lamp.pos = vector(MX, 0, 20)

其效果如下图

7 rate

设置动画一秒刷新的次数,动画的帧数,放在循环里就会调整循环一秒执行的次数。

Halts computations until 1.0/frequency seconds after the previous call to rate().
具体效果为,调用rate(frequency)将会停止运算 1.0/frequency 秒
doc: https://www.glowscript.org/docs/VPythonDocs/rate.html

4 - 1.9 TwoForces.py

1 为Vpython7更新代码语法

首先说明,1.9 TwoForces.py 是用Classic VPython (VPython 6)。
部分语法Vpython7中已经不支持。
其语法改换成Vpython7后代码如下

from vpython import *  # TwoForces.py

posy=100;  Lcord=250  # basic height, cord length
Hweight=50;  W = 10   # cylinder height, weight 

scene=canvas(heigth=600,width=600,range=380)
alt=curve(pos=[(-300,posy,0),(300,posy,0)])
divi=curve(pos=[(0,-150,0),(0,posy,0)])
kilogr=cylinder(pos=vector(0,posy-Lcord,0),radius=20,axis=vector(0,-Hweight,0),
                color=color.red) # kg as a cylinder
cord1=cylinder(pos=vector(0,posy,0),axis=vector(0,-Lcord,0),color=color.yellow,
               radius=2)
cord2=cylinder(pos=vector(0,posy,0),axis=vector(0,-Lcord,0),color=color.yellow,
               radius=2)

arrow1=arrow(pos=vector(0,posy,0), color=color.orange) # Tension cord 1
arrow2=arrow(pos=vector(0,posy,0), color=color.orange) # Tension cord 2

magF=W/2.0          # initial force of each student
v=2.0               # (m/s) velocity of each student
x1=0.0              # initial position student 1
anglabel=label(pos=vector(0,240,0), text='angle (deg)',box=0)
angultext=label(pos=vector(20,210,0),box=0)
Flabel1=label(pos=vector(200,240,0), text='Force',box=0)
Ftext1=label(pos=vector(200,210,0),box=0)
Flabel2=label(pos=vector(-200,240,0), text='Force',box=0)
Ftext2=label(pos=vector(-200,210,0),box=0)
local_light(pos=vector(-10,0,20), color=color.yellow)   # light

for t in arange(0.,100.0,0.2):  
    rate(50)                  # slow motion
    x1=v*t                    # 1 to right, 2 to left
    theta=asin(x1/Lcord)      # angle cord
    poscil=posy-Lcord*cos(theta)  # cylinder height
    kilogr.pos=vector(0,poscil,0)     # y-position kilogram
    magF=W/(2.*cos(theta))      # Cord tension
    angle=180.*theta/pi     
    cord1.pos=vector(x1,posy,0)       # position cord end
    cord1.axis=vector(-Lcord*sin(theta),-Lcord*cos(theta),0)
    cord2.pos=vector(-x1,posy,0)            # position end cord
    cord2.axis=vector(Lcord*sin(theta),-Lcord*cos(theta),0)
    arrow1.pos=cord1.pos            # axis arrow 
    arrow1.axis=vector(8*magF*sin(theta),8*magF*cos(theta),0)
    arrow2.pos=cord2.pos
    arrow2.axis=vector(-8*magF*sin(theta),8*magF*cos(theta),0)
    angultext.text='%4.2f'%angle
    force=magF
    Ftext1.text='%8.2f'%force     # Tension
    Ftext2.text='%8.2f'%force
2 TwoForces 绘制效果

TwoForces.py绘制效果是一个动画,
这里展示其初始效果和结束效果。

初始效果

结束效果

3 代码逐行解析
posy=100;  Lcord=250  # basic height, cord length
Hweight=50;  W = 10   # cylinder height, weight 
  • posy: 水平横线的高度
  • Lcord: 绳子长度
  • Hwight: 圆柱砝码的高度
  • W: 圆柱砝码的重量
alt=curve(pos=[(-300,posy,0),(300,posy,0)])
divi=curve(pos=[(0,-150,0),(0,posy,0)])
kilogr=cylinder(pos=vector(0,posy-Lcord,0),radius=20,axis=vector(0,-Hweight,0),
                color=color.red) # kg as a cylinder
cord1=cylinder(pos=vector(0,posy,0),axis=vector(0,-Lcord,0),color=color.yellow,
               radius=2)
cord2=cylinder(pos=vector(0,posy,0),axis=vector(0,-Lcord,0),color=color.yellow,
               radius=2)

arrow1=arrow(pos=vector(0,posy,0), color=color.orange) # Tension cord 1
arrow2=arrow(pos=vector(0,posy,0), color=color.orange) # Tension cord 2
  • alt: 在高为posy(100)的地方,绘制y轴左右各长300的水平线

  • divi: 在y轴上画一条竖直的线,从-150到高度为posy(100)。

  • kilogr: 创建一个红色圆柱体代表砝码,砝码半径为20,底部朝上,高度为Hweight(50),底部中心在posy-Lcord的位置上

  • cord1

  • cord2

创建两条黄色绳子(没有半径),绳子尾在alt线中点,绳子长Lcord,头刚好拉住kilogr

由于没有半径,刚开始会被divi这条线挡住。

  • arrow1
  • arrow2

创建两个橘色箭头(弹簧拉钩),底部中心位置在alt线的中点,方向向上。

其长度可以展示力的大小

magF=W/2.0          # initial force of each student
v=2.0               # (m/s) velocity of each student
x1=0.0              # initial position student 1

计算与设置初始值

  • magF: 每个绳子上的力
  • v: 移动速度,箭头底部沿x轴的移动速度
  • x1: 箭头移动的距离(距离alt线的中点)
anglabel=label(pos=vector(0,240,0), text='angle (deg)',box=0)
angultext=label(pos=vector(20,210,0),box=0)
Flabel1=label(pos=vector(200,240,0), text='Force',box=0)
Ftext1=label(pos=vector(200,210,0),box=0)
Flabel2=label(pos=vector(-200,240,0), text='Force',box=0)
Ftext2=label(pos=vector(-200,210,0),box=0)

在指定的位置添加无框文本进行展示

在高度为240的地方,展示变量名字anglabel,Flabel1,Flabel2,

在高度为210的地方,展示变量值angultext,Ftext1,Ftext2, 且后面还会不断更新这些变量值。

angultext展示的是绳子和竖直线divi形成的角度大小(角度制),

Ftext1,Ftext2展示两个绳子上的力的大小(两值相等)。

local_light(pos=vector(-10,0,20), color=color.yellow)   # light

添加一个局部点光源,效果不明显(基本没有)

for t in arange(0.,100.0,0.2):  
    rate(50)                  # slow motion

执行循环,从0到100间隔0.2取t值。
rate(50)设置循环每秒执行50次,每秒t增长50*0.2=10,相当于十倍速展示。

    x1=v*t                    # 1 to right, 2 to left
    theta=asin(x1/Lcord)      # angle cord
    poscil=posy-Lcord*cos(theta)  # cylinder height
    kilogr.pos=vector(0,poscil,0)     # y-position kilogram
    magF=W/(2.*cos(theta))      # Cord tension
    angle=180.*theta/pi    
  • x1: 速度乘时间,得到位移
  • theta: 对边除斜边,得到sin,在通过asin算出绳子和竖直线的夹角值(弧度制)
  • poscil: 算出砝码上端中心的y轴位置
  • kilogr.pos: 更新砝码位置
  • magF: 算出绳子上的力
  • angle: 算出theta对应的角度制的值
    cord1.pos=vector(x1,posy,0)       # position cord end
    cord1.axis=vector(-Lcord*sin(theta),-Lcord*cos(theta),0)
    cord2.pos=vector(-x1,posy,0)            # position end cord
    cord2.axis=vector(Lcord*sin(theta),-Lcord*cos(theta),0)
    arrow1.pos=cord1.pos            # axis arrow 
    arrow1.axis=vector(8*magF*sin(theta),8*magF*cos(theta),0)
    arrow2.pos=cord2.pos
    arrow2.axis=vector(-8*magF*sin(theta),8*magF*cos(theta),0)

重新设置两根绳子的位置pos(更新水平坐标)和方向axis。

重新设置两个箭头的位置pos(和绳子pos相同)和方向axis,方向向量的数值(箭头长)能展示力的大小变化。

    angultext.text='%4.2f'%angle
    force=magF
    Ftext1.text='%8.2f'%force     # Tension
    Ftext2.text='%8.2f'%force

更新文本标签

  • ‘%4.2f’ 字符宽度设置为4,保留2位有效数字
  • ‘%8.2f’ 字符宽度设置为8,保留2位有效数字

5 - Vpython 三解读

1 cone

doc: https://www.glowscript.org/docs/VPythonDocs/cone.html

建立一个圆锥体。

代码示例

cone(pos=vector(5,2,0), axis=vector(12,0,0), radius=1)

参数官方示意图

2 box

doc: https://www.glowscript.org/docs/VPythonDocs/box.html

建立一个立方体。
代码示例

mybox = box(pos=vector(x0,y0,z0), length=L, height=H, width=W)
mybox = box(pos=vector(x0,y0,z0), axis=vector(a,b,c), size=vector(L,H,W))
mybox = box(pos=vector(x0,y0,z0), axis=vector(a,b,c), length=L, height=H, width=W, up=vector(q,r,s))
  • pos: the center of the box
  • axis: (a, b, c)
  • size: (L, H, W), default is vector(1,1,1)

说明,不指定L的话,axis的a就是L,指定了L的话,axis只约束L的方向。(The axis attribute gives a direction for the length of the box)

  • up: (q,r,s)

the width of the box will lie in a plane perpendicular to the (q,r,s) vector,
and the height of the box will be perpendicular to the width and to the (a,b,c) vector.

方框的宽度将垂直于(q,r,s)矢量,方框的高度将垂直于宽度和(a,b,c)矢量。

参数官方示意图

3 textures

doc: https://www.glowscript.org/docs/VPythonDocs/textures.html
textures是Vpython7的新特性,通过texture这个参数名来指定。在Classic Vpython(Vpython 6)中,原本叫做materials,通过material参数名来指定。

设置对象的纹理(贴图)。

简单指定方法如下

box(texture=textures.stucco)

stucco是指定其为粉饰灰泥纹理。

纹理支持的所有值和对应的效果如下

{
    "flower": "花", 
    "granite": "花岗岩", 
    "gravel": "砾石", 
    "earth": "地球", 
    "metal": "金属", 
    "rock": "岩石", 
    "rough": "粗糙的", 
    "rug": "小地毯", 
    "stones": "石头", 
    "stucco": "灰泥", 
    "wood": "木材", 
    "wood_old": "老木头"
}

以1.10 的 SlidingBox.py为例,展示下有纹理和无纹理的效果区别

有纹理的示例代码如下。

from vpython import *

Hsupport=30;  d=100                # height, distance supports
Lbeam=500; Wbeam=80;  thickness=10 # beam dimensions
Lbox=60; Wbox=60; Hbox=60  # Box Dimensions

# Graphics
scene=canvas(width=750, height=500,range=300)
scene.forward=vector(0.5,-0.2,-1)  # to change point of view

beam=box(pos=vector(0,Hsupport+thickness/2,0),color=color.orange, length=Lbeam,width=Wbeam,height=thickness,texture=textures.wood)
cube=box(pos=vector(-d,Hsupport+Hbox/2+thickness,0),length=Lbox, width=Wbox,height=Hbox,texture=textures.rock)

有纹理的效果如下图

无纹理的效果如下图(删除指定纹理参数的代码)

6 - 1.10 SlidingBox.py

1 代码展示
from vpython import *

Hsupport=30;  d=100                # height, distance supports
Lbeam=500; Wbeam=80;  thickness=10 # beam dimensions     
W =200;  WeightBox=400             # weight of table,box 
Lbox=60; Wbox=60; Hbox=60 # Box Dimensions

# Graphics
scene=canvas(width=750, height=500,range=300)
scene.forward=vector(0.5,-0.2,-1)  # to change point of view
support1=cone(pos=vector(-d,0,0),axis=vector(0,Hsupport,0),color=color.yellow,
              radius=20)
support2=cone(pos=vector(d,0,0),axis=vector(0,Hsupport,0),color=color.yellow,
              radius=20)
beam=box(pos=vector(0,Hsupport+thickness/2,0),color=color.orange, length=Lbeam,width=Wbeam,height=thickness,texture=textures.wood)
cube=box(pos=vector(-d,Hsupport+Hbox/2+thickness,0),length=Lbox, width=Wbox,height=Hbox,texture=textures.rock)
piso=curve(pos=[(-300,0,0),(300,0,0)],color=color.green, radius=1)
arrowcube=arrow(color=color.orange,axis=vector(0,-0.15*Wbox,0)) # scale 
arrowbeam=arrow(color=color.orange,axis=vector(0,-0.15*W,0))
arrowbeam.pos=vector(0,Hsupport+thickness/2,0) 

v=4.0                           # box speed
x=-d                            # box initial position
Mg=WeightBox+W                  # weight box+beam
Fl=(2*Wbox+W)/2.0               
arrowFl=arrow(color=color.red,pos=vector(-d,Hsupport+thickness/2,0), axis=vector(0,0.15*Fl,0))
Fr=Mg-Fl                        # right force
arrowFr=arrow(color=color.red,pos=vector(d,Hsupport+thickness/2,0), axis=vector(0,0.15*Fr,0))
anglabel=label(pos=vector(-100,150,0), text='Fl=',box=0)   
Ftext1=label(pos=vector(-50,153,0),box=0)                  
anglabel2=label(pos=vector(100,150,0), text='Fr=',box=0)
Ftext2=label(pos=vector(150,153,0),box=0)
rate(4)                         # to slow motion

for t in arange(0.0,65.0,0.5):                           
    rate(10)                                         
    x=-d+v*t
    cube.pos=vector(x, Hsupport+Hbox/2+10,0) # position cube
    arrowcube.pos=vector(x,Hsupport+5,0)
    if Fl>0:                                  
        Fl=(d*Mg-x*WeightBox)/(2.0*d)   
        Fr=Mg-Fl                              
        cube.pos=vector(x, Hsupport+Hbox/2+10,0)   
        arrowcube.pos=vector(x,Hsupport+thickness/2,0)  
        arrowFl.axis=vector(0,0.15*Fl,0)          
        arrowFr.axis=vector(0,0.15*Fr,0)         
        Ftext1.text='%8.2f'%Fl                   # Left force value
        Ftext2.text='%8.2f'%Fr                   # Right force value
    elif Fl==0:                                   
         x=300
         beam.rotate(angle=-0.2,axis=vector(0,0,1),
          origin=vector(d,Hsupport+thickness/2,0))
         cube.pos=vector(300,Hsupport,0)
         arrowcube.pos=vector(300,0,0)
         break
    
rate(5) 
arrowFl.axis=vector(0,0.15*0.5*(W),0)  # return beam
arrowFr.axis=arrowFl.axis
beam.rotate(angle=0.2,axis=vector(0,0,1),origin=vector(d,Hsupport+thickness/2,0))
Fl=100.0
Ftext1.text='%8.2f'%Fl
Ftext2.text='%8.2f'%Fl
2 运行效果

这个代码运行效果是一个动画:
立方体在横木上从左往右移动,移动到右边的锥子右边后,掉落到水平面。

这里展示其三阶段的效果。

初始效果

中间效果

最终效果

3 逐行解读
Hsupport=30;  d=100                # height, distance supports
Lbeam=500; Wbeam=80;  thickness=10 # beam dimensions     
W =200;  WeightBox=400             # weight of table,box 
Lbox=60; Wbox=60; Hbox=60 # Box Dimensions
  • Hsupport: 黄色圆锥体(支撑)的高度
  • d: 黄色圆锥体(支撑)和水平中心的举例,x轴的偏移量
  • Lbeam, Wbeam, thickness: 横木梁的长,宽,高(厚度)
  • W: 横木梁的重量
  • WeightBox: 立方体(箱子)的重量
  • Lbox, Wbox, Hbox: 立方体(箱子)的长,宽,高(厚度)
scene=canvas(width=750, height=500,range=300)
scene.forward=vector(0.5,-0.2,-1)  # to change point of view

新建画板为场景,
更改场景相机的方向(forward)

forward: Vector pointing in the same direction as the camera looks (that is, from the current camera location, given by scene.camera.pos, toward scene.center). When forward is changed, either by program or by the user using the mouse to rotate the camera position, the camera position changes to continue looking at center. Default vector(0,0,-1). Its magnitude is not significant.

可看前文3 - Vpython 再解读的1 canvas的示意图。

support1=cone(pos=vector(-d,0,0),axis=vector(0,Hsupport,0),color=color.yellow,
              radius=20)
support2=cone(pos=vector(d,0,0),axis=vector(0,Hsupport,0),color=color.yellow,
              radius=20)
beam=box(pos=vector(0,Hsupport+thickness/2,0),color=color.orange, length=Lbeam,width=Wbeam,height=thickness,texture=textures.wood)
cube=box(pos=vector(-d,Hsupport+Hbox/2+thickness,0),length=Lbox, width=Wbox,height=Hbox,texture=textures.rock)
piso=curve(pos=[(-300,0,0),(300,0,0)],color=color.green, radius=1)

# Origin code in Book use WBox, I think it should be wrong
arrowcube=arrow(color=color.orange,axis=vector(0,-0.15*WeightBox,0)) # scale 
arrowbeam=arrow(color=color.orange,axis=vector(0,-0.15*W,0))
arrowbeam.pos=vector(0,Hsupport+thickness/2,0) 
  • support1, support2: 两个黄色圆锥体,支撑物
  • beam: 橘色横木梁,贴图为木头贴图
  • cube: 立方体箱子,题图为岩石贴图
  • piso: 地板上的一条绿色线,和x轴平行。
  • arrowcube: 橘色箭头,示意立方体箱子受到的重力,
  • arrowbeam: 橘色箭头,示意横木梁的重力,
    更改其y轴位置为横木梁上面中心。
v=4.0                           # box speed
x=-d                            # box initial position
Mg=WeightBox+W                  # weight box+beam
Fl=(2*WeightBox+W)/2.0          # Origin code in Book that should be wrong: Fl=(2*WBox+W)/2.0  
arrowFl=arrow(color=color.red,pos=vector(-d,Hsupport+thickness/2,0), axis=vector(0,0.15*Fl,0))
Fr=Mg-Fl                            # right force
arrowFr=arrow(color=color.red,pos=vector(d,Hsupport+thickness/2,0), axis=vector(0,0.15*Fr,0))
  • v: 立方体箱子的移动速度
  • x: 立方体x轴坐标,初始时应该为-d
  • Mg: 立方体箱子和横木梁的重力
  • Fl, Fr: 左边, 右边支撑体圆锥分到的力
  • arrowFl, arrowFr: 左边, 右边的箭头,用于展示左右边圆锥体的支撑力。
anglabel=label(pos=vector(-100,150,0), text='Fl=',box=0)   
Ftext1=label(pos=vector(-50,153,0),box=0)                  
anglabel2=label(pos=vector(100,150,0), text='Fr=',box=0)
Ftext2=label(pos=vector(150,153,0),box=0)
rate(4)                         # to slow motion
  • anglabel, anglabel2: 展示左右两边力的名字
  • Ftext1, Ftext2: 展示左右两边力的值

box = 0 表示无框

  • rate(4) 1/4秒后执行下一句
for t in arange(0.0,65.0,0.5):                           
    rate(10)                                         
    x=-d+v*t
    cube.pos=vector(x, Hsupport+Hbox/2+10,0) # position cube
    arrowcube.pos=vector(x,Hsupport+5,0)
  • 执行循环,从0到65间隔0.5取t值。
  • 设置循环每秒执行10次,每秒t增长 10*0.5=5 ,相当于5倍速展示。
  • 根据速度公式计算位移
  • 重新设置立方体箱子的位置,只修改了x。
    10是指thickness(横木梁的高度即厚度),这里写死数值不好,更应该写成thickness。
  • 更改箭头arrowcube的位置,该箭头示意立方体箱子的重力。
    if Fl>0:                                  
        Fl=(d*Mg-x*WeightBox)/(2.0*d)   
        Fr=Mg-Fl                              
        cube.pos=vector(x, Hsupport+Hbox/2+10,0)   
        arrowcube.pos=vector(x,Hsupport+thickness/2,0)  
        arrowFl.axis=vector(0,0.15*Fl,0)          
        arrowFr.axis=vector(0,0.15*Fr,0)         
        Ftext1.text='%8.2f'%Fl                   # Left force value
        Ftext2.text='%8.2f'%Fr 
  • Fl>0: 代表左边圆锥支撑还受到压力,说明此事立方体箱子还在两个圆锥支撑之间。
  • 计算左右两边圆锥收到的压力(数值上也等于其支持力)
    Fl是根据杠杆原理的公式计算的(有一点不太相同)
  • cube.pos, arrowcube.pos: 这两行代码和上面相同,是多余的。
  • 更新左右两边示意圆锥支撑体支持力的的红色箭头的长度
  • 更新左右两边文本上展示的力的值。
    ‘%8.2f’: 占位符总长度为8位,保留两位有效数字(保留两位小数)。
    elif Fl==0:                                   
         x=300
         beam.rotate(angle=-0.2,axis=vector(0,0,1),
          origin=vector(d,Hsupport+thickness/2,0))
         cube.pos=vector(300,Hsupport,0)
         arrowcube.pos=vector(300,0,0)
         break
  • Fl==0: 左边圆锥支撑无压力的话,说明左边已经翘起来了,立方体箱子将从右边滑下。
  • x=300: 箱子直接滑到横木梁最右边
  • 横木梁会以右边圆锥为支点,翘起来一点
  • 更新箱子位置
  • 更新箱子的重力示意箭头位子
  • break: 退出for循环
rate(5) 
arrowFl.axis=vector(0,0.15*0.5*(W),0)  # return beam
arrowFr.axis=arrowFl.axis
beam.rotate(angle=0.2,axis=vector(0,0,1),origin=vector(d,Hsupport+thickness/2,0))
Fl=100.0
Ftext1.text='%8.2f'%Fl
Ftext2.text='%8.2f'%Fl
  • rate(5): 1/5秒后执行后面的代码
  • arrowFl, arrowFr: 更新左右两边示意圆锥支撑体支持力的的红色箭头的长度
  • 横木梁归位
  • 更新左边圆锥支持力的大小
  • 更新左右两边文本上展示的力的值。

7 - 1.11 CentralValue.py

1 代码展示
import random
import numpy as np, matplotlib.pyplot as plt

N = 1000; NR = 10000   #  Sum N variables, distribution of sums 
SumList = [] # empty list

def SumRandoms():  # Sum N randoms in [0,1]
    sum = 0.0
    for i in range(0,N):  sum = sum + random.random() 
    return sum                    
    
def normal_dist_param():
    add = sum2 =0 
    for i in range(0,NR):  add = add + SumList[i]
    mu = add/NR               # Average distribution
    for i in range(0,NR): sum2 = sum2 + (SumList[i]-mu)**2
    sigma = np.sqrt(sum2/NR)
    return mu,sigma    

for i in range(0,NR):
    dist =SumRandoms()      
    SumList.append(dist)           # Fill list with NR sums

plt.hist(SumList, bins=100, density=True) # True: normalize
mu, sigma = normal_dist_param()            
x = np.arange(450,550)
rho = np.exp(-(x-mu)**2/(2*sigma**2))/(np.sqrt(2*np.pi*sigma**2)) 

plt.plot( x,rho, 'g-', linewidth=3.0)         # Normal distrib
plt.xlabel('Random Number x 1000')
plt.ylabel('Average of Random Numbers')
plt.title('Generated vs Analytic Normal Distribution')
plt.show()
2 运行效果

3 plt.hist

doc: matplotlib.pyplot.hist

简易写法为

plt.hist(x, **kwargs)

计算并绘制x的直方图。

可通过kwargs来进行一些设置。
用到的

  • bins: 可选参数,可为整数、序列或字符串。
    如果是整数,则定义范围内等宽的柱的数量。
  • density: 可选参数,布尔值(boolean)。
    是否按密度probability density绘制

已经遗弃的参数(书上用过)

  • normed: 该参数已被density替换。
4 逐行解析
def SumRandoms():  # Sum N randoms in [0,1]
    sum = 0.0
    for i in range(0, N):  sum = sum + random.random()
    return sum

计算[0,1]中N个随机数之和并返回
返回值是一个[0,N]之间的值

for i in range(0,NR):
    dist =SumRandoms()      
    SumList.append(dist)           # Fill list with NR sums

循环NR次,在SumList列表中添加NR个SumRandoms()的值

plt.hist(SumList, bins=100, density=True) # True: normalize

绘制SumList的分布直方图,按密度绘制,分为100段。

def normal_dist_param():
    add = sum2 =0
    for i in range(0,NR):  add = add + SumList[i]
    mu = add/NR               # Average distribution
    for i in range(0,NR): sum2 = sum2 + (SumList[i]-mu)**2
    sigma = np.sqrt(sum2/NR)
    return mu,sigma  

mu, sigma = normal_dist_param()     

计算SumList的平均值mu和标准差sigma

x = np.arange(450,550)
rho = np.exp(-(x-mu)**2/(2*sigma**2))/(np.sqrt(2*np.pi*sigma**2))

np.arange(450,550)没有写步长(间隔值),说明使用默认值1。
x为一个450到550之间隔1取值组成的数组。

rho这里用到了正态分布公式

e − ( x − μ ) 2 2 σ 2 2 π σ 2 , 其 中 平 均 值 μ 对 应 代 码 中 的 m u , 标 准 差 σ 对 应 代 码 中 的 s i g m a \frac{e^{-\frac{(x-\mu)^2}{2 \sigma^2}}}{\sqrt{2\pi \sigma^2}}, 其中平均值\mu对应代码中的mu,标准差\sigma对应代码中的sigma 2πσ2 ​e−2σ2(x−μ)2​​,其中平均值μ对应代码中的mu,标准差σ对应代码中的sigma

plt.plot( x,rho, 'g-', linewidth=3.0)         # Normal distrib

绘制刚才的符合正态分布公式的x和xho,
用绿色曲线绘制。

统计信号处理基础 习题解答1-1 1-1:在雷达习题中,双程延时时间的估计量具有PDF τ0~Nτ0,στ02,其中τ0是真值。假如要估计距离请提出一种估计量R,并求它的PDF。然后,确定标准偏差στ0,使得距离估计值的99%在真值的100m以内,对电磁波传播速度取c=3×108m/s。 解答: 问题1: 由于电磁波传播速度c,信号可观察的双程传播延时τ0和双程传播距离τ0满足关系: R=cτ02 因此可采用如下估计量: R=cτ02 问题2: 由于τ0满足正态分布,且: Eτ0=τ0 varτ0=στ02 那么: E 阅读详情

相关推荐

跟着团子学SAP CO:基于成本的完工百分比结算:Cost-based POC(以项目为例)

本文以英国及北美会计准则下的基于成本的POC的销售型项目结算对PS模块中的完工百分比进行介绍

Lucas1211的博客 2万+

python一对一辅导教程:Computational Problems for Physics chapter 1-A Code Listings 1.1 - 1.6

作者自我介绍:大爽歌, b站小UP主 ,直播编程+红警三 ,python1对1辅导老师 。 本博客为一对一辅导学生python代码的教案, 获得学生允许公开。 具体辅导内容为《Computational Problems for Physics With Guided Solutions Using Python》,第一章(Chapter 1 Computational Basics for Physics)的 Code Listings 0 安装第三方库 已安装 numpy matplotlib .

大爽老师的博客 502

k8s RoCE 部署: k8s-rdma-shared-dev-plugin + macvlan cni

写给自己的入门篇 文章目录前言一、创建 k8s 集群二、启用 primary network三、启用 secondary networkk8s-rdma-shared-dev-pluginMultus CNISecondary CNIMulti-Network CRD四、启用 pod五、在 pod 中启动 RoCE 流量总结 前言 写给自己的扫盲篇。后续会在原理方面持续更新 一、创建 k8s 集群 k8s 集群的创建有多种方法,可以按照官方文档的说明来.

sunshuying1010的博客 9783

python3d动画效果_python – 具有透明背景的mplot3d动画

我认为这真的是一个错误.但是,如果您更关心结果而不是达到目标的方式,那么下面的工作就可以完成.您可以单独保存每个图像,然后调用imageMagick将它们转换为动画gif,而不是调用动画.请参阅下面的代码并注意convert.exe的参数.from __future__ import divisionfrom numpy import pi, sin, cos, mgridfrom scipy.s...

weixin_39613089的博客 441

从2804云台电机到桌面机械臂:一个STM32/GD32玩家的FOC驱动踩坑全记录

本文详细记录了从2804云台电机到桌面机械臂的FOC驱动开发历程,涵盖了硬件选型、驱动方案优化、软件调试等关键环节。特别分享了L6234P驱动芯片的发热问题、AS5600编码器的I2C通信陷阱以及PID调参的实战经验,为DIY爱好者提供了宝贵的参考。

weixin_26897585的博客 482

描述符链表(Descriptor Chain)是什么?

描述符链表是硬件加速数据传输的核心数据结构,通过链式描述符(包含地址、长度、控制标志等)实现DMA自动批量处理,显著降低CPU负载。其工作原理为:CPU初始化链表后,硬件按序处理每个描述符,完成自动跳转与中断通知。在网卡收包、NVMe存储等场景中应用广泛,优势包括批处理、低延迟和灵活调度。需注意内存对齐、缓存一致性等实现细节,优化手段包括预分配描述符池、环形缓冲区等。该技术是网络/存储领域提升吞吐量的关键方案。

guigenyi的专栏 775

matplotlib的subplot使用

官方docs:https://matplotlib.org/api/_as_gen/matplotlib.pyplot.subplots.html?highlight=subplots#matplotlib.pyplot.subplots matplotlib.pyplot.subplots Create a figure and a set of subplots 调用su

csdn_sbregister的博客 631

如何下载era5数据?(两种方式)

供水利大数据云计算课程同学参考使用#

Camiel_sweet的博客 1万+

python一对一辅导教程:Computational Problems for Physics chapter 1-C Code Listings 1.12 - 1.17

作者自我介绍:大爽歌, b站小UP主 ,直播编程+红警三 ,python1对1辅导老师 。 本博客为一对一辅导学生python代码的教案, 获得学生允许公开。 具体辅导内容为《Computational Problems for Physics With Guided Solutions Using Python》,第一章(Chapter 1 Computational Basics for Physics)的 Code Listings 由于代码较多,第一章内容分为三部分 A(1.1 - 1.6) B(.

大爽老师的博客 521

ABAP 平台 SOAUTH2_CLIENT 全面实战:用一套配置,打通 OAuth 2.0 客户端的创建、联调与运维

本文是一份ABAP平台上配置OAuth 2.0客户端的全流程指南,重点介绍新界面SOAUTH2_CLIENT的使用方法。内容涵盖从概念解析到实操步骤,包括四种常见授权方式的选择、证书信任管理、Scope配置以及联调技巧。指南通过两个企业级案例(对接SAP BTP Cloud Integration和SAML 2.0身份联合)展示实际应用场景,并提供了配置清单和伪代码示例。特别强调新界面将客户端配置、令牌测试和校验功能整合的工程化优势,以及与旧事务码OA2C_CONFIG的主要差异。文中多处引用SAP官方文档

2007 年 ~ 2025 年,深耕 SAP 技术 18 年 319

学Simulink——基于Simulink的固态变压器(SST)多级协同控制​

本文介绍了基于Simulink的固态变压器(SST)多级协同控制系统设计与仿真方法。SST作为智能电网关键设备,包含AC-DC整流、DC-DC隔离和DC-AC逆变三级变换器。针对级间耦合问题,提出了能量-功率协同控制策略,通过纵向解耦和横向联动实现稳定运行。详细演示了在Simulink中搭建三级主电路、设计协同控制器(含电网定向控制、功率前馈和虚拟惯性控制)的全过程,并通过负载突变测试验证了系统动态性能(直流母线电压波动<2%)。最后给出了工程部署建议,包括数字控制延时补偿、启动序列设计和代码自动生成

xiaoheshang_123的博客 206

理解subplot() vs. subplots() in matlabplot

subplot matplotlib.pyplot.subplot(*args, **kwargs) Add an Axes to the current figure or retrieve an existing Axes. 理解Axes in matplotlib

漫步量化 386

【思考模型框架】采用双钻模型:发散(桌面研究/用户访谈)→收敛(需求归类/优先级排序),输出需求规格书、追踪矩阵及产品待办清单。

设计思维双钻模型是一种以用户为中心的需求管理方法,通过"发散-收敛"的双循环确保问题定位准确、方案切实可行。第一钻石(探索→定义)聚焦"找对问题",运用用户访谈、田野调查等方法挖掘真实需求;第二钻石(开发→交付)解决"做对方案",通过原型测试、A/B测试验证可行性。该模型强调低保真验证、多团队协作和真实用户测试,避免资源浪费与伪需求开发。典型应用场景包括产品功能优化、用户体验提升等需要精准落地的需求场景。核心价值在于建立从用户痛点到解决方案的可控闭

奶爸的编程之路,也就一周冷个三天 319

04-输出保留3位小数的浮点数「C++信息奥赛题解」

你好,我是悦创。 描述 读入一个单精度浮点数,保留 3 位小数输出这个浮点数。 输入 只有一行,一个单精度浮点数。 输出 也只有一行,读入的单精度浮点数。 样例输入 12.34521 样例输出 12.345 代码 #include <iostream> #include <iomanip> using namespace std; int main() { float f; cin >> f; cout << fixed <&

AI悦创·编程私教1v1 4608

SAP B1中文培訓教材_SDK

公司内部培训资料,对开发工具 ,DIAPI, UIAPI,Add-ON有详细解说

温度PID控制PLC程序

温度PID稳定控制程序,适用于欧姆龙PLC,对其他PLC也具有很大参考价值

matplotlib命令与格式:设置栅格,axes脊柱(坐标轴),背景颜色

1.设置栅格 (1)使用pyplot api命令 打开栅格:plt.grid(true) 设置栅格格式:plt.grid(color='r', linestyle='--', linewidth=1,alpha=0.3) (2)使用axes类面向对象命令 #同时设置两坐标轴上的栅格线 ax.grid(color='r', linestyle='--', linewidth=1,

开码河粉 3万+

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

python背景透明_python –强制matplotlib绘图背景透明

Script House收集的这篇文章主要介绍python –强制matplotlib映射的背景是透明的. Script House的编辑感觉很好. 现在,我将与您分享并提供参考.我正在尝试在正在编写的Gtk3应用程序中包含一个matplotlib图. 我想将图形的背景色设置为透明,以便图形将显示应用程序的自然灰色背景,但是到目前为止,我尝试的内容似乎没有效果.这是MWE:from gi.rep...

weixin_39874269的博客 2189

jre9下载 jdk9

(Java SE Runtime Environment 9.0) 9.0u175 官方最新版 【x86|x64】

matplotlib学习笔记

import numpy as np import matplotlib.pyplot as plt # 在notebook中画图 %matplotlib inline # 画图 plt.plot([1,2,3,4,5],[1,4,9,16,25],'--',color = 'm') # 改x轴显示 plt.xticks(x,bar_label) plt.show() # 绘制多个线 n =...

xiaotuzigaga的博客 1294

Python私教/Java私教「一对一教学」

计算机行业10年经,不同于千篇一律的教育机构,我的教育模式直面新人成长学习痛点,采用师徒模式,在课程讲授过程中,我会亲自一对一帮扶讲解,把我多年积累的经验和良好的代码素养传递给新人,对新人的成长速度提高是很快的,对于优秀的学生,我也会利用我的人脉积极帮推荐工作。根据学员个人基础定制课程体系,最高效率学习,少走弯路!

AI悦创·编程私教1v1 864

matplotlib的一些基本设置的记录

matplotlib的一些基本设置的记录 Matplotlib可能是Python 扩展包中仅有的最流行的 2D 绘图库。她不仅提供了快速的方式可视化Python中的数据,而且提供流行的图形格式的选择。 pyplot 是非常接近 Matlab 的一个函数库,承担了大部分的绘图任务。我们可以通过以下命令引入pyplot. from matplotlib import

wl_ss的博客 4576

python绘制动态模拟图-用python生成地球运动的动态模拟动态图

python作为一门简单易学且应用范围极广的语言有着其他语言无法比拟的优势,通过python可以实现各种各样的功能,例如我们可以利用python matplotlib的绘图库实现各种动态模拟仿真,在科学实验中有着极大的应用价值。下列是通过python实现地球公转的动态模拟图:import numpy as npimport matplotlib as mplmpl.use("TkAgg&...

weixin_37988176的博客 1538

python一对一辅导教程:PyGeM Tutorials 解析 1

作者自我介绍:大爽歌, b站小UP主 ,直播编程+红警三 ,python1对1辅导老师 。 本博客为一对一辅导学生python代码的教案, 获得学生允许公开。 目前具体辅导内容为PyGeM 本文为PyGeM tutorial-1-ffd 的讲解与分析 Tutorial 1 shows how to apply the free-form deformation to mesh nodes. 0 准备工作 准备软件 必须安装 python 3.8或以上版本 https://www.python.or.

大爽老师的博客 1969

Python画图知识点(整理自用)

色卡:

qq_42183184的博客 4586

一对一辅导python_Python辅导

Python编程辅导与R编程辅导根据作业内容,协同完成编程任务、开发过程共享、问题解答。纯个人,中介勿扰。服务流程:前段。与学生一对一确认作业或问题细节,可以无障碍阅读全英文文档,判断出作业难度与完成时间点。中段。进入正式开发过程,中间结果会及时发送给学生,与学生确认是否符合要求,并解释代码的作用后段。交付代码,并安排一对一在线讲解代码,可以辅助学生对每一行代码写注释。如作业任务出现新要求,可以帮...

weixin_39528289的博客 1425

python培训 一对一

image.png6-2编写函数计算一个或不特定多个数的乘积 1、函数接口定义: 打 * 号的参数 t 接受多个参数成员,参数成员预期为整数或浮点数类型。知识点讲解 Linke:https://www.aiyc.top/126.html *args 的用法 和 主要用于函数定义。你可以将不定数量的「参数」传递给一个函数。「这里的不定的意思是:「预先并不知道,函数使用者会传递多少个参数给你,所以在这个场景下使用这两个关键字。 是用来发送一个」非键值」对的可变数量的参数列表给一个函数。这里有个例子帮你.

weixin_63757190的博客 1198

Python一对一题目辅导「PTA 题目讲解·难度系数:基础」

点击此链接获得完整文章阅读: Python一对一题目辅导「PTA 题目讲解·难度系数:基础」 题目范围 作业 7: 6-2编写函数计算一个或不特定多个数的乘积(高教社,《Python编程基础及应用》习题8-6)(4分) 1、函数接口定义: def caculate(*t) 打 * 号的参数 t 接受多个参数成员,参数成员预期为整数或浮点数类型。 知识点讲解 Linke:htt...

AI悦创·编程私教1v1 6368

python一对一培训怎么收费

Python是现在最火的语言,Python极简的语法吸引了一大批人学习。不仅是很多学校计算机专业会开课,很多从事商业分析工作的从业者也在学习Python。俗话说得好啊,有钱能使鬼推磨,那么如果你是Python学习者,最感兴趣的应该就是,学了Python之后,可以怎么赚钱呢? 1、Python爬虫外包项目 开发爬虫项目,最方便的语言就是Python了。网上对于爬虫的需求也很大,所以外包是一种非常可行的挣钱方式。一般要向甲方提供数据抓取、数据结构化、数据清洗等服务。也算是最简单直接运用技术赚钱的方式。不过现

weixin_63757190的博客 1080
上一篇: python一对一辅导教程:Computational Problems for Physics chapter 1-C Code Listings 1.12 - 1.17
下一篇: tkinter Canvas delete 方法详解
大爽歌
博客等级 码龄9年 422粉丝 92原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值