删除Python中不必要的for循环

问题描述 投票:0回答:1

给定以下代码,您会做什么

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,但解决方案目前无法解决我..他们也是!

python numpy performance optimization vectorization
1个回答
0
投票

您需要对优化版本的代码进行的更改:

  1. 在current_weight的计算中使用start_at_bar代替j_range。这确保了我们考虑 Price_feed 中的正确指数。
  2. 更正权重的计算以确保其与原始代码中使用的逻辑相匹配。

来自 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)

我认为这适合你。

© www.soinside.com 2019 - 2024. All rights reserved.