Closed tvatter closed 5 months ago
Hi, could you please make a 2D heat plot to see what the target function look like?
import matplotlib.pyplot as plt
from matplotlib import cm
x, y = (
dataset["test_input"][:, 0].detach().cpu().numpy(),
dataset["test_input"][:, 1].detach().cpu().numpy(),
)
z = dataset["test_label"].detach().cpu().numpy()
fig, ax = plt.subplots(subplot_kw={"projection": "3d"})
ax.view_init(elev=30, azim=110, roll=0)
surf = ax.plot_trisurf(x, y, z, cmap=cm.jet, linewidth=0.1)
fig.colorbar(surf, shrink=0.5, aspect=5)
plt.show()
But I find it easier to see on a 1d plot as shown above :)
How about
f = lambda x: black_scholes_price(x[:, 0], x[:, 1])
to
f = lambda x: black_scholes_price(x[:, [0]], x[:, [1]])
I was gonna suggest: import numpy as np import pandas as pd import torch import matplotlib.pyplot as plt
torch.set_default_dtype(torch.float64)
from kan import create_dataset
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
def black_scholes_price(k, T, r=0.0, sigma=0.2): """Calculate Black Scholes option price using the given parameters.""" m = torch.distributions.Normal(0, 1) d1 = (k + (r + sigma*2 / 2) T) / (sigma torch.sqrt(T)) d2 = d1 - sigma torch.sqrt(T) price = m.cdf(d1) - torch.exp(-k - r T) m.cdf(d2) return price
f = lambda x: black_scholes_price(x[:,[0]], x[:,[1]])
dataset = create_dataset(f, n_var=2, ranges=np.array([[-1, 1], [1 / 52, 2]]))
if dataset['train_label'].ndim == 1: dataset['train_label'] = dataset['train_label'].unsqueeze(1)
print("Input shape:", dataset['train_input'].shape) print("Label shape:", dataset['train_label'].shape)
data_np = torch.cat([dataset['train_input'], dataset['train_label']], dim=1).detach().numpy() df = pd.DataFrame(data_np, columns=['k', 'T', 'price'])
plt.figure(figsize=(10, 6)) scatter = plt.scatter(df['k'], df['price'], c=df['T'], cmap='viridis') plt.colorbar(scatter, label='Time to Maturity (T)') plt.xlabel('Strike Price (k)') plt.ylabel('Option Price') plt.title('Black Scholes Option Pricing Visualization') plt.show()
this worked but I didn't get machine precision when training and pruning and substituting analytics functions...
Hi to get machine precision, you need both: (1) enough data; (2) enough grid size. For (2), please try grid extension for better accuracy, e.g., this example.
f = lambda x: black_scholes_price(x[:,[0]], x[:,[1]])
solved it, thanks a lot !
I'm trying to fit a vanilla Black-Scholes model as follows:
However, when trying a simple KAN model as follows, the loss immediately plateaus and nothing much happens:
Note that I've tried various configurations of width, grid, k, lambda, etc, not sure what I am doing wrong.