【问题标题】:Vectorizing theano/aesara variable operations向量化 theano/aesara 变量操作
【发布时间】:2022-11-05 15:13:14
【问题描述】:

我正在尝试以最好的矢量化方式使用 theano/aesara 计算以下函数:

![image|620x182](upload://9Px5wAGjZdkBXVBg4fqmuSPorPr.png)

我的解决方案没有矢量化,因此太慢了:

def apply_adstock_with_lag(x, L, P, D):
    """
    params:
    x: original array
    L: length
    P: peak, delay in effect
    D: decay, retain
    """
    x = np.append(np.zeros(L - 1), x)

    weights = [0 for _ in range(L)]
    for l in range(L):
        weight = D ** ((l - P) ** 2)
        weights[L - 1 - l] = weight
    weights = np.array(weights)
    adstocked_x = []
    for i in range(L - 1, len(x)):
        x_array = x[i - L + 1:i + 1]
        xi = sum(x_array * weights) / sum(weights)
        adstocked_x.append(xi)
    adstocked_x = tt.as_tensor_variable(adstocked_x)
    return adstocked_x

一个类似的函数虽然更简单,但它的矢量化解决方案可以在下面找到,请注意,这可能要快得多,这可能是由于矢量化操作:

![image|252x39](upload://ucZeqCmCXcBRAHLdA7lJ0crs1Oz.png)

def adstock_geometric_theano_pymc3(x, theta):
    x = tt.as_tensor_variable(x)

    def adstock_geometric_recurrence_theano(index, input_x, decay_x, theta):
        return tt.set_subtensor(decay_x[index], tt.sum(input_x + theta * decay_x[index - 1]))

    len_observed = x.shape[0]

    x_decayed = tt.zeros_like(x)
    x_decayed = tt.set_subtensor(x_decayed[0], x[0])

    output, _ = theano.scan(
        fn=adstock_geometric_recurrence_theano,
        sequences=[tt.arange(1, len_observed), x[1:len_observed]],
        outputs_info=x_decayed,
        non_sequences=theta,
        n_steps=len_observed - 1
    )

    return output[-1]

我无法为我的 adstock 功能提出矢量化解决方案,有人可以试一试吗?

【问题讨论】:

    标签: python vectorization theano pymc3 pymc


    【解决方案1】:

    你有没有尝试过:

    def apply_adstock_with_lag(x, L, P, D):
        adstocked_x = np.convolve(x, D**((np.arange(0, L, 1) - P)**2))[:-(L-1)] / sum(D**((np.arange(0, L, 1) - P)**2))
        adstocked_x = at.as_tensor_variable(adstocked_x)
        return adstocked_x
    

    这应该工作

    【讨论】:

      猜你喜欢
      • 2021-05-31
      • 2011-11-04
      • 2021-08-26
      • 1970-01-01
      • 1970-01-01
      • 2020-12-06
      • 1970-01-01
      • 2015-07-05
      • 1970-01-01
      相关资源
      最近更新 更多