desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Save verifier to database. A verifiersetter is required. It would be better to combine request token and verifier together:: def verifiersetter(token, verifier, request): tok = Grant.query.filter_by(token=token).first() tok.verifier = verifier[\'oauth_verifier\'] tok.user = get_current_user() return tok.save() .. admonition:: Note: A user is required on verifier, remember to attach current user to verifier.'
def save_verifier(self, token, verifier, request):
log.debug('Save verifier %r for %r', verifier, token) self._verifiersetter(token=token, verifier=verifier, request=request)
'Removes itself from the cache Note: This is required by the oauthlib'
def delete(self):
log.debug(('Deleting grant %s for client %s' % (self.code, self.client_id))) self._cache.delete(self.key) return None
'The string used as the key for the cache'
@property def key(self):
return ('%s%s' % (self.code, self.client_id))
'Determines which method of getting the query object for use'
@property def query(self):
if hasattr(self.model, 'query'): return self.model.query else: return self.session.query(self.model)
'Returns the User object Returns None if the user isn\'t found or the passwords don\'t match :param username: username of the user :param password: password of the user'
def get(self, username, password, *args, **kwargs):
user = self.query.filter_by(username=username).first() if (user and user.check_password(password)): return user return None
'Returns a Client object with the given client ID :param client_id: ID if the client'
def get(self, client_id):
return self.query.filter_by(client_id=client_id).first()
'returns a Token object with the given access token or refresh token :param access_token: User\'s access token :param refresh_token: User\'s refresh token'
def get(self, access_token=None, refresh_token=None):
if access_token: return self.query.filter_by(access_token=access_token).first() elif refresh_token: return self.query.filter_by(refresh_token=refresh_token).first() return None
'Creates a Token object and removes all expired tokens that belong to the user :param token: token object :param request: OAuthlib request object'
def set(self, token, request, *args, **kwargs):
if (hasattr(request, 'user') and request.user): user = request.user elif self.current_user: user = self.current_user() client = request.client tokens = self.query.filter_by(client_id=client.client_id, user_id=user.id).all() if tokens: for tk in tokens: self.session.delete(tk) self.session.commit() expires_in = token.get('expires_in') expires = (datetime.utcnow() + timedelta(seconds=expires_in)) tok = self.model(**token) tok.expires = expires tok.client_id = client.client_id tok.user_id = user.id self.session.add(tok) self.session.commit() return tok
'Creates Grant object with the given params :param client_id: ID of the client :param code: :param request: OAuthlib request object'
def set(self, client_id, code, request, *args, **kwargs):
expires = (datetime.utcnow() + timedelta(seconds=100)) grant = self.model(client_id=request.client.client_id, code=code['code'], redirect_uri=request.redirect_uri, scope=' '.join(request.scopes), user=self.current_user(), expires=expires) self.session.add(grant) self.session.commit()
'Get the Grant object with the given client ID and code :param client_id: ID of the client :param code:'
def get(self, client_id, code):
return self.query.filter_by(client_id=client_id, code=code).first()
'Adds remote application and applies custom attributes on it. If the application instance\'s name is different from the argument provided name, or the keyword arguments is not empty, then the application instance will not be modified but be copied as a prototype. :param remote_app: the remote application instance. :type remote_app: the subclasses of :class:`BaseApplication` :params kwargs: the overriding attributes for the application instance.'
def add_remote_app(self, remote_app, name=None, **kwargs):
if (name is None): name = remote_app.name if ((name != remote_app.name) or kwargs): remote_app = copy.copy(remote_app) remote_app.name = name vars(remote_app).update(kwargs) if (not hasattr(remote_app, 'clients')): remote_app.clients = cached_clients self.remote_apps[name] = remote_app return remote_app
'Creates and adds new remote application. :param name: the remote application\'s name. :param version: \'1\' or \'2\', the version code of OAuth protocol. :param kwargs: the attributes of remote application.'
def remote_app(self, name, version=None, **kwargs):
if (version is None): if ('request_token_url' in kwargs): version = '1' else: version = '2' if (version == '1'): remote_app = OAuth1Application(name, clients=cached_clients) elif (version == '2'): remote_app = OAuth2Application(name, clients=cached_clients) else: raise ValueError(('unkonwn version %r' % version)) return self.add_remote_app(remote_app, **kwargs)
'Obtains the access token by calling ``tokengetter`` which was defined by users. :returns: token or ``None``.'
def obtain_token(self):
tokengetter = getattr(self, '_tokengetter', None) if (tokengetter is None): raise RuntimeError(('%r missing tokengetter' % self)) return tokengetter()
'The lazy-created OAuth session with the return value of :meth:`tokengetter`. :returns: The OAuth session instance or ``None`` while token missing.'
@property def client(self):
token = self.obtain_token() if (token is None): raise AccessTokenNotFound return self._make_client_with_token(token)
'Uses cached client or create new one with specific token.'
def _make_client_with_token(self, token):
cached_clients = getattr(self, 'clients', None) hashed_token = _hash_token(self, token) if (cached_clients and (hashed_token in cached_clients)): return cached_clients[hashed_token] client = self.make_client(token) if cached_clients: cached_clients[hashed_token] = client return client
'Redirects to third-part URL and authorizes. :param callback_uri: the callback URI. if you generate it with the :func:`~flask.url_for`, don\'t forget to use the ``_external=True`` keyword argument. :param code: default is 302. the HTTP code for redirection. :returns: the redirection response.'
def authorize(self, callback_uri, code=302):
raise NotImplementedError
'Obtains access token from third-part API. :returns: the response with the type of :class:`OAuthResponse` dict, or ``None`` if the authorization has been denied.'
def authorized_response(self):
raise NotImplementedError
'Creates a client with specific access token pair. :param token: a tuple of access token pair ``(token, token_secret)`` or a dictionary of access token response. :returns: a :class:`requests_oauthlib.oauth1_session.OAuth1Session` object.'
def make_client(self, token):
if isinstance(token, dict): access_token = token['oauth_token'] access_token_secret = token['oauth_token_secret'] else: (access_token, access_token_secret) = token return self.make_oauth_session(resource_owner_key=access_token, resource_owner_secret=access_token_secret)
'Creates a client with specific access token dictionary. :param token: a dictionary of access token response. :returns: a :class:`requests_oauthlib.oauth2_session.OAuth2Session` object.'
def make_client(self, token):
return self.make_oauth_session(token=token)
'A decorator to register a callback function for saving refreshed token while the old token has expired and the ``refresh_token_url`` has been specified. It is necessary for using the automatic refresh mechanism. :param fn: the callback function with ``token`` as its unique argument.'
def tokensaver(self, fn):
self._tokensaver = fn return fn
'Creates a context to enable the oauthlib environment variable in order to debug with insecure transport.'
@contextlib.contextmanager def insecure_transport(self):
origin = os.environ.get('OAUTHLIB_INSECURE_TRANSPORT') if (current_app.debug or current_app.testing): try: os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = '1' (yield) finally: if origin: os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = origin else: os.environ.pop('OAUTHLIB_INSECURE_TRANSPORT', None) else: if origin: warnings.warn('OAUTHLIB_INSECURE_TRANSPORT has been found in os.environ but the app is not running in debug mode or testing mode. It may put you in danger of the Man-in-the-middle attack while using OAuth 2.', RuntimeWarning) (yield)
'Creates a remote app and registers it.'
def register_to(self, oauth, name=None, **kwargs):
kwargs = self._process_kwargs(name=(name or self.default_name), **kwargs) return oauth.remote_app(**kwargs)
'Creates a remote app only.'
def create(self, oauth, **kwargs):
kwargs = self._process_kwargs(name=self.default_name, register=False, **kwargs) return oauth.remote_app(**kwargs)
'Sets a function to process kwargs before creating any app.'
def kwargs_processor(self, fn):
self._kwargs_processor = fn return fn
'Returns a :class:`NullCache` instance'
def _null(self, **kwargs):
return NullCache()
'Returns a :class:`SimpleCache` instance .. warning:: This cache system might not be thread safe. Use with caution.'
def _simple(self, **kwargs):
kwargs.update(dict(threshold=self._config('threshold', 500))) return SimpleCache(**kwargs)
'Returns a :class:`MemcachedCache` instance'
def _memcache(self, **kwargs):
kwargs.update(dict(servers=self._config('MEMCACHED_SERVERS', None), key_prefix=self._config('key_prefix', None))) return MemcachedCache(**kwargs)
'Returns a :class:`RedisCache` instance'
def _redis(self, **kwargs):
kwargs.update(dict(host=self._config('REDIS_HOST', 'localhost'), port=self._config('REDIS_PORT', 6379), password=self._config('REDIS_PASSWORD', None), db=self._config('REDIS_DB', 0), key_prefix=self._config('KEY_PREFIX', None))) return RedisCache(**kwargs)
'Returns a :class:`FileSystemCache` instance'
def _filesystem(self, **kwargs):
kwargs.update(dict(threshold=self._config('threshold', 500))) return FileSystemCache(self._config('dir', None), **kwargs)
'Notes Monitors quantities related to the approximate posterior parameters phi and the conditional and prior parameters theta.'
@wraps(Model.get_monitoring_channels) def get_monitoring_channels(self, data):
(space, source) = self.get_monitoring_data_specs() space.validate(data) rval = OrderedDict() X = data epsilon_shape = (X.shape[0], self.nhid) epsilon = self.sample_from_epsilon(shape=epsilon_shape) phi = self.encode_phi(X) z = self.sample_from_q_z_given_x(epsilon=epsilon, phi=phi) theta = self.decode_theta(z) X_r = self.means_from_theta(theta) rval['reconstruction_mse'] = T.sqr((X - X_r)).mean() posterior_channels = self.posterior.monitoring_channels_from_conditional_params(phi) safe_update(rval, posterior_channels) conditional_channels = self.conditional.monitoring_channels_from_conditional_params(theta) safe_update(rval, conditional_channels) prior_channels = self.prior.monitoring_channels_from_prior_params() safe_update(rval, prior_channels) return rval
'Returns the weights of the first layer of the decoding network'
def get_conditional_weights(self):
return self.conditional.get_weights()
'Returns the model\'s prior distribution parameters'
def get_prior_params(self):
return self.prior.get_params()
'Returns the model\'s conditional distribution parameters'
def get_conditional_params(self):
return self.conditional.get_params()
'Returns the model\'s posterior distribution parameters'
def get_posterior_params(self):
return self.posterior.get_params()
'Sample from the model\'s learned distribution Parameters num_samples : int Number of samples return_sample_means : bool, optional Whether to return the conditional expectations :math:`\mathbb{E}[p_\theta(\mathbf{x} \mid \mathbf{h})]` in addition to the actual samples. Defaults to `False`. Returns rval : tensor_like or tuple of tensor_like Samples, and optionally conditional expectations'
def sample(self, num_samples, return_sample_means=True, **kwargs):
z = self.sample_from_p_z(num_samples=num_samples, **kwargs) theta = self.decode_theta(z) X = self.sample_from_p_x_given_z(num_samples=num_samples, theta=theta) if return_sample_means: return (X, self.means_from_theta(theta)) else: return X
'Given an input, generates its reconstruction by propagating it through the encoder network and projecting it back through the decoder network. Parameters X : tensor_like Input to reconstruct noisy_encoding : bool, optional If `True`, sample z from the posterior distribution. If `False`, take the expected value. Defaults to `False`. return_sample_means : bool, optional Whether to return the conditional expectations :math:`\mathbb{E}[p_\theta(\mathbf{x} \mid \mathbf{h})]` in addition to the actual samples. Defaults to `False`. Returns rval : tensor_like or tuple of tensor_like Samples, and optionally conditional expectations'
def reconstruct(self, X, noisy_encoding=False, return_sample_means=True):
epsilon = self.sample_from_epsilon((X.shape[0], self.nhid)) if (not noisy_encoding): epsilon *= 0 phi = self.encode_phi(X) z = self.sample_from_q_z_given_x(epsilon=epsilon, phi=phi) theta = self.decode_theta(z) reconstructed_X = self.sample_from_p_x_given_z(num_samples=X.shape[0], theta=theta) if return_sample_means: return (reconstructed_X, self.means_from_theta(theta)) else: return reconstructed_X
'Computes the VAE lower-bound on the marginal log-likelihood of X. Parameters X : tensor_like Input num_samples : int Number of posterior samples per data point, e.g. number of times z is sampled for each x. approximate_kl : bool, optional Whether to compute a stochastic approximation of the KL divergence term. Defaults to `False`. return_individual_terms : bool, optional If `True`, return `(kl_divergence_term, expectation_term)` instead. Defaults to `False`. Returns lower_bound : tensor_like Lower-bound on the marginal log-likelihood'
def log_likelihood_lower_bound(self, X, num_samples, approximate_kl=False, return_individual_terms=False):
epsilon_shape = (num_samples, X.shape[0], self.nhid) epsilon = self.sample_from_epsilon(shape=epsilon_shape) phi = self.encode_phi(X) prior_theta = self.get_prior_theta() z = self.sample_from_q_z_given_x(epsilon=epsilon, phi=phi) kl_divergence_term = self.kl_divergence_term(phi=phi, theta=prior_theta, approximate=approximate_kl, epsilon=epsilon) z = z.reshape(((epsilon.shape[0] * epsilon.shape[1]), epsilon.shape[2])) theta = self.decode_theta(z) theta = tuple((theta_i.reshape((epsilon.shape[0], epsilon.shape[1], theta_i.shape[1])) for theta_i in theta)) expectation_term = self.expectation_term(X=X.dimshuffle('x', 0, 1), theta=theta).mean(axis=0) if return_individual_terms: return (kl_divergence_term, expectation_term) else: return ((- kl_divergence_term) + expectation_term)
'Computes the importance sampling approximation to the marginal log-likelihood of X, using the reparametrization trick. Parameters X : tensor_like Input num_samples : int Number of posterior samples per data point, e.g. number of times z is sampled for each x. Returns approximation : tensor_like Approximation on the marginal log-likelihood'
def log_likelihood_approximation(self, X, num_samples):
epsilon_shape = (num_samples, X.shape[0], self.nhid) epsilon = self.sample_from_epsilon(shape=epsilon_shape) phi = self.encode_phi(X) z = self.sample_from_q_z_given_x(epsilon=epsilon, phi=phi) flat_z = z.reshape(((epsilon.shape[0] * epsilon.shape[1]), epsilon.shape[2])) theta = self.decode_theta(flat_z) theta = tuple((theta_i.reshape((epsilon.shape[0], epsilon.shape[1], theta_i.shape[1])) for theta_i in theta)) log_q_z_x = self.log_q_z_given_x(z=z, phi=phi) log_p_z = self.log_p_z(z) log_p_x_z = self.log_p_x_given_z(X=X.dimshuffle(('x', 0, 1)), theta=theta) return (log_sum_exp(((log_p_z + log_p_x_z) - log_q_z_x), axis=0) - T.log(num_samples))
'Maps input `X` to a tuple of parameters of the :math:`q_\phi(\mathbf{z} \mid \mathbf{x})` posterior distribution Parameters X : tensor_like Input Returns phi : tuple of tensor_like Tuple of parameters for the posterior distribution'
def encode_phi(self, X):
return self.posterior.encode_conditional_params(X)
'Maps latent variable `z` to a tuple of parameters of the :math:`p_\theta(\mathbf{x} \mid \mathbf{z})` distribution Parameters z : tensor_like Latent sample Returns theta : tuple of tensor_like Tuple of parameters for the conditional distribution'
def decode_theta(self, z):
return self.conditional.encode_conditional_params(z)
'Returns parameters of the prior distribution :math:`p_\theta(\mathbf{z})`'
def get_prior_theta(self):
return self.prior.get_params()
'Given a tuple of parameters of the :math:`p_\theta(\mathbf{x} \mid \mathbf{z})` distribution, returns the expected value of `x`. Parameters theta : tuple of tensor_like Tuple of parameters for the conditional distribution Returns means : tensor_like Expected value of `x`'
def means_from_theta(self, theta):
return self.conditional.conditional_expectation(theta)
'Computes an approximation of :math:`\mathrm{E}_{q_\phi(\mathbf{z} \mid \mathbf{x})} [\log p_\theta(\mathbf{x} \mid \mathbf{z})]` Parameters X : tensor_like Input theta : tuple of tensor_like Tuple of parameters for the conditional distribution Returns expectation_term : tensor_like Expectation term'
def expectation_term(self, X, theta):
return self.log_p_x_given_z(X, theta)
'Computes the KL-divergence term of the VAE criterion. Parameters phi : tuple of tensor_like Parameters of the distribution :math:`q_\phi(\mathbf{z} \mid \mathbf{x})` theta : tuple of tensor_like Parameters of the distribution :math:`p_\theta(\mathbf{z})` approximate_kl : bool, optional Whether to compute a stochastic approximation of the KL divergence term. Defaults to `False`. epsilon : tensor_like, optional Noise samples used to compute the approximate KL term. Defaults to `None`.'
def kl_divergence_term(self, phi, theta, approximate=False, epsilon=None):
if (self.kl_integrator is None): warnings.warn('computing the analytical KL divergence term is not supported for this prior/posterior combination, computing a stochastic approximate KL instead') return self._approximate_kl_divergence_term(phi, epsilon) if approximate: return self._approximate_kl_divergence_term(phi, epsilon) else: return self.kl_integrator.kl_divergence(phi=phi, theta=theta, prior=self.prior, posterior=self.posterior)
'Returns a Monte Carlo approximation of the KL divergence term. Parameters phi : tuple of tensor_like Tuple of parameters for the posterior distribution epsilon : tensor_like Noise term from which z is computed'
def _approximate_kl_divergence_term(self, phi, epsilon):
if (epsilon is None): raise ValueError('stochastic KL is requested but no epsilon is given') z = self.sample_from_q_z_given_x(epsilon=epsilon, phi=phi) log_q_z_x = self.log_q_z_given_x(z=z, phi=phi) log_p_z = self.log_p_z(z) return (log_q_z_x - log_p_z).mean(axis=0)
'If the prior/posterior combination allows it, analytically computes the per-latent-dimension KL divergences between the prior distribution :math:`p_\theta(\mathbf{z})` and :math:`q_\phi(\mathbf{z} \mid \mathbf{x})` Parameters phi : tuple of tensor_like Parameters of the distribution :math:`q_\phi(\mathbf{z} \mid \mathbf{x})` theta : tuple of tensor_like Parameters of the distribution :math:`p_\theta(\mathbf{z})`'
def per_component_kl_divergence_term(self, phi, theta):
if (self.kl_integrator is None): raise NotImplementedError('impossible to compute the analytical KL divergence') else: return self.kl_integrator.per_component_kl_divergence(phi=phi, theta=theta, prior=self.prior, posterior=self.posterior)
'Given a tuple of parameters, samples from the :math:`p_\theta(\mathbf{x} \mid \mathbf{z})` conditional distribution Parameters num_samples : int Number of samples theta : tuple of tensor_like Tuple of parameters for the conditional distribution Returns x : tensor_like Samples'
def sample_from_p_x_given_z(self, num_samples, theta):
return self.conditional.sample_from_conditional(conditional_params=theta, num_samples=num_samples)
'Samples from the prior distribution :math:`p_\theta(\mathbf{z})` Parameters num_samples : int Number of samples Returns z : tensor_like Sample from the prior distribution'
def sample_from_p_z(self, num_samples, **kwargs):
return self.prior.sample_from_p_z(num_samples, **kwargs)
'Given a tuple of parameters and an epsilon noise sample, generates samples from the :math:`q_\phi(\mathbf{z} \mid \mathbf{x})` posterior distribution using the reparametrization trick Parameters epsilon : tensor_like Noise sample phi : tuple of tensor_like Tuple of parameters for the posterior distribution Returns z : tensor_like Posterior sample'
def sample_from_q_z_given_x(self, epsilon, phi):
return self.posterior.sample_from_conditional(conditional_params=phi, epsilon=epsilon)
'Samples from a canonical noise distribution from which posterior samples will be drawn using the reparametrization trick (see `_sample_from_q_z_given_x`) Parameters shape : tuple of int Shape of the requested samples Returns epsilon : tensor_like Noise samples'
def sample_from_epsilon(self, shape):
return self.posterior.sample_from_epsilon(shape)
'Computes the log-prior probabilities of `z` Parameters z : tensor_like Posterior samples Returns log_p_z : tensor_like Log-prior probabilities'
def log_p_z(self, z):
return self.prior.log_p_z(z)
'Computes the log-conditional probabilities of `X` Parameters X : tensor_like Input theta : tuple of tensor_like Tuple of parameters for the contitional distribution Returns log_p_x_z : tensor_like Log-prior probabilities'
def log_p_x_given_z(self, X, theta):
return self.conditional.log_conditional(X, theta)
'Computes the log-posterior probabilities of `z` Parameters z : tensor_like Posterior samples phi : tuple of tensor_like Tuple of parameters for the posterior distribution Returns log_q_z_x : tensor_like Log-posterior probabilities'
def log_q_z_given_x(self, z, phi):
return self.posterior.log_conditional(z, phi)
'Computes the KL-divergence term of the VAE criterion. Parameters phi : tuple of tensor_like Parameters of the distribution :math:`q_\phi(\mathbf{z} \mid \mathbf{x})` theta : tuple of tensor_like Parameters of the distribution :math:`p_\theta(\mathbf{z})`'
def kl_divergence(self, phi, theta, prior, posterior):
raise NotImplementedError(((str(self.__class__) + ' does not ') + 'implement kl_divergence'))
'If the prior/posterior combination allows it, computes the per-component KL divergence term Parameters phi : tuple of tensor_like Parameters of the distribution :math:`q_\phi(\mathbf{z} \mid \mathbf{x})` theta : tuple of tensor_like Parameters of the distribution :math:`p_\theta(\mathbf{z})`'
def per_component_kl_divergence(self, phi, theta, prior, posterior):
raise NotImplementedError(((str(self.__class__) + ' does not ') + 'implement per_component_kl_divergence'))
'Checks that the prior/posterior combination is what the integrator expects and raises an exception otherwise Parameters prior : pylearn2.models.vae.prior.Prior Prior distribution on z posterior : pylearn2.models.vae.posterior.Posterior Posterior distribution on z given x'
def _validate_prior_posterior(self, prior, posterior):
if ((self.prior_class is None) or (self.posterior_class is None)): raise NotImplementedError((((str(self.__class__) + ' has not set ') + "the required 'prior_class' and ") + "'posterior_class' class attributes")) if (not isinstance(prior, self.prior_class)): raise ValueError((((('prior class ' + str(prior.__class__)) + ' is ') + 'incompatible with expected prior class ') + str(self.prior_class.__class__))) if (not isinstance(posterior, self.posterior_class)): raise ValueError((((('posterior class ' + str(posterior.__class__)) + ' is incompatible with expected posterior ') + 'class ') + str(self.prior_class.__class__)))
'Returns its MLP\'s weights'
def get_weights(self):
return self.mlp.get_weights()
'Returns the encoding model\'s learning rate scalers'
def get_lr_scalers(self):
return self.mlp.get_lr_scalers()
'Returns a default `Layer` mapping the MLP\'s last hidden representation to parameters of the conditional distribution'
def _get_default_output_layer(self):
raise NotImplementedError((str(self.__class__) + ' does not implement _get_default_output_layer'))
'Returns the expected output space of the MLP, i.e. a description of how the parameters output by the MLP should look like.'
def _get_required_mlp_output_space(self):
raise NotImplementedError((str(self.__class__) + ' does not implement _get_required_mlp_output_space'))
'Makes sure the MLP\'s output layer is compatible with the parameters expected by the conditional distribution'
def _validate_mlp(self):
expected_output_space = self._get_required_mlp_output_space() mlp_output_space = self.mlp.get_output_space() if (not (mlp_output_space == expected_output_space)): raise ValueError((((((("the specified MLP's output space is " + 'incompatible with ') + str(self.__class__)) + ': expected ') + str(expected_output_space)) + " but encoding model's output space is ") + str(mlp_output_space)))
'Get monitoring channels from the parameters of the conditional distribution. By default, no monitoring channel is computed. Parameters conditional_params : tuple of tensor_like Parameters of the conditional distribution'
def monitoring_channels_from_conditional_params(self, conditional_params):
return OrderedDict()
'Modifies the parameters before a learning update is applied. By default, only calls the MLP\'s `modify_updates` method.'
def _modify_updates(self, updates):
self.mlp.modify_updates(updates)
'Returns the VAE that this `Conditional` instance belongs to, or None if it has not been assigned to a VAE yet.'
def get_vae(self):
if hasattr(self, 'vae'): return self.vae else: return None
'Assigns this `Conditional` instance to a VAE. Parameters vae : pylearn2.models.vae.VAE VAE to assign to'
def set_vae(self, vae):
if (self.get_vae() is not None): raise RuntimeError(((('this ' + str(self.__class__)) + ' instance ') + 'already belongs to another VAE')) self.vae = vae self.rng = self.vae.rng self.theano_rng = make_theano_rng(int(self.rng.randint((2 ** 30))), which_method=['normal', 'uniform']) self.batch_size = vae.batch_size
'Initialize model parameters. Parameters input_space : pylearn2.space.Space The input space for the MLP ndim : int Number of units of a in f(a | b)'
def initialize_parameters(self, input_space, ndim):
self.ndim = ndim self.input_space = input_space if self.output_layer_required: self.mlp.add_layers([self._get_default_output_layer()]) self.mlp.set_mlp(self) self.mlp.set_input_space(self.input_space) self._validate_mlp() self._params = self.mlp.get_params() for param in self._params: param.name = ((self.name + '_') + param.name)
'Maps input `X` to a tuple of parameters of the conditional distribution Parameters X : tensor_like Input Returns conditional_params : tuple of tensor_like Tuple of parameters for the conditional distribution'
def encode_conditional_params(self, X):
conditional_params = self.mlp.fprop(X) if (not (type(conditional_params) == tuple)): conditional_params = (conditional_params,) return conditional_params
'Given parameters of the conditional distribution, returns the expected value of a in p(a | b). Parameters conditional_params : tuple of tensor_like Tuple of parameters for the conditional distribution'
def conditional_expectation(self, conditional_params):
raise NotImplementedError((str(self.__class__) + ' does not implement conditional_expectation.'))
'Given a tuple of conditional parameters and an epsilon noise sample, generates samples from the conditional distribution. Parameters conditional_params : tuple of tensor_like Tuple of parameters for the conditional distribution epsilon : tensor_like, optional Noise sample used to sample with the reparametrization trick. If `None`, sampling will be done without the reparametrization trick. Defaults to `None`. num_samples : int, optional Number of requested samples, in case the reparametrization trick is not used Returns rval : tensor_like Samples'
def sample_from_conditional(self, conditional_params, epsilon=None, num_samples=None):
raise NotImplementedError((str(self.__class__) + ' does not implement sample_from_conditional.'))
'Samples from a canonical noise distribution from which conditional samples will be drawn using the reparametrization trick. Parameters shape : tuple of int Shape of the requested samples Returns epsilon : tensor_like Noise samples Notes If using the reparametrization trick is not possible for this particular conditional distribution, will raise an exception.'
def sample_from_epsilon(self, shape):
raise NotImplementedError((str(self.__class__) + ' does not implement sample_from_epsilon, which probably means it is not able to sample using the reparametrization trick.'))
'Given the conditional parameters, computes the log-conditional probabilities of samples of this distribution. Parameters samples : tensor_like Conditional samples conditional_params : tuple of tensor_like Tuple of parameters for the conditional distribution Returns log_conditonal : tensor_like Log-conditional probabilities'
def log_conditional(self, samples, conditional_params):
raise NotImplementedError((str(self.__class__) + ' does not implement log_conditional.'))
'Returns the VAE that this `Prior` instance belongs to, or None if it has not been assigned to a VAE yet.'
def get_vae(self):
if hasattr(self, 'vae'): return self.vae else: return None
'Assigns this `Prior` instance to a VAE. Parameters vae : pylearn2.models.vae.VAE VAE to assign to'
def set_vae(self, vae):
if (self.get_vae() is not None): raise RuntimeError('this `Prior` instance already belongs to another VAE') self.vae = vae self.rng = self.vae.rng self.theano_rng = make_theano_rng(int(self.rng.randint((2 ** 30))), which_method=['normal', 'uniform']) self.batch_size = vae.batch_size
'Initialize model parameters. Parameters nhid : int Number of latent units for z'
def initialize_parameters(self, nhid):
raise NotImplementedError((str(self.__class__) + ' does not implement initialize_parameters'))
'Get monitoring channels from the parameters of the prior distribution. By default, no monitoring channel is computed.'
def monitoring_channels_from_prior_params(self):
return OrderedDict()
'Samples from the prior distribution :math:`p_\theta(\mathbf{z})` Parameters num_samples : int Number of samples Returns z : tensor_like Sample from the prior distribution'
def sample_from_p_z(self, num_samples, **kwargs):
raise NotImplementedError((str(self.__class__) + ' does not implement sample_from_p_z.'))
'Computes the log-prior probabilities of `z` Parameters z : tensor_like Posterior samples Returns log_p_z : tensor_like Log-prior probabilities'
def log_p_z(self, z):
raise NotImplementedError((str(self.__class__) + ' does not implement log_p_z.'))
'Tests that a matrix of binary samples (observations in rows, variables in columns) 1) Has the right shape 2) Is binary 3) Converges to the right mean'
@staticmethod def check_samples(value, expected_shape, expected_mean, tol):
assert (value.shape == expected_shape) assert is_binary(value) mean = value.mean(axis=0) max_error = np.abs((mean - expected_mean)).max() print('Actual mean:') print(mean) print('Expected mean:') print(expected_mean) print('Maximal error:', max_error) if (max_error > tol): raise ValueError("Samples don't seem to have the right mean.")
'gets a small batch of data sets up an S3C model'
def __init__(self):
self.prev_floatX = config.floatX config.floatX = 'float64' try: self.tol = 1e-05 X = np.random.RandomState([1, 2, 3]).randn(1000, 5) X -= X.mean() X /= X.std() (m, D) = X.shape N = 5 self.model = S3C(nvis=D, nhid=N, irange=0.1, init_bias_hid=0.0, init_B=3.0, min_B=1e-08, max_B=1000.0, init_alpha=1.0, min_alpha=1e-08, max_alpha=1000.0, init_mu=1.0, e_step=None, m_step=Grad_M_Step(), min_bias_hid=(-1e+30), max_bias_hid=1e+30) self.model.make_pseudoparams() self.h_new_coeff_schedule = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0] self.e_step = E_Step_Scan(h_new_coeff_schedule=self.h_new_coeff_schedule) self.e_step.register_model(self.model) self.X = X self.N = N self.m = m finally: config.floatX = self.prev_floatX
'tests that inference with scan matches result using unrolled loops'
def test_match_unrolled(self):
unrolled_e_step = E_Step(h_new_coeff_schedule=self.h_new_coeff_schedule) unrolled_e_step.register_model(self.model) V = T.matrix() scan_result = self.e_step.infer(V) unrolled_result = unrolled_e_step.infer(V) outputs = [] for key in scan_result: outputs.append(scan_result[key]) outputs.append(unrolled_result[key]) f = function([V], outputs) outputs = f(self.X) assert ((len(outputs) % 2) == 0) for i in xrange(0, len(outputs), 2): assert np.allclose(outputs[i], outputs[(i + 1)])
'tests that the gradients with respect to s_i are 0 after doing a mean field update of s_i'
def test_grad_s(self):
model = self.model e_step = self.e_step X = self.X assert (X.shape[0] == self.m) model.test_batch_size = X.shape[0] init_H = e_step.init_H_hat(V=X) init_Mu1 = e_step.init_S_hat(V=X) prev_setting = config.compute_test_value config.compute_test_value = 'off' (H, Mu1) = function([], outputs=[init_H, init_Mu1])() config.compute_test_value = prev_setting H = broadcast(H, self.m) Mu1 = broadcast(Mu1, self.m) H = np.cast[config.floatX](self.model.rng.uniform(0.0, 1.0, H.shape)) Mu1 = np.cast[config.floatX](self.model.rng.uniform((-5.0), 5.0, Mu1.shape)) H_var = T.matrix(name='H_var') H_var.tag.test_value = H Mu1_var = T.matrix(name='Mu1_var') Mu1_var.tag.test_value = Mu1 idx = T.iscalar() idx.tag.test_value = 0 S = e_step.infer_S_hat(V=X, H_hat=H_var, S_hat=Mu1_var) s_idx = S[:, idx] s_i_func = function([H_var, Mu1_var, idx], s_idx) sigma0 = (1.0 / model.alpha) Sigma1 = e_step.infer_var_s1_hat() mu0 = T.zeros_like(model.mu) trunc_kl = ((- model.entropy_hs(H_hat=H_var, var_s0_hat=sigma0, var_s1_hat=Sigma1)) + model.expected_energy_vhs(V=X, H_hat=H_var, S_hat=Mu1_var, var_s0_hat=sigma0, var_s1_hat=Sigma1)) grad_Mu1 = T.grad(trunc_kl.sum(), Mu1_var) grad_Mu1_idx = grad_Mu1[:, idx] grad_func = function([H_var, Mu1_var, idx], grad_Mu1_idx) for i in xrange(self.N): Mu1[:, i] = s_i_func(H, Mu1, i) g = grad_func(H, Mu1, i) assert (not contains_nan(g)) g_abs_max = np.abs(g).max() if (g_abs_max > self.tol): raise Exception(((('after mean field step, gradient of kl divergence wrt mean field parameter should be 0, but here the max magnitude of a gradient element is ' + str(g_abs_max)) + ' after updating s_') + str(i)))
'tests that the value of the kl divergence decreases with each update to s_i'
def test_value_s(self):
model = self.model e_step = self.e_step X = self.X assert (X.shape[0] == self.m) init_H = e_step.init_H_hat(V=X) init_Mu1 = e_step.init_S_hat(V=X) prev_setting = config.compute_test_value config.compute_test_value = 'off' (H, Mu1) = function([], outputs=[init_H, init_Mu1])() config.compute_test_value = prev_setting H = broadcast(H, self.m) Mu1 = broadcast(Mu1, self.m) H = np.cast[config.floatX](self.model.rng.uniform(0.0, 1.0, H.shape)) Mu1 = np.cast[config.floatX](self.model.rng.uniform((-5.0), 5.0, Mu1.shape)) H_var = T.matrix(name='H_var') H_var.tag.test_value = H Mu1_var = T.matrix(name='Mu1_var') Mu1_var.tag.test_value = Mu1 idx = T.iscalar() idx.tag.test_value = 0 S = e_step.infer_S_hat(V=X, H_hat=H_var, S_hat=Mu1_var) s_idx = S[:, idx] s_i_func = function([H_var, Mu1_var, idx], s_idx) sigma0 = (1.0 / model.alpha) Sigma1 = e_step.infer_var_s1_hat() mu0 = T.zeros_like(model.mu) trunc_kl = ((- model.entropy_hs(H_hat=H_var, var_s0_hat=sigma0, var_s1_hat=Sigma1)) + model.expected_energy_vhs(V=X, H_hat=H_var, S_hat=Mu1_var, var_s0_hat=sigma0, var_s1_hat=Sigma1)) trunc_kl_func = function([H_var, Mu1_var], trunc_kl) for i in xrange(self.N): prev_kl = trunc_kl_func(H, Mu1) Mu1[:, i] = s_i_func(H, Mu1, i) new_kl = trunc_kl_func(H, Mu1) increase = (new_kl - prev_kl) mx = increase.max() if (mx > 0.001): raise Exception(((('after mean field step in s, kl divergence should decrease, but some elements increased by as much as ' + str(mx)) + ' after updating s_') + str(i)))
'tests that the gradients with respect to h_i are 0 after doing a mean field update of h_i'
def test_grad_h(self):
model = self.model e_step = self.e_step X = self.X assert (X.shape[0] == self.m) init_H = e_step.init_H_hat(V=X) init_Mu1 = e_step.init_S_hat(V=X) prev_setting = config.compute_test_value config.compute_test_value = 'off' (H, Mu1) = function([], outputs=[init_H, init_Mu1])() config.compute_test_value = prev_setting H = broadcast(H, self.m) Mu1 = broadcast(Mu1, self.m) H = np.cast[config.floatX](self.model.rng.uniform(0.0, 1.0, H.shape)) Mu1 = np.cast[config.floatX](self.model.rng.uniform((-5.0), 5.0, Mu1.shape)) H_var = T.matrix(name='H_var') H_var.tag.test_value = H Mu1_var = T.matrix(name='Mu1_var') Mu1_var.tag.test_value = Mu1 idx = T.iscalar() idx.tag.test_value = 0 new_H = e_step.infer_H_hat(V=X, H_hat=H_var, S_hat=Mu1_var) h_idx = new_H[:, idx] updates_func = function([H_var, Mu1_var, idx], h_idx) sigma0 = (1.0 / model.alpha) Sigma1 = e_step.infer_var_s1_hat() mu0 = T.zeros_like(model.mu) trunc_kl = ((- model.entropy_hs(H_hat=H_var, var_s0_hat=sigma0, var_s1_hat=Sigma1)) + model.expected_energy_vhs(V=X, H_hat=H_var, S_hat=Mu1_var, var_s0_hat=sigma0, var_s1_hat=Sigma1)) grad_H = T.grad(trunc_kl.sum(), H_var) assert (len(grad_H.type.broadcastable) == 2) grad_func = function([H_var, Mu1_var], grad_H) failed = False for i in xrange(self.N): rval = updates_func(H, Mu1, i) H[:, i] = rval g = grad_func(H, Mu1)[:, i] assert (not contains_nan(g)) g_abs_max = np.abs(g).max() if (g_abs_max > self.tol): failed = True print('iteration ', i) failing_h = H[((np.abs(g) > self.tol), i)] high_mask = (failing_h > 0.001) low_mask = (failing_h < 0.999) mask = (high_mask * low_mask) print('masked failures: ', mask.shape[0], ' err ', g_abs_max) if (mask.sum() > 0): print('failing h passing the range mask') print(failing_h[mask.astype(bool)]) raise Exception(((('after mean field step, gradient of kl divergence wrt freshly updated variational parameter should be 0, but here the max magnitude of a gradient element is ' + str(g_abs_max)) + ' after updating h_') + str(i)))
'tests that the value of the kl divergence decreases with each update to h_i'
def test_value_h(self):
model = self.model e_step = self.e_step X = self.X assert (X.shape[0] == self.m) init_H = e_step.init_H_hat(V=X) init_Mu1 = e_step.init_S_hat(V=X) prev_setting = config.compute_test_value config.compute_test_value = 'off' (H, Mu1) = function([], outputs=[init_H, init_Mu1])() config.compute_test_value = prev_setting H = broadcast(H, self.m) Mu1 = broadcast(Mu1, self.m) H = np.cast[config.floatX](self.model.rng.uniform(0.0, 1.0, H.shape)) Mu1 = np.cast[config.floatX](self.model.rng.uniform((-5.0), 5.0, Mu1.shape)) H_var = T.matrix(name='H_var') H_var.tag.test_value = H Mu1_var = T.matrix(name='Mu1_var') Mu1_var.tag.test_value = Mu1 idx = T.iscalar() idx.tag.test_value = 0 newH = e_step.infer_H_hat(V=X, H_hat=H_var, S_hat=Mu1_var) h_idx = newH[:, idx] h_i_func = function([H_var, Mu1_var, idx], h_idx) sigma0 = (1.0 / model.alpha) Sigma1 = e_step.infer_var_s1_hat() mu0 = T.zeros_like(model.mu) trunc_kl = ((- model.entropy_hs(H_hat=H_var, var_s0_hat=sigma0, var_s1_hat=Sigma1)) + model.expected_energy_vhs(V=X, H_hat=H_var, S_hat=Mu1_var, var_s0_hat=sigma0, var_s1_hat=Sigma1)) trunc_kl_func = function([H_var, Mu1_var], trunc_kl) for i in xrange(self.N): prev_kl = trunc_kl_func(H, Mu1) H[:, i] = h_i_func(H, Mu1, i) new_kl = trunc_kl_func(H, Mu1) increase = (new_kl - prev_kl) print('failures after iteration ', i, ': ', (increase > self.tol).sum()) mx = increase.max() if (mx > 0.0001): print('increase amounts of failing examples:') print(increase[(increase > self.tol)]) print('failing H:') print(H[(increase > self.tol), :]) print('failing Mu1:') print(Mu1[(increase > self.tol), :]) print('failing V:') print(X[(increase > self.tol), :]) raise Exception(((('after mean field step in h, kl divergence should decrease, but some elements increased by as much as ' + str(mx)) + ' after updating h_') + str(i)))
'checks that two models with the same parameters have zero KL divergence'
def test_same_zero(self):
rng = np.random.RandomState([1, 2, 3]) dim = self.dim num_trials = 3 for trial in xrange(num_trials): mu = rng.randn(dim).astype(floatX) beta = rng.uniform(0.1, 10.0, (dim,)).astype(floatX) self.p.mu.set_value(mu) self.q.mu.set_value(mu) self.p.beta.set_value(beta) self.q.beta.set_value(beta) kl = kl_divergence(self.q, self.p) kl = function([], kl)() tol = 1e-07 if ((kl > tol) or (not (kl <= tol))): raise AssertionError(('KL divergence between two equivalent models should be 0 but is ' + str(kl)))
'checks that the kl divergence is non-negative at sampled parameter values for q and p'
def test_nonnegative_samples(self):
rng = np.random.RandomState([1, 2, 3]) dim = self.dim num_trials = 3 for trial in xrange(num_trials): mu = rng.randn(dim).astype(floatX) beta = rng.uniform(0.1, 10.0, (dim,)).astype(floatX) self.p.mu.set_value(mu) mu = rng.randn(dim).astype(floatX) self.q.mu.set_value(mu) self.p.beta.set_value(beta) beta = rng.uniform(0.1, 10.0, (dim,)).astype(floatX) self.q.beta.set_value(beta) kl = kl_divergence(self.q, self.p) kl = function([], kl)() if (kl < 0.0): raise AssertionError(('KL divergence should be non-negative but is ' + str(kl)))
'minimizes the kl divergence between q and p using batch gradient descent and checks that the result is zero'
def test_zero_optimal(self):
rng = np.random.RandomState([1, 2, 3]) dim = self.dim num_trials = 3 mu = rng.randn(dim).astype(floatX) beta = rng.uniform(0.1, 10.0, (dim,)).astype(floatX) self.p.mu.set_value(mu) mu = rng.randn(dim).astype(floatX) self.q.mu.set_value(mu) self.p.beta.set_value(beta) beta = rng.uniform(0.1, 10.0, (dim,)).astype(floatX) self.q.beta.set_value(beta) kl = kl_divergence(self.q, self.p) p = self.p q = self.q optimizer = BatchGradientDescent(max_iter=100, line_search_mode='exhaustive', verbose=True, objective=kl, conjugate=True, params=[p.mu, p.beta, q.mu, q.beta], param_constrainers=[p.modify_updates, q.modify_updates]) kl = optimizer.minimize() if (kl < 0.0): if (config.floatX == 'float32'): neg_tol = 4.8e-07 else: neg_tol = 0.0 if (kl < (- neg_tol)): raise AssertionError(('KL divergence should be non-negative but is ' + str(kl))) warnings.warn('KL divergence is not very numerically stable, evidently') tol = 6e-05 if (kl > tol): print('kl:', kl) print('tol:', tol) assert (kl <= tol) assert (not (kl > tol))
'gets a small batch of data sets up an S3C model and learns on the data creates an expression for the log likelihood of the data'
def __init__(self):
self.prev_floatX = config.floatX config.floatX = 'float64' try: self.tol = 1e-05 if (config.mode in ['DebugMode', 'DEBUG_MODE']): X = np.random.RandomState([1, 2, 3]).randn(30, 108) (m, D) = X.shape N = 10 else: X = np.random.RandomState([1, 2, 3]).randn(1000, 108) (m, D) = X.shape N = 300 self.model = S3C(nvis=D, nhid=N, irange=0.5, init_bias_hid=(-0.1), init_B=1.0, min_B=1e-08, max_B=100000000.0, tied_B=1, e_step=E_Step_Scan(h_new_coeff_schedule=[0.01]), init_alpha=1.0, min_alpha=1e-08, max_alpha=100000000.0, init_mu=1.0, m_step=Grad_M_Step(learning_rate=1.0)) self.orig_params = self.model.get_param_values() model = self.model self.mf_obs = model.e_step.infer(X) self.stats = SufficientStatistics.from_observations(needed_stats=model.m_step.needed_stats(), V=X, **self.mf_obs) self.prob = self.model.expected_log_prob_vhs(self.stats, H_hat=self.mf_obs['H_hat'], S_hat=self.mf_obs['S_hat']) self.X = X self.m = m self.D = D self.N = N finally: config.floatX = self.prev_floatX
'verifies that expected_log_prob_vhs = mean(expected_log_prob_vhs_batch) expected_log_prob_vhs_batch is implemented in terms of expected_energy_vhs so this verifies that as well'
def test_expected_log_prob_vhs_batch_match(self):
scalar = self.model.expected_log_prob_vhs(stats=self.stats, H_hat=self.mf_obs['H_hat'], S_hat=self.mf_obs['S_hat']) batch = self.model.expected_log_prob_vhs_batch(V=self.X, H_hat=self.mf_obs['H_hat'], S_hat=self.mf_obs['S_hat'], var_s0_hat=self.mf_obs['var_s0_hat'], var_s1_hat=self.mf_obs['var_s1_hat']) f = function([], [scalar, batch]) (res1, res2) = f() res2 = res2.mean(dtype='float64') print(res1, res2) assert np.allclose(res1, res2)
'tests that the gradient of the log probability with respect to alpha matches my analytical derivation'
def test_grad_alpha(self):
g = T.grad(self.prob, self.model.alpha, consider_constant=self.mf_obs.values()) mu = self.model.mu alpha = self.model.alpha half = as_floatX(0.5) mean_sq_s = self.stats.d['mean_sq_s'] mean_hs = self.stats.d['mean_hs'] mean_h = self.stats.d['mean_h'] term1 = ((- half) * mean_sq_s) term2 = (mu * mean_hs) term3 = (((- half) * T.sqr(mu)) * mean_h) term4 = (half / alpha) analytical = (((term1 + term2) + term3) + term4) f = function([], (g, analytical)) (gv, av) = f() assert (gv.shape == av.shape) max_diff = np.abs((gv - av)).max() if (max_diff > self.tol): print('gv') print(gv) print('av') print(av) raise Exception(('analytical gradient on alpha deviates from theano gradient on alpha by up to ' + str(max_diff)))
'tests that the gradient of the log probability with respect to W matches my analytical derivation'
def test_grad_W(self):
g = T.grad(self.prob, self.model.W, consider_constant=self.mf_obs.values()) B = self.model.B W = self.model.W mean_hsv = self.stats.d['mean_hsv'] mean_sq_hs = self.stats.d['mean_sq_hs'] mean_HS = (self.mf_obs['H_hat'] * self.mf_obs['S_hat']) m = mean_HS.shape[0] outer_prod = T.dot(mean_HS.T, mean_HS) outer_prod.name = 'outer_prod<from_observations>' outer = (outer_prod / m) mask = T.identity_like(outer) second_hs = (((1.0 - mask) * outer) + alloc_diag(mean_sq_hs)) term1 = (B * mean_hsv).T term2 = ((- B.dimshuffle(0, 'x')) * T.dot(W, second_hs)) analytical = (term1 + term2) f = function([], (g, analytical)) (gv, av) = f() assert (gv.shape == av.shape) max_diff = np.abs((gv - av)).max() if (max_diff > self.tol): print('gv') print(gv) print('av') print(av) raise Exception(('analytical gradient on W deviates from theano gradient on W by up to ' + str(max_diff)))
'tests that the gradient of the kl with respect to h matches my analytical version of it'
def test_d_kl_d_h(self):
model = self.model ip = self.model.e_step X = self.X assert (X.shape[0] == self.m) H = np.cast[config.floatX](self.model.rng.uniform(0.001, 0.999, (self.m, self.N))) S = np.cast[config.floatX](self.model.rng.uniform((-5.0), 5.0, (self.m, self.N))) H_var = T.matrix(name='H_var') H_var.tag.test_value = H S_var = T.matrix(name='S_var') S_var.tag.test_value = S sigma0 = ip.infer_var_s0_hat() Sigma1 = ip.infer_var_s1_hat() mu0 = T.zeros_like(model.mu) trunc_kl = ip.truncated_KL(V=X, obs={'H_hat': H_var, 'S_hat': S_var, 'var_s0_hat': sigma0, 'var_s1_hat': Sigma1}).sum() assert (len(trunc_kl.type.broadcastable) == 0) grad_H = T.grad(trunc_kl, H_var) grad_func = function([H_var, S_var], grad_H) grad_theano = grad_func(H, S) half = as_floatX(0.5) one = as_floatX(1.0) two = as_floatX(2.0) pi = as_floatX(np.pi) e = as_floatX(np.e) mu = self.model.mu alpha = self.model.alpha W = self.model.W B = self.model.B w = self.model.w term1 = T.log(H_var) term2 = (- T.log((one - H_var))) term3 = ((- half) * T.log((((Sigma1 * two) * pi) * e))) term4 = (half * T.log((((sigma0 * two) * pi) * e))) term5 = (- self.model.bias_hid) term6 = (half * (((- sigma0) + Sigma1) + T.sqr(S_var))) term7 = (((- mu) * alpha) * S_var) term8 = ((half * T.sqr(mu)) * alpha) term9 = ((- T.dot((X * self.model.B), self.model.W)) * S_var) term10 = (S_var * T.dot(T.dot((H_var * S_var), (W.T * B)), W)) term11 = (((- w) * T.sqr(S_var)) * H_var) term12 = ((half * (Sigma1 + T.sqr(S_var))) * T.dot(B, T.sqr(W))) analytical = (((((((((((term1 + term2) + term3) + term4) + term5) + term6) + term7) + term8) + term9) + term10) + term11) + term12) grad_analytical = function([H_var, S_var], analytical)(H, S) if (not np.allclose(grad_theano, grad_analytical)): print('grad theano: ', (grad_theano.min(), grad_theano.mean(), grad_theano.max())) print('grad analytical: ', (grad_analytical.min(), grad_analytical.mean(), grad_analytical.max())) ad = np.abs((grad_theano - grad_analytical)) print('abs diff: ', (ad.min(), ad.mean(), ad.max())) assert False
'tests that the gradient of the negative entropy with respect to h matches my analytical version of it'
def test_d_negent_d_h(self):
model = self.model ip = self.model.e_step X = self.X assert (X.shape[0] == self.m) H = np.cast[config.floatX](self.model.rng.uniform(0.001, 0.999, (self.m, self.N))) S = np.cast[config.floatX](self.model.rng.uniform((-5.0), 5.0, (self.m, self.N))) H_var = T.matrix(name='H_var') H_var.tag.test_value = H S_var = T.matrix(name='S_var') S_var.tag.test_value = S sigma0 = ip.infer_var_s0_hat() Sigma1 = ip.infer_var_s1_hat() mu0 = T.zeros_like(model.mu) negent = (- self.model.entropy_hs(H_hat=H_var, var_s0_hat=sigma0, var_s1_hat=Sigma1).sum()) assert (len(negent.type.broadcastable) == 0) grad_H = T.grad(negent, H_var) grad_func = function([H_var, S_var], grad_H, on_unused_input='ignore') grad_theano = grad_func(H, S) half = as_floatX(0.5) one = as_floatX(1.0) two = as_floatX(2.0) pi = as_floatX(np.pi) e = as_floatX(np.e) mu = self.model.mu alpha = self.model.alpha W = self.model.W B = self.model.B w = self.model.w term1 = T.log(H_var) term2 = (- T.log((one - H_var))) term3 = ((- half) * T.log((((Sigma1 * two) * pi) * e))) term4 = (half * T.log((((sigma0 * two) * pi) * e))) analytical = (((term1 + term2) + term3) + term4) grad_analytical = function([H_var, S_var], analytical, on_unused_input='ignore')(H, S) if (not np.allclose(grad_theano, grad_analytical)): print('grad theano: ', (grad_theano.min(), grad_theano.mean(), grad_theano.max())) print('grad analytical: ', (grad_analytical.min(), grad_analytical.mean(), grad_analytical.max())) ad = np.abs((grad_theano - grad_analytical)) print('abs diff: ', (ad.min(), ad.mean(), ad.max())) assert False
'tests that the gradient of the negative entropy of h with respect to \hat{h} matches my analytical version of it'
def test_d_negent_h_d_h(self):
model = self.model ip = self.model.e_step X = self.X assert (X.shape[0] == self.m) H = np.cast[config.floatX](self.model.rng.uniform(0.001, 0.999, (self.m, self.N))) S = np.cast[config.floatX](self.model.rng.uniform((-5.0), 5.0, (self.m, self.N))) H_var = T.matrix(name='H_var') H_var.tag.test_value = H S_var = T.matrix(name='S_var') S_var.tag.test_value = S sigma0 = ip.infer_var_s0_hat() Sigma1 = ip.infer_var_s1_hat() mu0 = T.zeros_like(model.mu) negent = (- self.model.entropy_h(H_hat=H_var).sum()) assert (len(negent.type.broadcastable) == 0) grad_H = T.grad(negent, H_var) grad_func = function([H_var, S_var], grad_H, on_unused_input='ignore') grad_theano = grad_func(H, S) half = as_floatX(0.5) one = as_floatX(1.0) two = as_floatX(2.0) pi = as_floatX(np.pi) e = as_floatX(np.e) mu = self.model.mu alpha = self.model.alpha W = self.model.W B = self.model.B w = self.model.w term1 = T.log(H_var) term2 = (- T.log((one - H_var))) analytical = (term1 + term2) grad_analytical = function([H_var, S_var], analytical, on_unused_input='ignore')(H, S) if (not np.allclose(grad_theano, grad_analytical)): print('grad theano: ', (grad_theano.min(), grad_theano.mean(), grad_theano.max())) print('grad analytical: ', (grad_analytical.min(), grad_analytical.mean(), grad_analytical.max())) ad = np.abs((grad_theano - grad_analytical)) print('abs diff: ', (ad.min(), ad.mean(), ad.max())) assert False
'tests that the gradient of the expected energy with respect to h matches my analytical version of it'
def test_d_ee_d_h(self):
model = self.model ip = self.model.e_step X = self.X assert (X.shape[0] == self.m) H = np.cast[config.floatX](self.model.rng.uniform(0.001, 0.999, (self.m, self.N))) S = np.cast[config.floatX](self.model.rng.uniform((-5.0), 5.0, (self.m, self.N))) H_var = T.matrix(name='H_var') H_var.tag.test_value = H S_var = T.matrix(name='S_var') S_var.tag.test_value = S sigma0 = ip.infer_var_s0_hat() Sigma1 = ip.infer_var_s1_hat() mu0 = T.zeros_like(model.mu) ee = self.model.expected_energy_vhs(V=X, H_hat=H_var, S_hat=S_var, var_s0_hat=sigma0, var_s1_hat=Sigma1).sum() assert (len(ee.type.broadcastable) == 0) grad_H = T.grad(ee, H_var) grad_func = function([H_var, S_var], grad_H) grad_theano = grad_func(H, S) half = as_floatX(0.5) one = as_floatX(1.0) two = as_floatX(2.0) pi = as_floatX(np.pi) e = as_floatX(np.e) mu = self.model.mu alpha = self.model.alpha W = self.model.W B = self.model.B w = self.model.w term1 = (- self.model.bias_hid) term2 = (half * (((- sigma0) + Sigma1) + T.sqr(S_var))) term3 = (((- mu) * alpha) * S_var) term4 = ((half * T.sqr(mu)) * alpha) term5 = ((- T.dot((X * self.model.B), self.model.W)) * S_var) term6 = (S_var * T.dot(T.dot((H_var * S_var), (W.T * B)), W)) term7 = (((- w) * T.sqr(S_var)) * H_var) term8 = ((half * (Sigma1 + T.sqr(S_var))) * T.dot(B, T.sqr(W))) analytical = (((((((term1 + term2) + term3) + term4) + term5) + term6) + term7) + term8) grad_analytical = function([H_var, S_var], analytical, on_unused_input='ignore')(H, S) if (not np.allclose(grad_theano, grad_analytical)): print('grad theano: ', (grad_theano.min(), grad_theano.mean(), grad_theano.max())) print('grad analytical: ', (grad_analytical.min(), grad_analytical.mean(), grad_analytical.max())) ad = np.abs((grad_theano - grad_analytical)) print('abs diff: ', (ad.min(), ad.mean(), ad.max())) assert False
'Set up test for DenseMulticlassSVM. Imports DenseMulticlassSVM if available, skips the test otherwise.'
def setUp(self):
global DenseMulticlassSVM skip_if_no_sklearn() skip_if_no_data() import pylearn2.models.svm DenseMulticlassSVM = pylearn2.models.svm.DenseMulticlassSVM
'Test DenseMulticlassSVM.decision_function.'
def test_decision_function(self):
dataset = MNIST(which_set='train') X = dataset.X[0:20, :] y = dataset.y[0:20] for i in xrange(10): assert ((y == i).sum() > 0) model = DenseMulticlassSVM(kernel='poly', C=1.0).fit(X, y) f = model.decision_function(X) print(f) yhat_f = np.argmax(f, axis=1) yhat = np.cast[yhat_f.dtype](model.predict(X)) print(yhat_f) print(yhat) assert ((yhat_f != yhat).sum() == 0)
'Get the dictionary of updates for the sampler\'s persistent state at each step. Returns updates : dict Dictionary with shared variable instances as keys and symbolic expressions indicating how they should be updated as values. Notes In the `Sampler` base class, this is simply a stub.'
def updates(self):
raise NotImplementedError()
'Get the dictionary of updates for the sampler\'s persistent state at each step. Parameters particles_clip : WRITEME Returns updates : dict Dictionary with shared variable instances as keys and symbolic expressions indicating how they should be updated as values.'
def updates(self, particles_clip=None):
steps = self.steps particles = self.particles for i in xrange(steps): (particles, _locals) = self.rbm.gibbs_step_for_v(particles, self.s_rng) assert (particles.type.dtype == self.particles.type.dtype) if (self.particles_clip is not None): (p_min, p_max) = self.particles_clip dtype = particles.dtype p_min = tensor.as_tensor_variable(p_min) if (p_min.dtype != dtype): p_min = tensor.cast(p_min, dtype) p_max = tensor.as_tensor_variable(p_max) if (p_max.dtype != dtype): p_max = tensor.cast(p_max, dtype) particles = tensor.clip(particles, p_min, p_max) if (not hasattr(self.rbm, 'h_sample')): self.rbm.h_sample = sharedX(numpy.zeros((0, 0)), 'h_sample') return {self.particles: particles, self.rbm.h_sample: _locals['h_mean']}
'.. todo:: WRITEME'
def get_default_cost(self):
raise NotImplementedError('The RBM class predates the current Cost-based training algorithms (SGD and BGD). To train the RBM with PCD, use DefaultTrainingAlgorithm rather than SGD or BGD. Some RBM subclassess may also be trained with SGD or BGD by using the Cost classes defined in pylearn2.costs.ebm_estimation. Note that it is also possible to make an RBM by allocating a DBM with only one hidden layer. The DBM class is newer and supports training with SGD / BGD. In the long run we should remove the old RBM class and turn it into a wrapper around the DBM class that makes a 1-layer DBM.')