Kolmogorov-Arnold Networks (KAN) 是 Multi-Layer Perceptrons (MLP) 的替代品。该模型使用 KAN 的方式类似于我们的 MLP 模型。

参考文献 - Ziming Liu, Yixuan Wang, Sachin Vaidya, Fabian Ruehle, James Halverson, Marin Soljačić, Thomas Y. Hou, Max Tegmark. “KAN: Kolmogorov–Arnold Networks”


来源

KANLinear

 KANLinear (in_features, out_features, grid_size=5, spline_order=3,
            scale_noise=0.1, scale_base=1.0, scale_spline=1.0,
            enable_standalone_scale_spline=True, base_activation=<class
            'torch.nn.modules.activation.SiLU'>, grid_eps=0.02,
            grid_range=[-1, 1])

KANLinear


来源

KAN

 KAN (h, input_size, grid_size:int=5, spline_order:int=3,
      scale_noise:float=0.1, scale_base:float=1.0, scale_spline:float=1.0,
      enable_standalone_scale_spline:bool=True, grid_eps:float=0.02,
      grid_range:list=[-1, 1], n_hidden_layers:int=1,
      hidden_size:Union[int,list]=512, stat_exog_list=None,
      hist_exog_list=None, futr_exog_list=None, exclude_insample_y=False,
      loss=MAE(), valid_loss=None, max_steps:int=1000,
      learning_rate:float=0.001, num_lr_decays:int=-1,
      early_stop_patience_steps:int=-1, val_check_steps:int=100,
      batch_size:int=32, valid_batch_size:Optional[int]=None,
      windows_batch_size=1024, inference_windows_batch_size=-1,
      start_padding_enabled=False, step_size:int=1,
      scaler_type:str='identity', random_seed:int=1,
      drop_last_loader:bool=False, alias:Optional[str]=None,
      optimizer=None, optimizer_kwargs=None, dataloader_kwargs=None,
      **trainer_kwargs)

*KAN

简单的 Kolmogorov-Arnold Network (KAN)。该网络使用 Kolmogorov-Arnold 近似定理,其中学习样条函数来逼近更复杂的函数。与 MLP 不同,非线性函数是在边缘学习的,而节点仅对不同的学习函数进行求和。

参数
h: int,预测范围(forecast horizon)。
input_size: int,考虑的自回归输入(滞后),y=[1,2,3,4] input_size=2 -> lags=[1,2]。
grid_size: int,样条函数用于逼近函数的区间数量。
spline_order: int,B样条的阶数。
scale_noise: float,样条函数的正则化系数。
scale_base: float,基函数的缩放系数。
scale_spline: float,样条函数的缩放系数。
enable_standalone_scale_spline: bool,是否对每个样条函数进行单独缩放。
grid_eps: float,用于数值稳定性。
grid_range: list,用于样条逼近的网格范围。
n_hidden_layers: int,KAN 的隐藏层数量。
hidden_size: int 或 list,KAN 每个隐藏层的单元数量。如果为整数,则所有隐藏层大小相同。使用列表指定每个隐藏层的大小。

stat_exog_list: str list,静态外部特征列。
hist_exog_list: str list,历史外部特征列。
futr_exog_list: str list,未来外部特征列。
exclude_insample_y: bool=False,如果为 True,模型将跳过自回归特征 y[t-input_size:t]。
loss: PyTorch 模块,从损失函数集合中实例化的训练损失类。
valid_loss: PyTorch 模块=loss,从损失函数集合中实例化的验证损失类。
max_steps: int=1000,最大训练步数。
learning_rate: float=1e-3,学习率,范围在 (0, 1) 之间。
num_lr_decays: int=-1,学习率衰减次数,均匀分布在 max_steps 中。
early_stop_patience_steps: int=-1,早停前等待的验证迭代次数。
val_check_steps: int=100,每次验证损失检查之间的训练步数。
batch_size: int=32,每个批次中不同时间序列的数量。
valid_batch_size: int=None,每个验证和测试批次中不同时间序列的数量,如果为 None 则使用 batch_size。
windows_batch_size: int=1024,每个训练批次中采样的窗口数量,默认为全部使用。
inference_windows_batch_size: int=-1,每个推理批次中采样的窗口数量,-1 为全部使用。
start_padding_enabled: bool=False,如果为 True,模型将按 input_size 在时间序列开头填充零。
step_size: int=1,每个时间数据窗口之间的步长。
scaler_type: str=‘identity’,用于时间输入归一化的缩放器类型,见temporal scalers
random_seed: int=1,用于 pytorch 初始化器和 numpy 生成器的随机种子。
drop_last_loader: bool=False,如果为 True,TimeSeriesDataLoader 会丢弃最后一个非完整批次。
alias: str, 可选,模型的自定义名称。
optimizer: ‘torch.optim.Optimizer’ 的子类,可选,用户指定的优化器,而不是默认选择 (Adam)。
optimizer_kwargs: dict, 可选,用户指定的 optimizer 使用的参数列表。
dataloader_kwargs: dict, 可选,由 TimeSeriesDataLoader 传递给 PyTorch Lightning 数据加载器的参数列表。
**trainer_kwargs: int,继承自 PyTorch Lightning 的 trainer 的关键字 trainer 参数。

参考文献
- Ziming Liu, Yixuan Wang, Sachin Vaidya, Fabian Ruehle, James Halverson, Marin Soljačić, Thomas Y. Hou, Max Tegmark. “KAN: Kolmogorov-Arnold Networks”*


KAN.fit

 KAN.fit (dataset, val_size=0, test_size=0, random_seed=None,
          distributed_config=None)

*拟合。

fit 方法使用初始化参数(learning_ratewindows_batch_size 等)和初始化期间定义的 loss 函数来优化神经网络的权重。在 fit 中,我们使用 PyTorch Lightning 的 Trainer,它继承了初始化的 self.trainer_kwargs 来定制其输入,参见 PL 的 trainer 参数

该方法设计用于与 SKLearn-like 类兼容,特别是与 StatsForecast 库兼容。

默认情况下,model 不保存训练检查点以保护磁盘内存,如需保存,请在 __init__ 中将 enable_checkpointing 设置为 True

参数
dataset: NeuralForecast 的 TimeSeriesDataset,参见documentation
val_size: int,用于时间序列交叉验证的验证集大小。
random_seed: int=None,用于 pytorch 初始化器和 numpy 生成器的随机种子,覆盖 model.__init__ 中的设置。
test_size: int,用于时间序列交叉验证的测试集大小。
*


KAN.predict

 KAN.predict (dataset, test_size=None, step_size=1, random_seed=None,
              quantiles=None, **data_module_kwargs)

*预测。

使用 PL 的 Trainer 执行 predict_step 进行神经网络预测。

参数
dataset: NeuralForecast 的 TimeSeriesDataset,参见documentation
test_size: int=None,用于时间序列交叉验证的测试集大小。
step_size: int=1,每个窗口之间的步长。
random_seed: int=None,用于 pytorch 初始化器和 numpy 生成器的随机种子,覆盖 model.__init__ 中的设置。
quantiles: list of floats, 可选 (默认=None),要预测的目标分位数。
**data_module_kwargs: PL 的 TimeSeriesDataModule 参数,参见 documentation.*

使用示例

import pandas as pd
import matplotlib.pyplot as plt

from neuralforecast import NeuralForecast
from neuralforecast.models import KAN
from neuralforecast.losses.pytorch import DistributionLoss
from neuralforecast.utils import AirPassengersPanel, AirPassengersStatic

Y_train_df = AirPassengersPanel[AirPassengersPanel.ds<AirPassengersPanel['ds'].values[-12]] # 132 train
Y_test_df = AirPassengersPanel[AirPassengersPanel.ds>=AirPassengersPanel['ds'].values[-12]].reset_index(drop=True) # 12 test

fcst = NeuralForecast(
    models=[
            KAN(h=12,
                input_size=24,
                loss = DistributionLoss(distribution="Normal"),
                max_steps=100,
                scaler_type='standard',
                futr_exog_list=['y_[lag12]'],
                hist_exog_list=None,
                stat_exog_list=['airline1'],
                ),     
    ],
    freq='ME'
)
fcst.fit(df=Y_train_df, static_df=AirPassengersStatic)
forecasts = fcst.predict(futr_df=Y_test_df)

# Plot quantile predictions
Y_hat_df = forecasts.reset_index(drop=False).drop(columns=['unique_id','ds'])
plot_df = pd.concat([Y_test_df, Y_hat_df], axis=1)
plot_df = pd.concat([Y_train_df, plot_df])

plot_df = plot_df[plot_df.unique_id=='Airline1'].drop('unique_id', axis=1)
plt.plot(plot_df['ds'], plot_df['y'], c='black', label='True')
plt.plot(plot_df['ds'], plot_df['KAN-median'], c='blue', label='median')
plt.fill_between(x=plot_df['ds'][-12:], 
                 y1=plot_df['KAN-lo-90'][-12:].values,
                 y2=plot_df['KAN-hi-90'][-12:].values,
                 alpha=0.4, label='level 90')
plt.legend()
plt.grid()