Spaces:
Runtime error
Runtime error
Create estimator.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640import numpy as npfrom data import get_prediction_modelfrom sklearn.base import BaseEstimator, clone, MetaEstimatorMixin, _fit_contextfrom sklearn.utils.validation import check_is_fittedfrom sklearn.preprocessing import MinMaxScaler
class MultiFidelityKriging_dev_dev(BaseEstimator, MetaEstimatorMixin): """A template estimator to be used as a reference implementation.
For more information regarding how to build your own estimator, read more in the :ref:`User Guide <user_guide>`.
Parameters ---------- demo_param : str, default='demo_param' A parameter used for demonstration of how to pass and store parameters.
Attributes ---------- is_fitted_ : bool A boolean indicating whether the estimator has been fitted.
n_features_in_ : int Number of features seen during :term:`fit`.
feature_names_in_ : ndarray of shape (`n_features_in_`,) Names of features seen during :term:`fit`. Defined only when `X` has feature names that are all strings.
Examples -------- >>> from skltemplate import TemplateEstimator >>> import numpy as np >>> X = np.arange(100).reshape(100, 1) >>> y = np.zeros((100, )) >>> estimator = TemplateEstimator() >>> estimator.fit(X, y) TemplateEstimator() """
# This is a dictionary allowing to define the type of parameters. # It used to validate parameter within the `_fit_context` decorator. _parameter_constraints = { "demo_param": [str], }
def __init__(self, noise_low=np.nan, noise_high=np.nan, thetasearchinterval = [0.1,15], n_points=20000, n_restarts=100, initial_span=[0.01, 1.0]): self.noise_low=noise_low self.noise_high=noise_high self.thetasearchinterval=thetasearchinterval self.n_points=n_points self.n_restarts=n_restarts self.initial_span=initial_span
def corrmatrix(self, x1, x2, theta): ndim = x1.shape[1]
D = np.zeros((np.shape(x1)[0], np.shape(x2)[0]))
for k in range(ndim): X2, X1 = np.meshgrid(np.squeeze(np.asarray(x2[:, k])), np.squeeze(np.asarray(x1[:, k]))) H = X2 - X1 if ndim == 1: D += - 0.5 * H ** 2 * np.squeeze(np.asarray(theta)) ** -2 else: D += - 0.5 * H ** 2 * np.squeeze(np.asarray(theta))[k] ** -2
C = np.exp(D) return C @_fit_context(prefer_skip_nested_validation=True) def fit(self, X, Y): """A reference implementation of a fitting function.
Parameters ---------- X : {array-like, sparse matrix}, shape (n_samples, n_features) The training input samples.
y : array-like, shape (n_samples,) or (n_samples, n_outputs) The target values (class labels in classification, real numbers in regression).
Returns ------- self : object Returns self. """ # `_validate_data` is defined in the `BaseEstimator` class. # It allows to: # - run different checks on the input data; # - define some attributes associated to the input data: `n_features_in_` and # `feature_names_in_`.
## Make sure the that the high-fidelity features and low-fidelity features are scaled in the same way #temp_scaler = MinMaxScaler((0, 1)) #temp_scaler.fit(X) #X_low = temp_scaler.transform(X_low)
## convert input X_high = np.matrix(X[0]) y_high = np.matrix(Y[0]) X_low = np.matrix(X[1]) y_low = np.matrix(Y[1]) ## get input shapes ## n1 = X_high.shape[0] n2 = X_low.shape[0] ndim = X_high.shape[1]
## normalise data ## domainmin = np.min(X_high, axis=0) domainsize = np.max(X_high, axis=0) - np.min(X_high, axis=0) X_highn = X_high.copy() X_lown = X_low.copy()
## estimate hyperparameters ## print('Low fidelity process:') sigma_low = np.std(y_low)
## fit a Kriging model on the low fidelity data #self.model_low = clone(self.model_low) model_parameters_low = {'fit_kwargs': {'thetasearchinterval': self.thetasearchinterval, 'n_points': self.n_points, 'initial_span':self.initial_span}} model_parameters_low['ey'] = self.noise_low #self.model_low__ey=self.noise_low #self.model_low.fit(X_lown, y_low) self.model_low = get_prediction_model('KrigingModel', model_parameters=model_parameters_low)._construct_model() self.model_low.fit(X_lown, y_low) b2 = self.model_low._model['theta0'] print('Difference process:') d = y_high - self.model_low.predict(X_highn) sigma_diff = np.std(d)
model_parameters_diff = {'fit_kwargs': {'thetasearchinterval': self.thetasearchinterval, 'n_points': self.n_points, 'initial_span':self.initial_span}} model_parameters_diff['ey'] = self.noise_high self.model_diff = get_prediction_model('KrigingModel', model_parameters=model_parameters_diff)._construct_model() self.model_diff.fit(X_highn, d) b1 = self.model_diff._model['theta0'] # Obtain noise from model when noise is learned if np.isnan(float(self.noise_high)): self.noise_high = self.model_diff._model['ey'] * self.model_diff._model['st'] ed = self.noise_high * np.ones(n1) else: ## estimate difference uncertainty ## ed = self.model_low.predict_std(X) ed = np.sqrt(np.square(ed) + self.noise_high ** 2)
if np.isnan(float(self.noise_low)): self.noise_low = self.model_low._model['ey'] * self.model_low._model['st'] ######### ## build matrices ## # z - Kennedy & O'Hagan, page 3 par 2 z = np.concatenate((y_high, y_low), axis=0)
# V - Kennedy & O'Hagan, between (6) and (7) V00 = sigma_diff ** 2 * self.corrmatrix(X_highn, X_highn, b1) + sigma_low ** 2 * self.corrmatrix(X_highn, X_highn, b2) V10 = sigma_low ** 2 * self.corrmatrix(X_lown, X_highn, b2) V01 = sigma_low ** 2 * self.corrmatrix(X_highn, X_lown, b2) V11 = sigma_low ** 2 * self.corrmatrix(X_lown, X_lown, b2) V = np.concatenate((np.concatenate((V00, V01), axis=1), np.concatenate((V10, V11), axis=1)), axis=0)
# H - Kennedy & O'Hagan (4) H00 = np.ones((n1, 1)) H10 = np.zeros((n2, 1)) H01 = np.ones((n1, 1)) H11 = np.ones((n2, 1)) H = np.concatenate((np.concatenate((H00, H01), axis=1), np.concatenate((H10, H11), axis=1)), axis=0)
# R - error covariance matrix # R00 = (ed**2)*np.ones((n1,n1)) R00 = np.zeros((n1, n1)) for k in range(n1): R00[k, k] = ed[k] ** 2 R01 = np.zeros((n1, n2)) R10 = np.zeros((n2, n1)) R11 = (self.noise_low ** 2) * np.eye(n2, n2) R = np.concatenate((np.concatenate((R00, R01), axis=1), np.concatenate((R10, R11), axis=1)), axis=0)
## prior mean ## beta = np.linalg.solve(np.dot(H.T, np.linalg.solve(V + R, H)), np.dot(H.T, np.linalg.solve(V + R, z)))
## output ## self._model = {'X': X_highn, 'y': y_high, 'noise_high': self.noise_high, 'X_low': X_lown, 'y_low': y_low, 'noise_low': self.noise_low, 'ed': ed, 'sigma_diff': sigma_diff, 'b1': b1, 'sigma_low': sigma_low, 'b2': b2, 'domainmin': domainmin, 'domainsize': domainsize, 'beta': beta} #X, y = self._validate_data(X, y, accept_sparse=True) #problem -> y.ravel() required self.is_fitted_ = True # `fit` should always return `self` return self
def predict(self, X, a1=1, a2=1): """A reference implementation of a predicting function.
Parameters ---------- X : {array-like, sparse matrix}, shape (n_samples, n_features) The training input samples.
Returns ------- y : ndarray, shape (n_samples,) Returns an array of ones. """ # Check if fit had been called check_is_fitted(self) # We need to set reset=False because we don't want to overwrite `n_features_in_` # `feature_names_in_` but only check that the shape is consistent.
## get input shapes ## X_highn = self._model['X'] X_lown = self._model['X_low'] n1 = self._model['X'].shape[0] n2 = self._model['X_low'].shape[0] ni = X.shape[0] ndim = self._model['X'].shape[1] y_high = self._model['y'] y_low = self._model['y_low'] sigma_diff = self._model['sigma_diff'] sigma_low = self._model['sigma_low'] ed = self._model['ed'] b1 = self._model['b1'] b2 = self._model['b2'] beta = self._model['beta']
## normalise data ## Xn = X.copy()
# z - Kennedy & O'Hagan, page 3 par 2 z = np.concatenate((y_high, y_low), axis=0)
# V - Kennedy & O'Hagan, between (6) and (7) V00 = sigma_diff ** 2 * self.corrmatrix(X_highn, X_highn, b1) + sigma_low ** 2 * self.corrmatrix(X_highn, X_highn, b2) V10 = sigma_low ** 2 * self.corrmatrix(X_lown, X_highn, b2) V01 = sigma_low ** 2 * self.corrmatrix(X_highn, X_lown, b2) V11 = sigma_low ** 2 * self.corrmatrix(X_lown, X_lown, b2) V = np.concatenate((np.concatenate((V00, V01), axis=1), np.concatenate((V10, V11), axis=1)), axis=0) # t - Kennedy & O'Hagan (6) t0 = a1 * sigma_diff ** 2 * self.corrmatrix(X_highn, Xn, b1) + a2 * sigma_low ** 2 * self.corrmatrix(X_highn, Xn, b2) t1 = a2 * sigma_low ** 2 * self.corrmatrix(X_lown, Xn, b2) t = np.concatenate((t0, t1), axis=0)
# H - Kennedy & O'Hagan (4) H00 = np.ones((n1, 1)) H10 = np.zeros((n2, 1)) H01 = np.ones((n1, 1)) H11 = np.ones((n2, 1)) H = np.concatenate((np.concatenate((H00, H01), axis=1), np.concatenate((H10, H11), axis=1)), axis=0)
# h - Kennedy & O'Hagan (4) h0 = a1 * np.ones((1, ni)) h1 = a2 * np.ones((1, ni)) h = np.concatenate((h0, h1), axis=0)
# R - error covariance matrix # R00 = (ed**2)*np.ones((n1,n1)) R00 = np.zeros((n1, n1)) for k in range(n1): R00[k, k] = ed[k] ** 2 R01 = np.zeros((n1, n2)) R10 = np.zeros((n2, n1)) R11 = (self.noise_low ** 2) * np.eye(n2, n2) R = np.concatenate((np.concatenate((R00, R01), axis=1), np.concatenate((R10, R11), axis=1)), axis=0)
## Posterior mean - Kennedy & O'Hagan (4) ## m = np.dot(h.T, beta) + np.dot(t.T, np.linalg.solve(V + R, z - np.dot(H, beta))) ## output ## X = self._validate_data(X, accept_sparse=True, reset=False) return np.array(m)
class SequentialResidualRegressor(BaseEstimator, MetaEstimatorMixin): def __init__(self, estimators): self.estimators = estimators
def fit(self, X, y=None): #Record the input feature names & how many in total if hasattr(X[0], 'columns'): self.feature_names_in_ = np.array([X_step.columns for X_step in X]).ravel() self.n_features_in_ = sum([X_step.shape[1] for X_step in X])
self.estimators_ = [clone(estimator) for estimator in self.estimators] # #Fit estimators sequentially # #Keep a record of the fit data for each step, for user's reference fit_data = { 'targets': [], 'predictions': [], 'residuals': [] } #Fit first estimator on y, and subsequent estimators on residuals target = y for estimator, X_step in zip(self.estimators_, X): #print(f'[SequentialResidualRegressor] fitting: {estimator.__repr__()}') estimator.fit(X_step, target) #Get residuals in order to compose next target prediction = estimator.predict(X_step) residual = target - prediction #Record data used for fitting at this step, for user's reference for name, data in zip(fit_data.keys(), [target, prediction, residual]): fit_data[name].append(data) #The next target target = residual self.fit_data_ = fit_data return self def predict(self, X): #X = [X for i in self.estimators] preds = [estimator.predict(X_step).reshape(-1, 1) for estimator, X_step in zip(self.estimators_, X)] #Predicted y is the sum over each estimator's prediction y_hat = np.concatenate(preds, axis=1).sum(axis=1) return y_hat def get_feature_names_out(self, features_in=None): return ['predicted_value']
class MultiFidelityKriging_dev(BaseEstimator, MetaEstimatorMixin): """A template estimator to be used as a reference implementation.
For more information regarding how to build your own estimator, read more in the :ref:`User Guide <user_guide>`.
Parameters ---------- demo_param : str, default='demo_param' A parameter used for demonstration of how to pass and store parameters.
Attributes ---------- is_fitted_ : bool A boolean indicating whether the estimator has been fitted.
n_features_in_ : int Number of features seen during :term:`fit`.
feature_names_in_ : ndarray of shape (`n_features_in_`,) Names of features seen during :term:`fit`. Defined only when `X` has feature names that are all strings.
Examples -------- >>> from skltemplate import TemplateEstimator >>> import numpy as np >>> X = np.arange(100).reshape(100, 1) >>> y = np.zeros((100, )) >>> estimator = TemplateEstimator() >>> estimator.fit(X, y) TemplateEstimator() """
# This is a dictionary allowing to define the type of parameters. # It used to validate parameter within the `_fit_context` decorator. _parameter_constraints = { "demo_param": [str], }
def __init__(self, noise_low=np.nan, noise_high=np.nan, thetasearchinterval = [0.1,10], n_points=10000, n_restarts=50, initial_span=[0.01, 1.0]): self.noise_low=noise_low self.noise_high=noise_high self.thetasearchinterval=thetasearchinterval self.n_points=n_points self.n_restarts=n_restarts self.initial_span=initial_span
def corrmatrix(self, x1, x2, theta): ndim = x1.shape[1]
D = np.zeros((np.shape(x1)[0], np.shape(x2)[0]))
for k in range(ndim): X2, X1 = np.meshgrid(np.squeeze(np.asarray(x2[:, k])), np.squeeze(np.asarray(x1[:, k]))) H = X2 - X1 if ndim == 1: D += - 0.5 * H ** 2 * np.squeeze(np.asarray(theta)) ** -2 else: D += - 0.5 * H ** 2 * np.squeeze(np.asarray(theta))[k] ** -2
C = np.exp(D) return C
def _validate_data(self, X, accept_sparse=False, reset=True, **kwargs): return np.asarray(X)
@_fit_context(prefer_skip_nested_validation=True) def fit(self, X, y, X_low=None, y_low=None): """A reference implementation of a fitting function.
Parameters ---------- X : {array-like, sparse matrix}, shape (n_samples, n_features) The training input samples.
y : array-like, shape (n_samples,) or (n_samples, n_outputs) The target values (class labels in classification, real numbers in regression).
Returns ------- self : object Returns self. """ # `_validate_data` is defined in the `BaseEstimator` class. # It allows to: # - run different checks on the input data; # - define some attributes associated to the input data: `n_features_in_` and # `feature_names_in_`.
## Make sure the that the high-fidelity features and low-fidelity features are scaled in the same way temp_scaler = MinMaxScaler((0, 1)) temp_scaler.fit(X) X_low = temp_scaler.transform(X_low) #print(temp_scaler.data_min_) ## convert input X_high = np.matrix(X) y_high = np.matrix(y) X_low = np.matrix(X_low) y_low = np.matrix(y_low) ## get input shapes ## n1 = X_high.shape[0] n2 = X_low.shape[0] ndim = X_high.shape[1]
## normalise data ## domainmin = np.min(X_high, axis=0) domainsize = np.max(X_high, axis=0) - np.min(X_high, axis=0) X_highn = X_high.copy() X_lown = X_low.copy()
## estimate hyperparameters ## print('Low fidelity process:') sigma_low = np.std(y_low)
## fit a Kriging model on the low fidelity data #self.model_low = clone(self.model_low) model_parameters_low = {'fit_kwargs': {'thetasearchinterval': self.thetasearchinterval, 'n_points': self.n_points, 'initial_span':self.initial_span}} model_parameters_low['ey'] = self.noise_low #self.model_low__ey=self.noise_low #self.model_low.fit(X_lown, y_low) self.model_low = get_prediction_model('KrigingModel', model_parameters=model_parameters_low)._construct_model() self.model_low.fit(X_lown, y_low) b2 = self.model_low._model['theta0'] print('Difference process:') d = y_high - self.model_low.predict(X_highn) sigma_diff = np.std(d)
model_parameters_diff = {'fit_kwargs': {'thetasearchinterval': self.thetasearchinterval, 'n_points': self.n_points, 'initial_span':self.initial_span}} model_parameters_diff['ey'] = self.noise_high self.model_diff = get_prediction_model('KrigingModel', model_parameters=model_parameters_diff)._construct_model() self.model_diff.fit(X_highn, d) b1 = self.model_diff._model['theta0'] # Obtain noise from model when noise is learned if np.isnan(float(self.noise_high)): self.noise_high = self.model_diff._model['ey'] * self.model_diff._model['st'] ed = self.noise_high * np.ones(n1) else: ## estimate difference uncertainty ## ed = self.model_low.predict_std(X) ed = np.sqrt(np.square(ed) + self.noise_high ** 2)
if np.isnan(float(self.noise_low)): self.noise_low = self.model_low._model['ey'] * self.model_low._model['st'] ######### ## build matrices ## # z - Kennedy & O'Hagan, page 3 par 2 z = np.concatenate((y_high, y_low), axis=0)
# V - Kennedy & O'Hagan, between (6) and (7) V00 = sigma_diff ** 2 * self.corrmatrix(X_highn, X_highn, b1) + sigma_low ** 2 * self.corrmatrix(X_highn, X_highn, b2) V10 = sigma_low ** 2 * self.corrmatrix(X_lown, X_highn, b2) V01 = sigma_low ** 2 * self.corrmatrix(X_highn, X_lown, b2) V11 = sigma_low ** 2 * self.corrmatrix(X_lown, X_lown, b2) V = np.concatenate((np.concatenate((V00, V01), axis=1), np.concatenate((V10, V11), axis=1)), axis=0)
# H - Kennedy & O'Hagan (4) H00 = np.ones((n1, 1)) H10 = np.zeros((n2, 1)) H01 = np.ones((n1, 1)) H11 = np.ones((n2, 1)) H = np.concatenate((np.concatenate((H00, H01), axis=1), np.concatenate((H10, H11), axis=1)), axis=0)
# R - error covariance matrix # R00 = (ed**2)*np.ones((n1,n1)) R00 = np.zeros((n1, n1)) for k in range(n1): R00[k, k] = ed[k] ** 2 R01 = np.zeros((n1, n2)) R10 = np.zeros((n2, n1)) R11 = (self.noise_low ** 2) * np.eye(n2, n2) R = np.concatenate((np.concatenate((R00, R01), axis=1), np.concatenate((R10, R11), axis=1)), axis=0)
## prior mean ## beta = np.linalg.solve(np.dot(H.T, np.linalg.solve(V + R, H)), np.dot(H.T, np.linalg.solve(V + R, z)))
## output ## self._model = {'X': X_highn, 'y': y_high, 'noise_high': self.noise_high, 'X_low': X_lown, 'y_low': y_low, 'noise_low': self.noise_low, 'ed': ed, 'sigma_diff': sigma_diff, 'b1': b1, 'sigma_low': sigma_low, 'b2': b2, 'domainmin': domainmin, 'domainsize': domainsize, 'beta': beta} #X, y = self._validate_data(X, y, accept_sparse=True) #problem -> y.ravel() required self.is_fitted_ = True # `fit` should always return `self` return self
def predict(self, X, a1=1, a2=1): """A reference implementation of a predicting function.
Parameters ---------- X : {array-like, sparse matrix}, shape (n_samples, n_features) The training input samples.
Returns ------- y : ndarray, shape (n_samples,) Returns an array of ones. """ # Check if fit had been called check_is_fitted(self) # We need to set reset=False because we don't want to overwrite `n_features_in_` # `feature_names_in_` but only check that the shape is consistent.
## get input shapes ## X_highn = self._model['X'] X_lown = self._model['X_low'] n1 = self._model['X'].shape[0] n2 = self._model['X_low'].shape[0] ni = X.shape[0] ndim = self._model['X'].shape[1] y_high = self._model['y'] y_low = self._model['y_low'] sigma_diff = self._model['sigma_diff'] sigma_low = self._model['sigma_low'] ed = self._model['ed'] b1 = self._model['b1'] b2 = self._model['b2'] beta = self._model['beta']
## normalise data ## Xn = X.copy()
# z - Kennedy & O'Hagan, page 3 par 2 z = np.concatenate((y_high, y_low), axis=0)
# V - Kennedy & O'Hagan, between (6) and (7) V00 = sigma_diff ** 2 * self.corrmatrix(X_highn, X_highn, b1) + sigma_low ** 2 * self.corrmatrix(X_highn, X_highn, b2) V10 = sigma_low ** 2 * self.corrmatrix(X_lown, X_highn, b2) V01 = sigma_low ** 2 * self.corrmatrix(X_highn, X_lown, b2) V11 = sigma_low ** 2 * self.corrmatrix(X_lown, X_lown, b2) V = np.concatenate((np.concatenate((V00, V01), axis=1), np.concatenate((V10, V11), axis=1)), axis=0) # t - Kennedy & O'Hagan (6) t0 = a1 * sigma_diff ** 2 * self.corrmatrix(X_highn, Xn, b1) + a2 * sigma_low ** 2 * self.corrmatrix(X_highn, Xn, b2) t1 = a2 * sigma_low ** 2 * self.corrmatrix(X_lown, Xn, b2) t = np.concatenate((t0, t1), axis=0)
# H - Kennedy & O'Hagan (4) H00 = np.ones((n1, 1)) H10 = np.zeros((n2, 1)) H01 = np.ones((n1, 1)) H11 = np.ones((n2, 1)) H = np.concatenate((np.concatenate((H00, H01), axis=1), np.concatenate((H10, H11), axis=1)), axis=0)
# h - Kennedy & O'Hagan (4) h0 = a1 * np.ones((1, ni)) h1 = a2 * np.ones((1, ni)) h = np.concatenate((h0, h1), axis=0)
# R - error covariance matrix # R00 = (ed**2)*np.ones((n1,n1)) R00 = np.zeros((n1, n1)) for k in range(n1): R00[k, k] = ed[k] ** 2 R01 = np.zeros((n1, n2)) R10 = np.zeros((n2, n1)) R11 = (self.noise_low ** 2) * np.eye(n2, n2) R = np.concatenate((np.concatenate((R00, R01), axis=1), np.concatenate((R10, R11), axis=1)), axis=0)
## Posterior mean - Kennedy & O'Hagan (4) ## m = np.dot(h.T, beta) + np.dot(t.T, np.linalg.solve(V + R, z - np.dot(H, beta))) ## output ## X = self._validate_data(X, accept_sparse=True, reset=False) return np.array(m)estimator.pyAdded+640