amorf package

Submodules

amorf.datasets module

class amorf.datasets.EDM[source]

Bases: object

get_numpy()[source]

Retrieve X and Y as Numpy Array

Returns tuple with two arrays, X and y

Args:

Returns:Numpy Array X (n,16) and y (n,2) of type np.float32
Return type:(np.ndarray, np.ndarray)
class amorf.datasets.RiverFlow1[source]

Bases: object

get_numpy()[source]

Retrieve X and Y as Numpy Array

Returns tuple with two arrays, X and y Replaces NaN values with 0

Args:

Returns:Numpy Array X (n,64) and y (n,8) of type np.float32
Return type:(np.ndarray, np.ndarray)
class amorf.datasets.TransparentConductors[source]

Bases: object

get_numpy()[source]

Retrieve X and Y as Numpy Array

Returns tuple with two arrays, X and y

Args:

Returns:Numpy Arraya X (n,12) and y (n,2) of type np.float32
Return type:(np.ndarray, np.ndarray)
class amorf.datasets.WaterQuality[source]

Bases: object

get_numpy()[source]

Retrieve X and Y as Numpy Array

Returns tuple with two arrays, X and y

Args:

Returns:Numpy Array X (n,16) and y (n,14) of type np.float32
Return type:(np.ndarray, np.ndarray)

amorf.metrics module

amorf.metrics.average_correlation_coefficient(y_pred, y_true)[source]

Calculate Average Correlation Coefficient

Parameters:
  • y_true (array-like) – np.ndarray or torch.Tensor of dimension N x d with actual values
  • y_pred (array-like) – np.ndarray or torch.Tensor of dimension N x d with predicted values
Returns:

Average Relative Mean Squared Error

Return type:

float

Raises:

ValueError – If Parameters are not both of type np.ndarray or torch.Tensor

amorf.metrics.average_relative_error(y_pred, y_true)[source]

Calculate Average Relative Error

Parameters:
  • y_true (array-like) – np.ndarray or torch.Tensor of dimension N x d with actual values
  • y_pred (array-like) – np.ndarray or torch.Tensor of dimension N x d with predicted values
Returns:

Average Relative Mean Squared Error

Return type:

float

Raises:

ValueError – If Parameters are not both of type np.ndarray or torch.Tensor

amorf.metrics.average_relative_root_mean_squared_error(y_pred, y_true)[source]

Calculate Average Relative Root Mean Squared Error (aRRMSE)

Parameters:
  • y_true (array-like) – np.ndarray or torch.Tensor of dimension N x d with actual values
  • y_pred (array-like) – np.ndarray or torch.Tensor of dimension N x d with predicted values
Returns:

Average Relative Root Mean Squared Error

Return type:

float

Raises:

ValueError – If Parameters are not both of type np.ndarray or torch.Tensor

amorf.metrics.average_root_mean_squared_error(y_pred, y_true)[source]

Calculate Average Root Mean Squared Error (aRMSE)

Parameters:
  • y_true (array-like) – np.ndarray or torch.Tensor of dimension N x d with actual values
  • y_pred (array-like) – np.ndarray or torch.Tensor of dimension N x d with predicted values
Returns:

Average Root Mean Squared Error

Return type:

float

Raises:

ValueError – If Parameters are not both of type np.ndarray or torch.Tensor

amorf.metrics.mean_squared_error(y_pred, y_true)[source]

Calculate Mean Squared Error (MSE)

Parameters:
  • y_true (array-like) – np.ndarray or torch.Tensor of dimension N x d with actual values
  • y_pred (array-like) – np.ndarray or torch.Tensor of dimension N x d with predicted values
Returns:

Mean Squared Error

Return type:

float

Raises:

ValueError – If Parameters are not both of type np.ndarray or torch.Tensor

amorf.multiOutputSVR module

class amorf.multiOutputSVR.MLSSVR(kernel_param1, kernel_param2, kernel_selector='linear')[source]

Bases: object

Multi-Output Least Squares Support Vector Regression

MLSSVR implementation based on this matlab implementation:https://github.com/pzczxs/MLSSVR

Original Paper: Shuo Xu, Xin An, Xiaodong Qiao, Lijun Zhu, and Lin Li, 2013. Multi-Output Least-Squares Support Vector Regression Machines. Pattern Recognition Letters, Vol. 34, No. 9, pp. 1078-1084.

Raises:
Parameters:
  • kernel_param1 (float) – first Parameter for kernel function
  • kernel_param1 – seconde Parameter for kernel function
  • kernel_selector (string,optional) – One of ‘linear’,’poly’,’rbf’,’erbf’,’sigmoid’. Default:’linear’
fit(X_train, y_train, gamma, lambd)[source]

Fits the model to the training data set

Parameters:
  • X_train (nd.array) – Set of descriptive Variables
  • y_train (nd.array) – Set of target Variables
  • gamma (float) – gamma parameter
  • lambd (float) – lambda parameter
Raises:

ValueError – if length of X_train and y_train don’t match

Returns:

fitted MLSSVR

Return type:

MLSSVR

predict(X_test, X_train)[source]

Predicts the target variables for the given test set

Parameters:
  • X_test (np.ndarray) – Test set withdescriptive variables
  • X_train (np.ndarray) – Train set with descriptive variables
Returns:

Predicted target variables

Return type:

np.ndarray

score(X_test, X_train, y_test)[source]

Returns Average Relative Root Mean Squared Error for given test data and targets

Parameters:
  • X_test (np.ndarray) – Test samples
  • y_test (np.ndarray) – True targets

amorf.neuralNetRegression module

class amorf.neuralNetRegression.AbstractNeuralNet[source]

Bases: abc.ABC

convert_test_set_to_tensor(X_test, device)[source]
convert_train_set_to_tensor(X_train, y_train, device)[source]
class amorf.neuralNetRegression.Convolutional_NN_Model(input_dim, output_dim, p_dropout=0.5)[source]

Bases: torch.nn.modules.module.Module

convert_test_set_to_tensor(X_test, device)[source]
convert_train_set_to_tensor(X_train, y_train, device)[source]
forward(x)[source]

Defines the computation performed at every call.

Should be overridden by all subclasses.

Note

Although the recipe for forward pass needs to be defined within this function, one should call the Module instance afterwards instead of this since the former takes care of running the registered hooks while the latter silently ignores them.

class amorf.neuralNetRegression.Linear_NN_Model(input_dim, output_dim, selector='max', p_dropout_1=0.5, p_dropout_2=0.5)[source]

Bases: torch.nn.modules.module.Module

convert_test_set_to_tensor(X_test, device)[source]
convert_train_set_to_tensor(X_train, y_train, device)[source]
forward(x)[source]

Defines the computation performed at every call.

Should be overridden by all subclasses.

Note

Although the recipe for forward pass needs to be defined within this function, one should call the Module instance afterwards instead of this since the former takes care of running the registered hooks while the latter silently ignores them.

class amorf.neuralNetRegression.NeuralNetRegressor(model=None, batch_size=None, shuffle=False, learning_rate=0.01, use_gpu=False, patience=None, training_limit=1000, verbosity=1, print_after_epochs=100)[source]

Bases: object

Regressor that uses PyTorch models to predict multiple targets

Raises:

ValueError – If given model ist not instance of pytorch.NN.nodule

Parameters:
  • model (pytorch.NN.Module,optional) – PyTorch Model to use. Default: None (will use Linear_NN_Model)
  • batch_size (int,optional) – Otherwise training set is split into batches of given size. Default: None
  • shuffle (bool,optional) – Set to True to have the data reshuffled at every epoch. Default: False
  • learning_rate (float,optional) – learning rate for optimizer. Default: 0.01
  • use_gpu (bool,optional) – Flag that allows usage of cuda cores for calculations. Default: False
  • patience (int,optional) – Stop training after p continous incrementations (stops at training limit if it is not none). Default: 0
  • training_limit (int,optional) – After specified number of epochs training will be terminated, regardless of EarlyStopping stopping. Default: 100
  • verbosity (int,optional) – 0 to only print errors, 1 (default) to print status information. Default: 1
  • print_after_epochs (int,optional) – Specifies after how many epochs training and validation error will be printed to command line. Default: 10
fit(X_train, y_train)[source]

Fits the model to the training data set

Parameters:
  • X_train (nd.array) – Set of descriptive Variables
  • y_train (nd.array) – Set of target Variables
Returns:

fitted NeuralNetRegressor

Return type:

NeuralNetRegressor

get_params(deep=True)[source]

Get parameters for this estimator. :param deep: If True, will return the parameters for this estimator and

contained subobjects that are estimators.
Returns:params – Parameter names mapped to their values.
Return type:mapping of string to any
load(load_path)[source]

Load model from path

Parameters:load_path (string) – Path to saved model
predict(X_test)[source]

Predicts the target variables for the given test set

Parameters:X_test (np.ndarray) – Test set with descriptive variables
Returns:Predicted target variables
Return type:np.ndarray
save(store_path)[source]

Save model and store it at given path

Parameters:store_path (string) – Path to store model at
score(X_test, y_test)[source]

Returns Average Relative Root Mean Squared Error for given test data and targets

Parameters:
  • X_test (np.ndarray) – Test samples
  • y_test (np.ndarray) – True targets
set_params(**params)[source]

Set the parameters of this estimator. The method works on simple estimators as well as on nested objects (such as pipelines). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object. :returns: :rtype: self

amorf.probabalisticRegression module

class amorf.probabalisticRegression.BayesianNeuralNetworkRegression(batch_size=None, shuffle=False, learning_rate=0.001, use_gpu=False, patience=None, training_limit=100, verbosity=1, print_after_epochs=500)[source]

Bases: object

Bayesian Neural Network that uses a Pyro model to predict multiple targets

Uses Pyros Elbo Loss internally :param batch_size: Otherwise training set is split into batches of given size. Default: None :type batch_size: int,optional :param shuffle: Set to True to have the data reshuffled at every epoch. Default: False :type shuffle: bool,optional :param learning_rate: Learning rate for optimizer. Default: 1e-3 :type learning_rate: float,optional :param use_gpu: Flag that allows usage of cuda cores for calculations. Default: False :type use_gpu: bool,optional :param patience: Stop training after p continous incrementations. Default: None :type patience: int,optional :param training_limit: After specified number of epochs training will be terminated, regardless of early stopping. Default: 100 :type training_limit: int,optional :param verbosity: 0 to only print errors, 1 (default) to print status information. Default: 1 :type verbosity: int,optional :param print_after_epochs: Specifies after how many epochs training and validation loss will be printed to command line. Default: 500 :type print_after_epochs: int,optional

fit(X_train, y_train)[source]

Fits the model to the training data set

Parameters:
  • X_train (nd.array) – Set of descriptive Variables
  • y_train (nd.array) – Set of target Variables
Returns:

fitted NeuralNetRegressor

Return type:

NeuralNetRegressor

get_params(deep=True)[source]

Get parameters for this estimator. :param deep: If True, will return the parameters for this estimator and

contained subobjects that are estimators.
Returns:params – Parameter names mapped to their values.
Return type:mapping of string to any
load(path)[source]

Load model from path

Parameters:load_path (string) – Path to saved model
model(x_data, y_data)[source]
predict(X_test, num_samples=100)[source]

Predicts the target variables for the given test set :param X_test: Test set withdescriptive variables :type X_test: np.ndarray

Returns:Predicted target variables
Return type:np.ndarray
save(path)[source]

Save model and store it at given path

Parameters:store_path (string) – Path to store model at
score(X_test, y_test)[source]

Returns Average Relative Root Mean Squared Error for given test data and targets

Parameters:
  • X_test (np.ndarray) – Test samples
  • y_test (np.ndarray) – True targets
set_params(**params)[source]

Set the parameters of this estimator. The method works on simple estimators as well as on nested objects (such as pipelines). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object. :returns: :rtype: self

class amorf.probabalisticRegression.GaussianProcessAutoregressiveRegression[source]

Bases: object

[summary]

fit(X_train, y_train)[source]
predict(X_test)[source]
class amorf.probabalisticRegression.GaussianProcessRegression(kernel=None, alpha=1e-10, optimizer='fmin_l_bfgs_b', n_restarts_optimizer=0, normalize_y=False, copy_X_train=True, random_state=None)[source]

Bases: object

Wrapper around sklearns GaussianProcessRegressor (sklearn.gaussian_process.GaussienProcessRegressor) (from sklearn Documentation https://github.com/scikit-learn/scikit-learn/blob/1495f6924/sklearn/gaussian_process/gpr.py)

The implementation is based on Algorithm 2.1 of Gaussian Processes for Machine Learning (GPML) by Rasmussen and Williams. In addition to standard scikit-learn estimator API, GaussianProcessRegressor:

  • allows prediction without prior fitting (based on the GP prior)
  • provides an additional method sample_y(X), which evaluates samples drawn from the GPR (prior or posterior) at given inputs
  • exposes a method log_marginal_likelihood(theta), which can be used externally for other ways of selecting hyperparameters, e.g., via Markov chain Monte Carlo.

Args: kernel : kernel object

The kernel specifying the covariance function of the GP. If None is passed, the kernel “1.0 * RBF(1.0)” is used as default. Note that the kernel’s hyperparameters are optimized during fitting.
alpha : float or array-like, optional (default: 1e-10)
Value added to the diagonal of the kernel matrix during fitting. Larger values correspond to increased noise level in the observations. This can also prevent a potential numerical issue during fitting, by ensuring that the calculated values form a positive definite matrix. If an array is passed, it must have the same number of entries as the data used for fitting and is used as datapoint-dependent noise level. Note that this is equivalent to adding a WhiteKernel with c=alpha. Allowing to specify the noise level directly as a parameter is mainly for convenience and for consistency with Ridge.
optimizer : string or callable, optional (default: “fmin_l_bfgs_b”)

Can either be one of the internally supported optimizers for optimizing the kernel’s parameters, specified by a string, or an externally defined optimizer passed as a callable. If a callable is passed, it must have the signature:

def optimizer(obj_func, initial_theta, bounds):
    # * 'obj_func' is the objective function to be minimized, which
    #   takes the hyperparameters theta as parameter and an
    #   optional flag eval_gradient, which determines if the
    #   gradient is returned additionally to the function value
    # * 'initial_theta': the initial value for theta, which can be
    #   used by local optimizers
    # * 'bounds': the bounds on the values of theta
    ....
    # Returned are the best found hyperparameters theta and
    # the corresponding value of the target function.
    return theta_opt, func_min

Per default, the ‘fmin_l_bfgs_b’ algorithm from scipy.optimize is used. If None is passed, the kernel’s parameters are kept fixed. Available internal optimizers are:

'fmin_l_bfgs_b'
n_restarts_optimizer : int, optional (default: 0)
The number of restarts of the optimizer for finding the kernel’s parameters which maximize the log-marginal likelihood. The first run of the optimizer is performed from the kernel’s initial parameters, the remaining ones (if any) from thetas sampled log-uniform randomly from the space of allowed theta-values. If greater than 0, all bounds must be finite. Note that n_restarts_optimizer == 0 implies that one run is performed.
normalize_y : boolean, optional (default: False)
Whether the target values y are normalized, i.e., the mean of the observed target values become zero. This parameter should be set to True if the target values’ mean is expected to differ considerable from zero. When enabled, the normalization effectively modifies the GP’s prior based on the data, which contradicts the likelihood principle; normalization is thus disabled per default.
copy_X_train : bool, optional (default: True)
If True, a persistent copy of the training data is stored in the object. Otherwise, just a reference to the training data is stored, which might cause predictions to change if the data is modified externally.
random_state : int, RandomState instance or None, optional (default: None)
The generator used to initialize the centers. If int, random_state is the seed used by the random number generator; If RandomState instance, random_state is the random number generator; If None, the random number generator is the RandomState instance used by np.random.
fit(X_train, y_train)[source]

Fit Gaussian process regression model. (from sklearn Documentation https://github.com/scikit-learn/scikit-learn/blob/1495f6924/sklearn/gaussian_process/gpr.py) :param X: :type X: array-like) shape = (n_samples, n_features :param Training data: :param y: :type y: array-like) shape = (n_samples, [n_output_dims] :param Target values:

Returns:self
Return type:returns an instance of self.
predict(X_test, return_std=False, return_cov=False)[source]

Predict using the Gaussian process regression model (from sklearn Documentation https://github.com/scikit-learn/scikit-learn/blob/1495f6924/sklearn/gaussian_process/gpr.py)

We can also predict based on an unfitted model by using the GP prior. In addition to the mean of the predictive distribution, also its standard deviation (return_std=True) or covariance (return_cov=True). Note that at most one of the two can be requested. Args: X : array-like, shape = (n_samples, n_features)

Query points where the GP is evaluated
return_std : bool, default: False
If True, the standard-deviation of the predictive distribution at the query points is returned along with the mean.
return_cov : bool, default: False
If True, the covariance of the joint predictive distribution at the query points is returned along with the mean

Returns: y_mean (array): shape = (n_samples, [n_output_dims])

Mean of predictive distribution a query points
y_std (array): shape = (n_samples,), optional
Standard deviation of predictive distribution at query points. Only returned when return_std is True.
y_cov (array): shape = (n_samples, n_samples), optional
Covariance of joint predictive distribution a query points. Only returned when return_cov is True.
class amorf.probabalisticRegression.NN(input_size=None, output_size=None)[source]

Bases: torch.nn.modules.module.Module

forward(x)[source]

Defines the computation performed at every call.

Should be overridden by all subclasses.

Note

Although the recipe for forward pass needs to be defined within this function, one should call the Module instance afterwards instead of this since the former takes care of running the registered hooks while the latter silently ignores them.

amorf.problemTransformation module

class amorf.problemTransformation.AutoEncoderRegression(regressor='gradientboost', custom_regressor=None, batch_size=None, shuffle=False, learning_rate=0.001, use_gpu=False, patience=None, training_limit=100, verbosity=1, print_after_epochs=500)[source]

Bases: object

Regressor that uses an Autoencoder to reduce dimensionality of target variables

Raises:
  • Warning – If Custom Regressor is not valid, default estimator will be used instead
  • ValueError – If selector is not a valid value
Parameters:
  • regressor (string,optional) – Can be one of the following linear’, ‘kneighbors’, ‘adaboost’, ‘gradientboost’, ‘mlp’, ‘svr’, ‘xgb’. Default: ‘gradientboost’
  • custom_regressor (object,optional) – Custom Estimator that must implement ‘fit()’ and ‘predict()’ function. Default: None
  • batch_size (int,optional) – Otherwise training set is split into batches of given size. Default: None
  • shuffle (bool,optional) – False
  • learning_rate (float,optional) – Learning rate for optimizer. Default: 1e-3
  • use_gpu (bool,optional) – Flag that allows usage of cuda cores for calculations. Default: False
  • patience (int,optional) – Stop training after p continous incrementations. Default: None
  • training_limit (int,optional) – After specified number of epochs training will be terminated, regardless of EarlyStopping stopping. Default: 100
  • verbosity (int,optional) – 0 to only print errors, 1 (default) to print status information. Default: 1
  • print_after_epochs (int,optional) – Specifies after how many epochs training and validation loss will be printed to command line. Default: 500
fit(X_train, y_train)[source]

Fits the model to the training data set

Trains an AutoEncoder to encode multidimensional target variables into scalar. The resulting data set is used to train the given regressor to predict these scalars.

Parameters:
  • X_train (nd.array) – Set of descriptive Variables
  • y_train (nd.array) – Set of target Variables
Returns:

fitted AutoEncoderRegressor

Return type:

AutoEncoderRegressor

predict(X_test)[source]

Predicts the encoded target variables and decodes them for the given test set

Parameters:X_test (np.ndarray) – Test set with descriptive variables
Returns:Predicted target variables
Return type:np.ndarray
score(X_test, y_test)[source]

Returns Average Relative Root Mean Squared Error for given test data and targets

Parameters:
  • X_test (np.ndarray) – Test samples
  • y_test (np.ndarray) – True targets
class amorf.problemTransformation.SingleTargetMethod(selector='gradientboost', custom_regressor=None)[source]

Bases: object

Performs regression for each target variable separately.

This method is a wrapper around scikit learns MultiOutputRegressor class. It has some estimators readily provided and allows for custom estimators to be used.
Parameters:
  • selector (string) – Can be one of the following linear’, ‘kneighbors’, ‘adaboost’, ‘gradientboost’, ‘mlp’, ‘svr’, ‘xgb’
  • custom_regressor (object) – Custom Estimator that must implement ‘fit()’ and ‘predict()’ function.
Raises:
  • Warning – If Custom Regressor is not valid, default estimator will be used instead
  • ValueError – If selector is not a valid value
fit(X_train, y_train)[source]

Fits the estimator to the training data

Parameters:
  • X_train (np.ndarray) – Training set descriptive variables
  • y_train (np.ndarray) – Training set target variables
Returns:

Trained estimator

Return type:

[sklearn.MultiOutputRegressor]

predict(X_test)[source]

Predicts the target variables for a given set of descriptive variables

Parameters:X_test (np.ndarray) – Array with descriptive variables
Returns:Array with predicted target variables
Return type:np.ndarray
class amorf.problemTransformation.autoencoder(n_targets)[source]

Bases: torch.nn.modules.module.Module

forward(x)[source]

Defines the computation performed at every call.

Should be overridden by all subclasses.

Note

Although the recipe for forward pass needs to be defined within this function, one should call the Module instance afterwards instead of this since the former takes care of running the registered hooks while the latter silently ignores them.

amorf.utils module

class amorf.utils.EarlyStopping(patience)[source]

Bases: object

Early Stopping Mechanism

Returns True if training should stop and False if it should continue. Saves the best model. Only works for decreasing loss values.

Parameters:patience (int) – Stop after p continous incrementations.
lastLoss

Loss-value of previous call of the ‘stop’-function

Type:float
patience

Stop after how many continous incrementations

Type:int
suceedingsHigherValues

Number of continous incrementations of loss

Type:int
stop(newLoss, model)[source]

Decides whether training should be stopped

Decides whether training should be stopped. Every time the erorr decreases the model is saved.

Parameters:newLoss (float) – Training or validation Loss.
Returns:Return true if number of values higher than the previous one equals patience.
Return type:bool
amorf.utils.printMessage(Message, verbosity)[source]

Prints messages if verbosity is set

Does not do much currently but can be expanded later.

Module contents