Skip to content
Snippets Groups Projects
Commit d4407e36 authored by FROGE Ewen's avatar FROGE Ewen
Browse files

Upload New File

parent dd211099
No related branches found
No related tags found
No related merge requests found
import numpy as np
import matplotlib.pyplot as plt
from numpy.linalg import inv
from sklearn.neighbors import NearestNeighbors
def create_database(data, p, overlapping=False):
"""Create a database of tuples from the given data with optional overlapping."""
window = np.lib.stride_tricks.sliding_window_view(data, window_shape=(p + 1,))
stride = 1 if overlapping else p
db = window[0::stride, :]
return db
def prediction_neighbors(data, db, k, weighting=True, verbose=False, random=False, lr=False, normalize=False):
"""Predict future data points using nearest neighbors algorithm."""
Np, pp1 = db.shape
p = pp1 - 1
puplets = np.lib.stride_tricks.sliding_window_view(data, window_shape=(p,))
if normalize:
# Detrend puplets and database
puplet_means = np.mean(puplets, axis=1)
puplets -= puplet_means[:, np.newaxis]
db_means = np.mean(db[:, :-1], axis=1)
db -= db_means[:, np.newaxis]
neigh = NearestNeighbors(n_jobs=4)
neigh.fit(db[:, :-1])
Dist, Idx = neigh.kneighbors(puplets, n_neighbors=k)
if random:
Idx = np.random.randint(low=0, high=Np, size=Idx.shape)
if weighting:
med = np.median(Dist, axis=1)
weights = np.exp(-Dist / med[:, np.newaxis])
weights /= np.sum(weights, axis=1)[:, np.newaxis]
else:
weights = np.ones_like(Dist)
vals = np.full_like(data, np.nan)
if lr:
vals[p:] = np.sum(weights * db[Idx, -1], axis=1)[:-1]
else:
X = db[Idx, :-1]
y = (weights * db[Idx, -1])[:, :, np.newaxis]
X = np.pad(X, [(0, 0), (0, 0), (1, 0)], mode='constant', constant_values=1)
coef = inv(np.transpose(X, axes=[0, 2, 1]) @ (weights[:, :, np.newaxis] * X)) @ np.transpose(X, axes=[0, 2, 1]) @ y
vals[p:] = coef[:-1, 0, 0] + np.sum(coef[:, 1:, 0] * puplets, axis=1)[:-1]
if normalize:
vals[p:] += puplet_means[:-1]
if verbose:
print('Index', Idx)
print('Dist', Dist)
print('puplets', puplets)
return vals
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment