Skip to content

Commit

Permalink
[models/kernel_regression](feat) Add functional implementation of ker…
Browse files Browse the repository at this point in the history
…nel regression model
  • Loading branch information
kzajac97 committed Dec 10, 2023
1 parent dc1794b commit beb159d
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 0 deletions.
23 changes: 23 additions & 0 deletions pydentification/models/kernel_regression/functional.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from typing import Callable

import torch
from torch import Tensor

Expand All @@ -15,3 +17,24 @@ def point_wise_distance_tensor(x: Tensor, y: Tensor, p: float = 1.0) -> Tensor:
return torch.abs(x.unsqueeze(dim=1) - y.unsqueeze(dim=0)) # shortcut for P=1
# generic equation for point-wise P-norm
return torch.pow(torch.pow(torch.abs(x.unsqueeze(dim=1) - y.unsqueeze(dim=0)), p), 1 / p).squeeze()


def kernel_regression(inputs: Tensor, memory: Tensor, targets: Tensor, kernel: Callable) -> Tensor:
"""
Functional implementation of kernel regression, which computes the weighted average of the memory (training data)
using kernel function given as callable.
:note: This implementation only support MISO systems, i.e. multiple inputs, but only single output.
:param inputs: points where function is to be predicted from training data
:param memory: points where function was evaluated during training
:param targets: values of function at memory points
:param kernel: kernel function
"""
kernels = kernel(memory, inputs) # (MEMORY_SIZE, INPUT_SIZE)
# unsqueeze along last dimension to allow broadcasting target values over kernel density
targets = targets.unsqueeze(-1) # (MEMORY_SIZE, 1, 1)
# average over kernel density for each point function is predicted for
predictions = (kernels * targets).sum(axis=0) / kernels.sum(dim=0)

return predictions
Empty file.

0 comments on commit beb159d

Please sign in to comment.