Skip to content

Commit 8c39001

Browse files
0.26.4 Z -> y
1 parent 7818bbd commit 8c39001

5 files changed

Lines changed: 79 additions & 576 deletions

File tree

notebooks/00_spotPython_tests.ipynb

Lines changed: 5 additions & 5 deletions
Large diffs are not rendered by default.

pyproject.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ build-backend = "setuptools.build_meta"
77

88
[project]
99
name = "spotpython"
10-
version = "0.26.3"
10+
version = "0.26.4"
1111
authors = [
1212
{ name="T. Bartz-Beielstein", email="tbb@bartzundbartz.de" }
1313
]

src/spotpython/gp/gp_sep.py

Lines changed: 57 additions & 57 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import math
22
import numpy as np
3-
from spotpython.gp.covar import covar_sep_symm, covar_sep, diff_covar_sep_symm
3+
from spotpython.gp.covar import covar_sep_symm, covar_sep
44
from spotpython.gp.matrix import new_vector
55
from spotpython.gp.lite import predGPsep_lite
66
from spotpython.gp.likelihood import nlsep, gradnlsep
@@ -247,13 +247,13 @@ class GPsep:
247247
m: Number of input dimensions.
248248
n: Number of observations.
249249
X: Input data matrix.
250-
Z: Output data vector.
250+
y: Output data vector.
251251
d: Length-scale parameters.
252252
g: Nugget parameter.
253253
K: Covariance matrix.
254254
Ki: Inverse of covariance matrix.
255-
KiZ: Product of Ki and Z.
256-
phi: Scalar value from Z^T Ki Z calculation.
255+
Kiy: Product of Ki and y.
256+
phi: Scalar value from y^T Ki y calculation.
257257
dK: Boolean flag for calculating derivatives.
258258
DK: Matrix of derivatives.
259259
ldetK: Log determinant of K.
@@ -270,7 +270,7 @@ class GPsep:
270270
def __init__(
271271
self,
272272
X: np.ndarray = None,
273-
Z: np.ndarray = None,
273+
y: np.ndarray = None,
274274
d: np.ndarray = None,
275275
g: float = None,
276276
nlsep_method="inv",
@@ -288,7 +288,7 @@ def __init__(
288288
Args:
289289
X (np.ndarray):
290290
Input data matrix of shape (n, m). If pandas DataFrame, will be converted to numpy array.
291-
Z (np.ndarray):
291+
y (np.ndarray):
292292
Output data vector of length n. If pandas Series, will be converted to numpy array.
293293
d (np.ndarray):
294294
Length-scale parameters.
@@ -315,23 +315,23 @@ def __init__(
315315
# convert pandas dataframes or series to numpy arrays
316316
if hasattr(X, "to_numpy"):
317317
X = X.to_numpy()
318-
if Z is not None:
319-
if hasattr(Z, "to_numpy"):
320-
Z = Z.to_numpy()
321-
Z = Z.reshape(-1, 1)
322-
if X is not None and Z is not None:
318+
if y is not None:
319+
if hasattr(y, "to_numpy"):
320+
y = y.to_numpy()
321+
y = y.reshape(-1, 1)
322+
if X is not None and y is not None:
323323
if max_points is not None:
324-
X, Z = select_distant_points(X, Z, max_points)
324+
X, y = select_distant_points(X, y, max_points)
325325
print(f"Selected {max_points} points for the model.")
326326
self.m = None # (int) number of input dimensions
327327
self.n = None # (int) number of observations
328328
self.X = X
329-
self.Z = Z
329+
self.y = y
330330
self.d = d
331331
self.g = g
332332
self.K = None
333333
self.Ki = None
334-
self.KiZ = None
334+
self.Kiy = None
335335
self.phi = None
336336
self.dK = None # boolean
337337
self.DK = None # matrix
@@ -348,7 +348,7 @@ def __init__(
348348
# need to store the initial parameters for the fit method (sklearn compatibility)
349349
self.init_params = {
350350
"X": X,
351-
"Z": Z,
351+
"y": y,
352352
"d": d,
353353
"g": g,
354354
"nlsep_method": nlsep_method,
@@ -376,7 +376,7 @@ def get_params(self, deep=True):
376376
"""
377377
return {
378378
"X": self.X,
379-
"Z": self.Z,
379+
"y": self.y,
380380
"d": self.d,
381381
"g": self.g,
382382
"nlsep_method": self.nlsep_method,
@@ -408,12 +408,12 @@ def set_params(self, **parameters):
408408

409409
return self
410410

411-
def fit(self, X: np.ndarray, Z: np.ndarray, d=None, g=None, dK: bool = True, auto_optimize: bool = None, verbosity=0) -> "GPsep":
411+
def fit(self, X: np.ndarray, y: np.ndarray, d=None, g=None, dK: bool = True, auto_optimize: bool = None, verbosity=0) -> "GPsep":
412412
"""Fit the GP model with training data and optionally auto-optimize hyperparameters.
413413
414414
Args:
415415
X: The input data matrix of shape (n, m).
416-
Z: The output data vector of length n.
416+
y: The output data vector of length n.
417417
d: The length-scale parameters. If None, will be determined
418418
automatically. Defaults to None.
419419
g: The nugget parameter. If None, will be determined automatically.
@@ -429,30 +429,30 @@ def fit(self, X: np.ndarray, Z: np.ndarray, d=None, g=None, dK: bool = True, aut
429429
GPsep: The fitted GPsep object.
430430
431431
Raises:
432-
ValueError: If X has no rows or if X and Z dimensions mismatch.
432+
ValueError: If X has no rows or if X and y dimensions mismatch.
433433
"""
434-
# if X or Z are pandas dataframes or series, convert them to numpy arrays
434+
# if X or y are pandas dataframes or series, convert them to numpy arrays
435435
if hasattr(X, "to_numpy"):
436436
X = X.to_numpy()
437-
if hasattr(Z, "to_numpy"):
438-
Z = Z.to_numpy()
439-
Z = Z.reshape(-1, 1)
440-
print(f"X shape: {X.shape}, Z shape: {Z.shape}")
437+
if hasattr(y, "to_numpy"):
438+
y = y.to_numpy()
439+
y = y.reshape(-1, 1)
440+
print(f"X shape: {X.shape}, y shape: {y.shape}")
441441
if self.max_points is not None:
442-
X, Z = select_distant_points(X, Z, self.max_points)
442+
X, y = select_distant_points(X, y, self.max_points)
443443
print(f"Selected {self.max_points} points for the model.")
444444
if auto_optimize is None:
445445
auto_optimize = self.auto_optimize
446446
n, m = X.shape
447447
if n == 0:
448448
raise ValueError("X must be a matrix with rows.")
449-
if len(Z) != n:
450-
raise ValueError(f"X has {n} rows but Z length is {len(Z)}")
449+
if len(y) != n:
450+
raise ValueError(f"X has {n} rows but y length is {len(y)}")
451451

452452
self.m = m
453453
self.n = n
454454
self.X = X
455-
self.Z = Z
455+
self.y = y
456456
self.dk = dK
457457

458458
# Determine good hyperparameters if not explicitly provided
@@ -463,7 +463,7 @@ def fit(self, X: np.ndarray, Z: np.ndarray, d=None, g=None, dK: bool = True, aut
463463
# Process nugget arguments
464464
# TODO: Check if mle is True is correct
465465
g_dict = {"mle": True} if g is None else g
466-
g_args = garg(g_dict, Z)
466+
g_args = garg(g_dict, y)
467467

468468
# Use the determined parameters if not provided
469469
d_val = d_args["start"] if d is None else d
@@ -564,13 +564,13 @@ def fit(self, X: np.ndarray, Z: np.ndarray, d=None, g=None, dK: bool = True, aut
564564
print(f"bounds: {bounds}")
565565
print(f"p: {p}")
566566
X = copy.deepcopy(self.X)
567-
Z = copy.deepcopy(self.Z)
567+
y = copy.deepcopy(self.y)
568568

569569
def objective(par):
570-
return nlsep(par, X, Z, self.nlsep_method)
570+
return nlsep(par, X, y, self.nlsep_method)
571571

572572
def gradient(par):
573-
return gradnlsep(par, X, Z, self.gradnlsep_method)
573+
return gradnlsep(par, X, y, self.gradnlsep_method)
574574

575575
result = run_minimize_with_restarts(objective=objective, gradient=gradient, x0=p, bounds=bounds, n_restarts_optimizer=self.n_restarts_optimizer, maxit=self.maxit, verb=self.verbosity)
576576

@@ -609,24 +609,24 @@ def gradient(par):
609609
self.build()
610610
return self
611611

612-
def calc_ZtKiZ(self) -> None:
612+
def calc_ytKiy(self) -> None:
613613
"""
614-
Recalculate phi and related components from Ki and Z.
614+
Recalculate phi and related components from Ki and y.
615615
"""
616-
if self.KiZ is None:
617-
self.KiZ = new_vector(self.n)
616+
if self.Kiy is None:
617+
self.Kiy = new_vector(self.n)
618618

619-
# Convert Z to numpy array if it's a pandas Series
620-
if hasattr(self.Z, "to_numpy"):
621-
Z_array = self.Z.to_numpy()
619+
# Convert y to numpy array if it's a pandas Series
620+
if hasattr(self.y, "to_numpy"):
621+
y_array = self.y.to_numpy()
622622
else:
623-
Z_array = np.asarray(self.Z)
623+
y_array = np.asarray(self.y)
624624

625-
Z = Z_array.reshape(-1, 1)
626-
KiZ = np.dot(self.Ki, Z)
627-
phi = np.dot(Z.T, KiZ)
625+
y = y_array.reshape(-1, 1)
626+
Kiy = np.dot(self.Ki, y)
627+
phi = np.dot(y.T, Kiy)
628628
self.phi = phi[0, 0]
629-
self.KiZ = KiZ
629+
self.Kiy = Kiy
630630

631631
def build(self) -> None:
632632
"""
@@ -638,7 +638,7 @@ def build(self) -> None:
638638
self.K = covar_anisotropic(self.X, d=self.d, g=self.g)
639639
self.Ki = matrix_inversion_dispatcher(self.K, method=self.nlsep_method)
640640
self.ldetK = np.log(det(self.K))
641-
self.calc_ZtKiZ()
641+
self.calc_ytKiy()
642642
# TODO: Check if this is necessary
643643
# if self.dK:
644644
# # TODO: Check if this is necessary
@@ -672,9 +672,9 @@ def predict(self, XX: np.ndarray, lite: bool = False, nonug: bool = False, retur
672672
import matplotlib.pyplot as plt
673673
# Simple sine data
674674
X = np.linspace(0, 2 * np.pi, 7).reshape(-1, 1)
675-
Z = np.sin(X)
675+
y = np.sin(X)
676676
# New GP fit
677-
gpsep = newGPsep(X, Z, d=2, g=0.000001)
677+
gpsep = newGPsep(X, y, d=2, g=0.000001)
678678
# Make predictions
679679
XX = np.linspace(-1, 2 * np.pi + 1, 499).reshape(-1, 1)
680680
p = gpsep.predict(XX, lite=False)
@@ -684,13 +684,13 @@ def predict(self, XX: np.ndarray, lite: bool = False, nonug: bool = False, retur
684684
Sigma = p["Sigma"]
685685
df = p["df"]
686686
# Generate samples from the multivariate t-distribution
687-
ZZ = np.random.multivariate_normal(mean, Sigma, N)
688-
ZZ = ZZ.T
687+
yy = np.random.multivariate_normal(mean, Sigma, N)
688+
yy = yy.T
689689
# Plot the results
690690
plt.figure(figsize=(10, 6))
691691
for i in range(N):
692-
plt.plot(XX, ZZ[:, i], color="gray", linewidth=0.5)
693-
plt.scatter(X, Z, color="black", s=50, zorder=5)
692+
plt.plot(XX, yy[:, i], color="gray", linewidth=0.5)
693+
plt.scatter(X, y, color="black", s=50, zorder=5)
694694
plt.xlabel("x")
695695
plt.ylabel("f-hat(x)")
696696
plt.title("Predictive Distribution")
@@ -760,7 +760,7 @@ def _predict_full(self, XX: np.ndarray, nonug: bool) -> dict:
760760
k = covar_sep(self.m, self.X, n, XX, nn, self.d, 0.0)
761761
Sigma[...] = covar_sep_symm(self.m, XX, nn, self.d, g)
762762
ktKi = np.dot(k.T, self.Ki)
763-
mean[:] = np.dot(ktKi, self.Z).reshape(-1)
763+
mean[:] = np.dot(ktKi, self.y).reshape(-1)
764764
Sigma[...] = phidf * (Sigma - np.dot(ktKi, k))
765765
return {"mean": mean, "Sigma": Sigma, "df": df, "llik": llik}
766766

@@ -837,10 +837,10 @@ def mleGPsep_optimize(self, tmin: np.ndarray, tmax: np.ndarray, ab: np.ndarray,
837837
print(f"bounds: {bounds}")
838838

839839
def objective(par):
840-
return nlsep(par, self.X, self.Z, self.nlsep_method)
840+
return nlsep(par, self.X, self.y, self.nlsep_method)
841841

842842
def gradient(par):
843-
return gradnlsep(par, self.X, self.Z, self.gradnlsep_method)
843+
return gradnlsep(par, self.X, self.y, self.gradnlsep_method)
844844

845845
result = run_minimize_with_restarts(objective=objective, gradient=gradient, x0=p, bounds=bounds, n_restarts_optimizer=self.n_restarts_optimizer, maxit=maxit, verb=verb)
846846

@@ -856,13 +856,13 @@ def gradient(par):
856856
return {"parameters": result.x, "iterations": result.nit, "convergence": result.status, "message": result.message}
857857

858858

859-
def newGPsep(X: np.ndarray, Z: np.ndarray, d=None, g=None, dK: bool = True, optimize: bool = True) -> GPsep:
859+
def newGPsep(X: np.ndarray, y: np.ndarray, d=None, g=None, dK: bool = True, optimize: bool = True) -> GPsep:
860860
"""
861861
Instantiate a new GPsep model with automatic hyperparameter optimization.
862862
863863
Args:
864864
X (np.ndarray): The input data matrix of shape (n, m).
865-
Z (np.ndarray): The output data vector of length n.
865+
y (np.ndarray): The output data vector of length n.
866866
d (optional): The length-scale parameters. If None, will be determined automatically.
867867
g (optional): The nugget parameter. If None, will be determined automatically.
868868
dK (bool): Flag to indicate whether to calculate derivatives.
@@ -872,4 +872,4 @@ def newGPsep(X: np.ndarray, Z: np.ndarray, d=None, g=None, dK: bool = True, opti
872872
GPsep: The newly created and optimized GPsep object.
873873
"""
874874
gpsep = GPsep()
875-
return gpsep.fit(X, Z, d=d, g=g, dK=dK, auto_optimize=optimize)
875+
return gpsep.fit(X, y, d=d, g=g, dK=dK, auto_optimize=optimize)

0 commit comments

Comments
 (0)