gpt4 book ai didi

python - 有效计算平方差和

转载 作者:太空宇宙 更新时间:2023-11-03 17:15:26 25 4
gpt4 key购买 nike

这是一个循环,用于提取两个图像的 RGB 值,并计算所有三个 channel 的平方差之和。直接在我的 main.py 中运行此代码需要 0.07 秒。如果我在这个 .pyx 文件中运行它,速度会降低到 1 秒。我已阅读有关 cdef 函数的内容,但当时我没有成功传递数组。任何将此函数转换为 cdef 函数的帮助将不胜感激。我真的需要这个循环尽可能快地进行。

from cpython cimport array
import array
import numpy as np
cimport numpy as np

def fittnes(Orginal, Mutated):

Fittnes = 0

for x in range(0, 299):

for y in range(0, 299):

DeltaRed = (Orginal[x][y][0] - Mutated[x][y][0])
DeltaGreen = (Orginal[x][y][1] - Mutated[x][y][1])
DeltaBlue = (Orginal[x][y][2] - Mutated[x][y][2])

Fittnes += (DeltaRed * DeltaRed + DeltaGreen * DeltaGreen + DeltaBlue * DeltaBlue)

return Fittnes

我的 Main.py 函数调用

 NewScore = cythona.fittnes(numpy.array(Orginal), numpy.array(MutatedImage))

最佳答案

让我有兴趣了解加速数字,所以我将其作为解决方案发布。因此,正如评论中所述/讨论的那样,如果输入是 NumPy 数组,您可以使用 native NumPy 工具,在本例中 ndarray.sum() ,就像这样 -

out = ((Orginal - Mutated)**2).sum()

您还可以使用非常高效的np.einsum对于相同的任务,就像这样 -

sub = Orginal - Mutated
out = np.einsum('ijk,ijk->',sub,sub)

运行时测试

定义函数 -

def org_app(Orginal,Mutated):
Fittnes = 0
for x in range(0, Orginal.shape[0]):
for y in range(0, Orginal.shape[1]):
DR = (Orginal[x][y][0] - Mutated[x][y][0])
DG = (Orginal[x][y][1] - Mutated[x][y][1])
DB = (Orginal[x][y][2] - Mutated[x][y][2])
Fittnes += (DR * DR + DG * DG + DB * DB)
return Fittnes

def einsum_based(Orginal,Mutated):
sub = Orginal - Mutated
return np.einsum('ijk,ijk->',sub,sub)

def dot_based(Orginal,Mutated): # @ali_m's suggestion
sub = Orginal - Mutated
return np.dot(sub.ravel(), sub.ravel())

def vdot_based(Orginal,Mutated): # variant of @ali_m's suggestion
sub = Orginal - Mutated
return np.vdot(sub, sub)

时间安排 -

In [14]: M,N = 100,100
...: Orginal = np.random.rand(M,N,3)
...: Mutated = np.random.rand(M,N,3)
...:

In [15]: %timeit org_app(Orginal,Mutated)
...: %timeit ((Orginal - Mutated)**2).sum()
...: %timeit einsum_based(Orginal,Mutated)
...: %timeit dot_based(Orginal,Mutated)
...: %timeit vdot_based(Orginal,Mutated)
...:
10 loops, best of 3: 54.9 ms per loop
10000 loops, best of 3: 112 µs per loop
10000 loops, best of 3: 69.8 µs per loop
10000 loops, best of 3: 86.2 µs per loop
10000 loops, best of 3: 85.3 µs per loop

In [16]: # Inputs
...: M,N = 1000,1000
...: Orginal = np.random.rand(M,N,3)
...: Mutated = np.random.rand(M,N,3)
...:

In [17]: %timeit org_app(Orginal,Mutated)
...: %timeit ((Orginal - Mutated)**2).sum()
...: %timeit einsum_based(Orginal,Mutated)
...: %timeit dot_based(Orginal,Mutated)
...: %timeit vdot_based(Orginal,Mutated)
...:
1 loops, best of 3: 5.49 s per loop
10 loops, best of 3: 63 ms per loop
10 loops, best of 3: 23.9 ms per loop
10 loops, best of 3: 24.9 ms per loop
10 loops, best of 3: 24.9 ms per loop

关于python - 有效计算平方差和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33709902/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com