给定以下代码,您会做什么
remove the second loop using vectorization
。
from numba import prange
import numpy as np
start_at_bar = 2
lookback = 3
relative_weight = 1.0
lookback_squared = np.power(lookback, 2)
denominator = lookback_squared * 2 * relative_weight
price_feed = [4308.172, 4175.935, 4070.76, 4112.74, 4029.135, 4308.172, 4175.935]
check_1 = []
for index in prange(start_at_bar, len(price_feed)):
current_weight = 0.0
cumulative_weight = 0.0
for j in range(start_at_bar):
w = np.power(
1 + (np.power(j, 2) / denominator),
-relative_weight,
)
y = price_feed[index - j]
current_weight += y * w
cumulative_weight += w
check_1.append(current_weight / cumulative_weight)
这是我的尝试,不幸的是输出不一样......
from numba import prange
import numpy as np
start_at_bar = 2
lookback = 3
relative_weight = 1.0
lookback_squared = np.power(lookback, 2)
denominator = lookback_squared * 2 * relative_weight
price_feed = [4308.172, 4175.935, 4070.76, 4112.74, 4029.135, 4308.172, 4175.935]
check_2 = []
for index in prange(start_at_bar, len(price_feed)):
current_weight = 0.0
cumulative_weight = 0.0
j_range = np.arange(start_at_bar)
weights = (1 + (j_range**2 / denominator)) ** (-relative_weight)
current_weight = np.dot(price_feed[index - j_range], weights)
cumulative_weight = np.sum(weights)
check_2.append(current_weight / cumulative_weight)
这个一定要坚持
check_1 == check_2
我尝试使用 numpy
.dot
来乘以数组切片并查询 ChatGPT 和 Bard,但解决方案目前无法解决我..他们也是!
您需要对优化版本的代码进行的更改:
来自 numba 导入计划
import numpy as np
start_at_bar = 2
lookback = 3
relative_weight = 1.0
lookback_squared = np.power(lookback, 2)
denominator = lookback_squared * 2 * relative_weight
price_feed = [4308.172, 4175.935, 4070.76, 4112.74, 4029.135, 4308.172, 4175.935]
check_1 = []
# Precompute weights outside the loop
weights = np.power(
1 + (np.power(np.arange(start_at_bar), 2) / denominator),
-relative_weight,
)
for index in prange(start_at_bar, len(price_feed)):
current_weight = 0.0
cumulative_weight = 0.0
# Calculate wtd sum and cumulative wt without the inside loop
current_weight = np.sum(price_feed[index - start_at_bar : index] * weights)
cumulative_weight = np.sum(weights)
check_1.append(current_weight / cumulative_weight)
print("Optimized Code Output:", check_1)
我认为这适合你。