我有以下代码:
import numpy as np
import torch
from torch import autograd
# Define the parameters with requires_grad=True
r = torch.tensor(0.03, requires_grad=True)
q = torch.tensor(0.02, requires_grad=True)
v = torch.tensor(0.14, requires_grad=True)
S = torch.tensor(1001.0, requires_grad=True)
# Generate random numbers and other tensors
Z = torch.randn(10000, 5)
t = torch.tensor(np.arange(1.0, 6.0))
c = torch.tensor([0.2, 0.3, 0.4, 0.5, 0.6])
# Calculate mc_S with differentiable operations
mc_S = S * torch.exp((r - q - 0.5 * v * v) * t + Z.cumsum(axis=1))
# Calculate payoff with differentiable operations
res = []
mask = 1.0
for col, coup in zip(mc_S.T, c):
payoff = mask * torch.where(col > S, coup, torch.tensor(0.0))
res.append(payoff)
mask = mask * (payoff == 0)
v = torch.stack(res).T
result = v.sum(axis=1).mean()
# Compute gradients - breaks here
grads = autograd.grad(result, [r, q, v, S], allow_unused=True, retain_graph=True)
print(grads)
我正在尝试为具有早期淘汰的可自动调用选项定价,并且需要输入变量的敏感性。
但是,优惠券的计算方式(上面代码中的 c 张量)破坏了计算图,我无法获得梯度。有没有办法让这个代码来计算导数?
谢谢
torch.where(col > S, coup, torch.tensor(0.0))
不是可微分运算。它没有平滑度,您要么选择 coup
要么选择 0
。该函数没有斜率。 coup * torch.sigmoid(col - S)
将为您提供与您的操作类似但可微分的结果。
在您的示例中,当
coup
时,我们从 col > S
中进行选择,否则选择 0
。在可微分版本中,当 coup
时我们得到 col >> S
,当 0
时我们得到 col << S
。在中间,我们得到了介于两者之间的东西,您可能需要调整比例和偏移量以获得应用程序所需的确切损失函数,例如alpha * (col + beta / alpha > S)
。
import numpy as np
import torch
from torch import autograd
# Define the parameters with requires_grad=True
r = torch.tensor(0.03, requires_grad=True)
q = torch.tensor(0.02, requires_grad=True)
v = torch.tensor(0.14, requires_grad=True)
S = torch.tensor(1001.0, requires_grad=True)
# Generate random numbers and other tensors
Z = torch.randn(10000, 5)
t = torch.tensor(np.arange(1.0, 6.0))
c = torch.tensor([0.2, 0.3, 0.4, 0.5, 0.6])
# Calculate mc_S with differentiable operations
mc_S = S * torch.exp((r - q - 0.5 * v * v) * t + Z.cumsum(axis=1))
# Calculate payoff with differentiable operations
res = []
mask = 1.0
for col, coup in zip(mc_S.T, c):
payoff = coup * torch.sigmoid(col - S)
res.append(payoff)
mask = mask * (payoff == 0)
v = torch.stack(res).T
result = v.sum(axis=1).mean()
# Compute gradients - breaks here
grads = autograd.grad(result, [r, q, v, S], allow_unused=True, retain_graph=True)
print(grads)