gpt4 book ai didi

python - 如何在不使用循环的情况下重写 NumPy 代码

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

我有代码应该找出生成的 NumPy 数组中的极值并将它们一一写在一个新数组中(最小值、最大值、最小值、最大值等)这段代码可以工作,但是速度太慢。所以我需要在没有循环的情况下完成它。我已经用 numpy.logic_and 删除了一个,但剩下的两个是大的。也许 np.where 可以工作,但我不知道如何在这里使用它们。

代码

import numpy as np
from scipy.signal import argrelextrema
import matplotlib.pyplot as plt
import timeit


if __name__ == '__main__':
N = 1000000 # Length of an array
T = 4 # Diff between indexes of an array
D = 4 # Diff between values of an array
x = np.random.uniform(low=-1, high=1, size=N)
x[0] = 1 # Starting value
x = np.cumsum(x) # Using cumsum for faster generating
index = [] # Array for indexes of local extremums
mins = argrelextrema(x, np.less)[0] # Array of min local extremums
maxs = argrelextrema(x, np.greater)[0] # Array of max local extremums
# print('AutoGenerated NumPy massive prepared using np.cumsum() \n', x)
index.append(mins[0]) # Zero will be min
min_elem = mins[0]
assert index[0] in mins
for max_elem in maxs:
# Checking the diff in values and in indexes, write if if suites
if x[max_elem] - x[min_elem] >= D and max_elem - min_elem >= T:
# Check if there's more suitable local minimum
min_elem = np.argmin(x[min_elem:max_elem]) + min_elem
index[-1] = min_elem
index.append(max_elem)
assert index[-1] in maxs
assert max_elem - min_elem >= T
assert x[max_elem] - x[min_elem] >= D
assert np.all(np.logical_and(x[min_elem+1:max_elem] >= x[min_elem],
x[min_elem+1:max_elem] <= x[max_elem]))
for min_elem in mins:
# Checking the diff in values and in indexes, write if if suites
if x[max_elem] - x[min_elem] >= D and min_elem - max_elem >= T:
# Check if there's more suitable local maximum
max_elem = np.argmax(x[max_elem:min_elem]) + max_elem
index[-1] = max_elem
index.append(min_elem)
assert index[-1] in mins
assert min_elem - max_elem >= T
assert x[max_elem] - x[min_elem] >= D
break

最佳答案

建议:

编辑:

  • 在测试代码之前删除所有不需要的“打印”语句,如 Console Output速度很慢并且会给你错误的计时。

  • 已添加错误消息至 assert statements例如 assert x >= 0, 'x 小于零'

  • 尝试消除 y 中的 x 语句,因为语言/编译器必须检查 y 中的每个元素以查看是否 x 存在。 References

祝你好运。

关于python - 如何在不使用循环的情况下重写 NumPy 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59017580/

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