我正在尝试计算期权价格y对输入现货价格的梯度。这是我的代码。现在看来梯度不是没有梯度,但它返回张量误差,我认为我做对了。
def vanilla_price(X):
moneyness_inverse = X.iloc[:, 0]
sig = X.iloc[:, 1]
r = X.iloc[:, 2]
T = X.iloc[:, 3]
d1 = (np.log(moneyness_inverse) + (r + 0.5 * sig ** 2) * T) / (sig*
np.sqrt(T))
d2 = (np.log(moneyness_inverse) + (r - 0.5 * sig ** 2)* T) / (sig * np.sqrt(T))
result = ((moneyness_inverse) * ss.norm.cdf(d1, 0.0, 1.0) - np.exp(-r * T) * ss.norm.cdf(d2, 0.0, 1.0))
return result
spot = 100.001
spot = 100.001
weight = tf.keras.preprocessing.sequence.pad_sequences(np.array(X), dtype
='float32')
with tf.GradientTape(persistent=True) as g:
g.watch(weight)
y = vanilla_price(weight)
jacob_actual = g.gradient(y, weight)[:, 0]
print(jacob_actual)
ValueError Traceback (most recent call last)
<ipython-input-231-c20368558cc7> in <module>
3
4 with tf.GradientTape(persistent=True) as g:
----> 5 g.watch(weight)
6 y = vanilla_price(weight)
7
~\Anaconda3\lib\site-packages\tensorflow_core\python\eager\backprop.py in
watch(self, tensor)
848 pywrap_tensorflow.IsVariable(t)):
849 raise ValueError("Passed in object of type {}, not
tf.Tensor".format(
--> 850 type(t)))
851 if not t.dtype.is_floating:
852 logging.log_first_n(
ValueError: Passed in object of type <class 'numpy.ndarray'>, not
tf.Tensor
谁能给我一个提示或我做错了什么?