Exemple #1
0
    def __init__(self, f, df, x0, names=None, *args, **kwargs):
        """
        :param f: Function to check gradient for
        :param df: Gradient of function to check
        :param x0:
            Initial guess for inputs x (if it has a shape (a,b) this will be reflected in the parameter names).
            Can be a list of arrays, if f takes a list of arrays. This list will be passed
            to f and df in the same order as given here.
            If f takes only one argument, make sure not to pass a list for x0!!!
        :type x0: [array-like] | array-like | float | int
        :param list names:
            Names to print, when performing gradcheck. If a list was passed to x0
            a list of names with the same length is expected.
        :param args kwargs: Arguments passed as f(x, *args, **kwargs) and df(x, *args, **kwargs)

        Examples:
        ---------
        from GPy.models import GradientChecker
        N, M, Q = 10, 5, 3

        Sinusoid:

            X = numpy.random.rand(N, Q)
            grad = GradientChecker(numpy.sin,numpy.cos,X,'sin_in')
            grad.checkgrad(verbose=1)

        Using GPy:

            X, Z = numpy.random.randn(N,Q), numpy.random.randn(M,Q)
            kern = GPy.kern.linear(Q, ARD=True) + GPy.kern.rbf(Q, ARD=True)
            grad = GradientChecker(kern.K,
                                   lambda x: kern.dK_dX(numpy.ones((1,1)), x),
                                   x0 = X.copy(),
                                   names=['X_input'])
            grad.checkgrad(verbose=1)
            grad.randomize()
            grad.checkgrad(verbose=1)
        """
        Model.__init__(self)
        if isinstance(x0, (list, tuple)) and names is None:
            self.shapes = [get_shape(xi) for xi in x0]
            self.names = ['X{i}'.format(i=i) for i in range(len(x0))]
        elif isinstance(x0, (list, tuple)) and names is not None:
            self.shapes = [get_shape(xi) for xi in x0]
            self.names = names
        elif names is None:
            self.names = ['X']
            self.shapes = [get_shape(x0)]
        else:
            self.names = names
            self.shapes = [get_shape(x0)]
        for name, xi in zip(self.names, at_least_one_element(x0)):
            self.__setattr__(name, numpy.float_(xi))
#         self._param_names = []
#         for name, shape in zip(self.names, self.shapes):
#             self._param_names.extend(map(lambda nameshape: ('_'.join(nameshape)).strip('_'), itertools.izip(itertools.repeat(name), itertools.imap(lambda t: '_'.join(map(str, t)), itertools.product(*map(lambda xi: range(xi), shape))))))
        self.args = args
        self.kwargs = kwargs
        self._f = f
        self._df = df
Exemple #2
0
    def __init__(self, f, df, x0, names=None, *args, **kwargs):
        """
        :param f: Function to check gradient for
        :param df: Gradient of function to check
        :param x0:
            Initial guess for inputs x (if it has a shape (a,b) this will be reflected in the parameter names).
            Can be a list of arrays, if f takes a list of arrays. This list will be passed
            to f and df in the same order as given here.
            If f takes only one argument, make sure not to pass a list for x0!!!
        :type x0: [array-like] | array-like | float | int
        :param list names:
            Names to print, when performing gradcheck. If a list was passed to x0
            a list of names with the same length is expected.
        :param args kwargs: Arguments passed as f(x, *args, **kwargs) and df(x, *args, **kwargs)

        Examples:
        ---------
        from GPy.models import GradientChecker
        N, M, Q = 10, 5, 3

        Sinusoid:

            X = numpy.random.rand(N, Q)
            grad = GradientChecker(numpy.sin,numpy.cos,X,'sin_in')
            grad.checkgrad(verbose=1)

        Using GPy:

            X, Z = numpy.random.randn(N,Q), numpy.random.randn(M,Q)
            kern = GPy.kern.linear(Q, ARD=True) + GPy.kern.rbf(Q, ARD=True)
            grad = GradientChecker(kern.K,
                                   lambda x: kern.dK_dX(numpy.ones((1,1)), x),
                                   x0 = X.copy(),
                                   names=['X_input'])
            grad.checkgrad(verbose=1)
            grad.randomize()
            grad.checkgrad(verbose=1)
        """
        Model.__init__(self)
        if isinstance(x0, (list, tuple)) and names is None:
            self.shapes = [get_shape(xi) for xi in x0]
            self.names = ['X{i}'.format(i=i) for i in range(len(x0))]
        elif isinstance(x0, (list, tuple)) and names is not None:
            self.shapes = [get_shape(xi) for xi in x0]
            self.names = names
        elif names is None:
            self.names = ['X']
            self.shapes = [get_shape(x0)]
        else:
            self.names = names
            self.shapes = [get_shape(x0)]
        for name, xi in zip(self.names, at_least_one_element(x0)):
            self.__setattr__(name, numpy.float_(xi))
#         self._param_names = []
#         for name, shape in zip(self.names, self.shapes):
#             self._param_names.extend(map(lambda nameshape: ('_'.join(nameshape)).strip('_'), itertools.izip(itertools.repeat(name), itertools.imap(lambda t: '_'.join(map(str, t)), itertools.product(*map(lambda xi: range(xi), shape))))))
        self.args = args
        self.kwargs = kwargs
        self._f = f
        self._df = df
Exemple #3
0
 def setstate(self, state):
     """
     Set the state of the model. Used for efficient pickling
     """
     self._Xscale = state.pop()
     self._Xoffset = state.pop()
     self.output_dim = state.pop()
     self.likelihood = state.pop()
     self.kern = state.pop()
     self.input_dim = state.pop()
     self.num_data = state.pop()
     self.X = state.pop()
     Model.setstate(self, state)
Exemple #4
0
 def setstate(self, state):
     """
     Set the state of the model. Used for efficient pickling
     """
     self._Xscale = state.pop()
     self._Xoffset = state.pop()
     self.output_dim = state.pop()
     self.likelihood = state.pop()
     self.kern = state.pop()
     self.input_dim = state.pop()
     self.num_data = state.pop()
     self.X = state.pop()
     Model.setstate(self, state)
Exemple #5
0
    def __init__(self, mapping=None, dL_df=None, X=None):
        num_samples = 20
        if mapping==None:
            mapping = GPy.mapping.linear(1, 1)
        if X==None:
            X = np.random.randn(num_samples, mapping.input_dim)
        if dL_df==None:
            dL_df = np.ones((num_samples, mapping.output_dim))

        self.mapping=mapping
        self.X = X
        self.dL_df = dL_df
        self.num_params = self.mapping.num_params
        Model.__init__(self)
Exemple #6
0
    def __init__(self, mapping=None, dL_df=None, X=None):
        num_samples = 20
        if mapping == None:
            mapping = GPy.mapping.linear(1, 1)
        if X == None:
            X = np.random.randn(num_samples, mapping.input_dim)
        if dL_df == None:
            dL_df = np.ones((num_samples, mapping.output_dim))

        self.mapping = mapping
        self.X = X
        self.dL_df = dL_df
        self.num_params = self.mapping.num_params
        Model.__init__(self)
Exemple #7
0
def load_model(output_file_name: str,
               data: Optional[Tuple[np.ndarray, np.ndarray]]) -> RawModelType:
    """Load a GPy model.

    :param output_file_name: The path of the file containing the saved model.
    :param data: A tuple containing X and Y arrays. data = (x, y).
    :return: The GPy model.
    """
    return Model.load_model(output_file_name, data=data)
Exemple #8
0
 def getstate(self):
     """
     Get the curent state of the class. This is only used to efficiently
     pickle the model. See also self.setstate
     """
     return Model.getstate(self) + [self.X,
             self.num_data,
             self.input_dim,
             self.kern,
             self.likelihood,
             self.output_dim,
             self._Xoffset,
             self._Xscale]
Exemple #9
0
 def getstate(self):
     """
     Get the curent state of the class. This is only used to efficiently
     pickle the model. See also self.setstate
     """
     return Model.getstate(self) + [
         self.X,
         self.num_data,
         self.input_dim,
         self.kern,
         self.likelihood,
         self.output_dim,
         self._Xoffset,
         self._Xscale,
     ]
Exemple #10
0
gp = GaussianProcess('PES.dat', InputProcessor(''), molecule_type='A2B')
params = {
    'morse_transform': {
        'morse': True,
        'morse_alpha': 1.6
    },
    'pip': {
        'degree_reduction': False,
        'pip': True
    },
    'scale_X': 'mm01',
    'scale_y': 'std'
}

X, y, Xscaler, yscaler = gp.preprocess(params, gp.raw_X, gp.raw_y)
model = Model('mymodel')
with open('model.json', 'r') as f:
    model_dict = json.load(f)
final = model.from_dict(model_dict)

# How to use 'compute_energy()' function
# --------------------------------------
# E = compute_energy(geom_vectors, cartesian=bool)
# 'geom_vectors' is either:
#  1. A list or tuple of coordinates for a single geometry.
#  2. A column vector of one or more sets of 1d coordinate vectors as a list of lists or 2D NumPy array:
# [[ coord1, coord2, ..., coordn],
#  [ coord1, coord2, ..., coordn],
#      :       :             :  ],
#  [ coord1, coord2, ..., coordn]]
# In all cases, coordinates should be supplied in the exact same format and exact same order the model was trained on.