【问题标题】:How to limit numpy float computation precision如何限制 numpy 浮点计算精度
【发布时间】:2021-04-12 15:10:25
【问题描述】:

我正在使用 numpy 来计算相机图像,这将由无符号整数灰度值表示。 我想限制浮点精度,以加快计算速度。 举个例子,假设我正在计算由高斯光束的强度分布形成的图像:

import numpy as np
import matplotlib.pyplot as plt

nx = 1000
ny = 1000
px = 5e-3

x = np.linspace(0, nx * px)
y = np.linspace(0, ny * px)

X, Y = np.meshgrid(x, y)

xc = x[-1] / 2
yc = y[-1] / 2
sigma = 1

gauss_profile = np.exp(-(np.square(X - xc) + np.square(Y - yc)) / sigma**2)
print(gauss_profile.dtype)

bitdepth = 12
gauss_profile *= 2**bitdepth - 1
camera_image = gauss_profile.astype(np.uint16)

#%% plot image
fig = plt.figure()
ax = fig.add_subplot(111)
grey_cmap = plt.get_cmap('gray')
im = ax.imshow(camera_image,
               cmap=grey_cmap,
               extent=(0, nx * px,
                       0, ny * px))
plt.xlabel('x (mm)')
plt.ylabel('y (mm)')
plt.colorbar(im)

有没有办法让 gauss_profile 不使用 float64 精度计算,而是使用足以获得所需灰度值的最小分辨率? 到目前为止,我之前尝试初始化数组并将其传递给 np.exp 调用中的 out 关键字,但这会导致 TypeError 或 ValueError 取决于 dtype。有没有其他方法可以加速这个计算?

【问题讨论】:

  • @AKX 这就是为什么它是一个评论,我不能保证它会为 OP 的目的工作。
  • 我的笔记本电脑能够在 0.22 秒内计算出其中的 2000 个 camera_images。您是在一些非常受限的设备上运行它,还是参​​数变化很大..?
  • @AKX。过早的优化...
  • @Richard 在这种情况下,为 SO 简化您的用例可能不是正确的选择,那么 :-) 那么您究竟会如何处理 camera_image?你能在计算它的函数上加上一个lru_cache 装饰器吗?
  • @Richard 在你原来的问题中知道这一点会很有用,你知道的。 ;-) 无论哪种方式,如果您将这个“光圈图像”视为“画笔”(只需几个参数即可轻松缓存),然后您可以通过简单的+= 操作将其绘制到您的相机图像上呢?

标签: python numpy optimization


【解决方案1】:

也许尝试使用 dtype np.halfnp.single 设置您的 ndarrays xy。这将限制浮点精度。但我不知道计算是否仍在进行。

np.half:半精度浮点数类型。 (float16)

np.single:单精度浮点数类型,兼容C float.(float32)

x = np.linspace(0, nx * px, dtype=np.half)
y = np.linspace(0, ny * px, dtype=np.half)

...

【讨论】:

    猜你喜欢
    • 2021-11-11
    • 1970-01-01
    • 2017-09-23
    • 2014-09-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-15
    • 2014-03-12
    相关资源
    最近更新 更多