<aside> <img src="/icons/condense_yellow.svg" alt="/icons/condense_yellow.svg" width="40px" /> Python | 弹性 | 物理 | 力学 | 可压缩 | 液体 | 不可压缩 | 烟雾 | 波动 | 质量弹簧 | 碰撞 | 欧拉 | 刚体 | 运动 | 水面模型 | 渲染器 | 体积 | 磁场

</aside>

🎯要点

🎯弹性连续力学 | 🎯弱可压缩液体 | 🎯不可压缩流体(烟雾)| 🎯高度场浅水波动 | 🎯质量弹簧系统地面碰撞 | 🎯前向欧拉方法台球刚体运动,动量和动能守恒 | 🎯高度场重建水面模型实现图像渲染器 | 🎯图像体积渲染器 | 🎯磁场模拟

🎯算法微分:Python | C++漂移扩散方程和无风险套利公式算法微分

pie showdata
 title 语言分比
 "Python":53
 "C++":34
 "CMake":13

✂️梗概

🍇Python微分计算出租车往返速度模型

微分计算的总体目标是计算:

$$ \frac{d p_{\text {rogram }}}{d p_{\text {arams }}} $$

即量化程序及其输出对其某些参数的敏感性。

首先,使用传统的、数据独立的代码编写一个程序来估计出租车乘坐的持续时间:

 import numpy as np
 
 def linear_predictions(weights, inputs):
     return np.dot(inputs, weights) * 60.0
 
 v_avg = 30
 startup_time = 2 /60.0 
 
 inputs = np.array([[1.0, 6.0],
                    [1.0, 4.0 ]])
 
 weights = np.array([startup_time, 1.0 / v_avg]) 
 
 print("Predictions:", linear_predictions(weights, inputs))

在此代码中,我们使用某市预先计算的平均速度来计算出租车行程持续时间:大约 30 公里/小时。这是制作程序的传统方法,即数据不影响其参数。我们使用预定义的参数,这里是预先估计的平均速度,将该速度的倒数乘以行程距离,我们就得到了预期的行程持续时间。无论我们运行多少次,它都永远不会改善。它永远不会从错误中吸取教训。

微分计算提供的功能恰恰相反:每次运行都可用于微调应用程序参数。让我们看看这是如何实现的。对于计算机和人类来说都适用的一件事是,为了改进,你需要反馈。理想情况下,您需要一种方法来量化您的错误。

在计算机世界中,这可以通过在我们的初始代码中引入一个新函数来轻松完成,该函数计算相对常见的误差测量:平方误差。

 import numpy as np
 
 def linear_predictions(weights, inputs):
 
     return np.dot(inputs, weights) * 60.0
 
 def squared_loss(weights, inputs, targets):
     preds = linear_predictions(weights, inputs)
     err = (preds - targets)**2
     return np.sum(err)
 
 v_avg = 30
 startup_time = 2 /60.0
 
 inputs = np.array([[1.0, 6.0],
                    [1.0, 4.0 ]])
 targets = np.array([13, 10.5])
 
 weights = np.array([startup_time, 1.0 / v_avg])
 print("Trained loss:", squared_loss(weights, inputs, targets))

了解错误后,您需要一种方法来了解需要朝哪个方向修改参数以减少错误。让我们分析一个具体的例子。假设一次旅行的持续时间为 12 分钟,距离为 6 公里。要用我们的模型精确预测这个值,模型的正确参数应该是 30 公里。

让我们看一下平方误差相对于我们的参数(平均速度)的图,以获得一些见解。整个代码很简单:

 import matplotlib.pyplot as plt
 import numpy as np
 
 trip_distance = 6.0
 trip_duration = 12.0
 trip_avg_speed = 30.0
 
 def duration(distance, speed):
     return distance * 1/speed * 60.0
 
 real_duration = duration(trip_distance, trip_avg_speed)
 
 speeds = np.linspace(5, 50)
 duration = np.vectorize(lambda speed: duration(trip_distance, speed))(speeds)
 error = 12 - duration
 
 fig, ax = plt.subplots()
 ax.grid(True, which='both')
 
 ax.plot(speeds, duration, label='Trip duration wrt speed')
 ax.plot(speeds, error, label='Error wrt to speed param')
 ax.scatter([trip_avg_speed], [0], label='Error for real average speed')
 
 plt.xlabel('average speed')
 plt.legend()
 plt.show()

蓝色曲线显示了行程持续时间相对于速度的演变。更快的行程显然会导致更短的行程持续时间。橙色曲线将误差显示为实际持续时间(此处为 12 分钟)与给定所选速度的行程持续时间之间的简单差异。对于实际平均速度:30km/h,该误差为零。绿色曲线是平方误差。与误差类似,平均速度为 30 km/h 时达到零。