INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Use this method to iterate through a user s dialogs sequentially.
def iter_dialogs( self, offset_date: int = 0, limit: int = 0 ) -> Generator["pyrogram.Dialog", None, None]: """Use this method to iterate through a user's dialogs sequentially. This convenience method does the same as repeatedly calling :meth:`get_dialogs` in a loop, thus sa...
A simple method for testing your authorization. Requires no parameters.
def get_me(self) -> "pyrogram.User": """A simple method for testing your authorization. Requires no parameters. Returns: Basic information about the user or bot in form of a :obj:`User` object Raises: :class:`RPCError <pyrogram.RPCError>` in case of a Telegram RPC error...
Use this method to generate a new invite link for a chat ; any previously generated link is revoked.
def export_chat_invite_link( self, chat_id: Union[int, str] ) -> str: """Use this method to generate a new invite link for a chat; any previously generated link is revoked. You must be an administrator in the chat for this to work and have the appropriate admin rights. Args...
Use this method to turn off the Two - Step Verification security feature ( Cloud Password ) on your account.
def remove_cloud_password( self, password: str ) -> bool: """Use this method to turn off the Two-Step Verification security feature (Cloud Password) on your account. Args: password (``str``): Your current password. Returns: True on su...
Use this method to send a new poll.
def send_poll( self, chat_id: Union[int, str], question: str, options: List[str], disable_notification: bool = None, reply_to_message_id: int = None, reply_markup: Union[ "pyrogram.InlineKeyboardMarkup", "pyrogram.ReplyKeyboardMarkup", ...
Use this method to delete contacts from your Telegram address book.
def delete_contacts( self, ids: List[int] ): """Use this method to delete contacts from your Telegram address book. Args: ids (List of ``int``): A list of unique identifiers for the target users. Can be an ID (int), a username (string) or ...
Use this method to send a group of photos or videos as an album.
def send_media_group( self, chat_id: Union[int, str], media: List[Union["pyrogram.InputMediaPhoto", "pyrogram.InputMediaVideo"]], disable_notification: bool = None, reply_to_message_id: int = None ): """Use this method to send a group of photos or videos as an album. ...
Use this method to set the score of the specified user in a game.
def set_game_score( self, user_id: Union[int, str], score: int, force: bool = None, disable_edit_message: bool = None, chat_id: Union[int, str] = None, message_id: int = None ): # inline_message_id: str = None): TODO Add inline_message_id """U...
Use this method to pin a message in a group channel or your own chat. You must be an administrator in the chat for this to work and must have the can_pin_messages admin right in the supergroup or can_edit_messages admin right in the channel.
def pin_chat_message( self, chat_id: Union[int, str], message_id: int, disable_notification: bool = None ) -> bool: """Use this method to pin a message in a group, channel or your own chat. You must be an administrator in the chat for this to work and must have the "c...
Use this method to kick a user from a group a supergroup or a channel. In the case of supergroups and channels the user will not be able to return to the group on their own using invite links etc. unless unbanned first. You must be an administrator in the chat for this to work and must have the appropriate admin rights...
def kick_chat_member( self, chat_id: Union[int, str], user_id: Union[int, str], until_date: int = 0 ) -> Union["pyrogram.Message", bool]: """Use this method to kick a user from a group, a supergroup or a channel. In the case of supergroups and channels, the user will ...
Use this method to forward messages of any kind.
def forward_messages( self, chat_id: Union[int, str], from_chat_id: Union[int, str], message_ids: Iterable[int], disable_notification: bool = None, as_copy: bool = False, remove_caption: bool = False ) -> "pyrogram.Messages": """Use this method to forw...
Use this method to download the media from a message.
def download_media( self, message: Union["pyrogram.Message", str], file_name: str = "", block: bool = True, progress: callable = None, progress_args: tuple = () ) -> Union[str, None]: """Use this method to download the media from a message. Args: ...
Use this method to send text messages.
def send_message( self, chat_id: Union[int, str], text: str, parse_mode: str = "", disable_web_page_preview: bool = None, disable_notification: bool = None, reply_to_message_id: int = None, reply_markup: Union[ "pyrogram.InlineKeyboardMarkup", ...
Use this method to edit audio document photo or video messages.
def edit_message_media( self, chat_id: Union[int, str], message_id: int, media: InputMedia, reply_markup: "pyrogram.InlineKeyboardMarkup" = None ) -> "pyrogram.Message": """Use this method to edit audio, document, photo, or video messages. If a message is a p...
Use this method to enable the Two - Step Verification security feature ( Cloud Password ) on your account.
def enable_cloud_password( self, password: str, hint: str = "", email: str = None ) -> bool: """Use this method to enable the Two-Step Verification security feature (Cloud Password) on your account. This password will be asked when you log-in on a new device in addit...
Use this method to get the preview of a chat using the invite link.
def get_chat_preview( self, invite_link: str ): """Use this method to get the preview of a chat using the invite link. This method only returns a chat preview, if you want to join a chat use :meth:`join_chat` Args: invite_link (``str``): Unique i...
Use this method to change the title of a chat. Titles can t be changed for private chats. You must be an administrator in the chat for this to work and must have the appropriate admin rights.
def set_chat_title( self, chat_id: Union[int, str], title: str ) -> bool: """Use this method to change the title of a chat. Titles can't be changed for private chats. You must be an administrator in the chat for this to work and must have the appropriate admin rights....
Use this method to get data for high score tables.
def get_game_high_scores( self, user_id: Union[int, str], chat_id: Union[int, str], message_id: int = None ): """Use this method to get data for high score tables. Args: user_id (``int`` | ``str``): Unique identifier (int) or username (str...
Use this method to unpin a message in a group channel or your own chat. You must be an administrator in the chat for this to work and must have the can_pin_messages admin right in the supergroup or can_edit_messages admin right in the channel.
def unpin_chat_message( self, chat_id: Union[int, str] ) -> bool: """Use this method to unpin a message in a group, channel or your own chat. You must be an administrator in the chat for this to work and must have the "can_pin_messages" admin right in the supergroup or "can_e...
Bound method * answer * of: obj: CallbackQuery <pyrogram. CallbackQuery >.
def answer(self, text: str = None, show_alert: bool = None, url: str = None, cache_time: int = 0): """Bound method *answer* of :obj:`CallbackQuery <pyrogram.CallbackQuery>`. Use this method as a shortcut for: .. code-block:: python client.answer_callback_query( cal...
Use this method to get up to date information about the chat. Information include current name of the user for one - on - one conversations current username of a user group or channel etc.
def get_chat( self, chat_id: Union[int, str] ) -> "pyrogram.Chat": """Use this method to get up to date information about the chat. Information include current name of the user for one-on-one conversations, current username of a user, group or channel, etc. Args: ...
Use this method to send answers to callback queries sent from inline keyboards. The answer will be displayed to the user as a notification at the top of the chat screen or as an alert.
def answer_callback_query( self, callback_query_id: str, text: str = None, show_alert: bool = None, url: str = None, cache_time: int = 0 ): """Use this method to send answers to callback queries sent from inline keyboards. The answer will be displayed ...
Use this method to create a Filter.
def create(name: str, func: callable, **kwargs) -> type: """Use this method to create a Filter. Custom filters give you extra control over which updates are allowed or not to be processed by your handlers. Args: name (``str``): Your filter's name. Can be anything you like. fun...
Filter commands i. e.: text messages starting with/ or any other custom prefix.
def command( commands: str or list, prefix: str or list = "/", separator: str = " ", case_sensitive: bool = False ): """Filter commands, i.e.: text messages starting with "/" or any other custom prefix. Args: commands (``str`` | ``list``): ...
Filter messages that match a given RegEx pattern.
def regex(pattern, flags: int = 0): """Filter messages that match a given RegEx pattern. Args: pattern (``str``): The RegEx pattern as string, it will be applied to the text of a message. When a pattern matches, all the `Match Objects <https://docs.python.org...
Use this method to change your Two - Step Verification password ( Cloud Password ) with a new one.
def change_cloud_password( self, current_password: str, new_password: str, new_hint: str = "" ) -> bool: """Use this method to change your Two-Step Verification password (Cloud Password) with a new one. Args: current_password (``str``): Yo...
Use this method to get information about one member of a chat.
def get_chat_member( self, chat_id: Union[int, str], user_id: Union[int, str] ) -> "pyrogram.ChatMember": """Use this method to get information about one member of a chat. Args: chat_id (``int`` | ``str``): Unique identifier (int) or username (str...
Use this method to iterate through the members of a chat sequentially.
def iter_chat_members( self, chat_id: Union[int, str], limit: int = 0, query: str = "", filter: str = Filters.ALL ) -> Generator["pyrogram.ChatMember", None, None]: """Use this method to iterate through the members of a chat sequentially. This convenience met...
Check that the argument is a type and return it ( internal helper ).
def _type_check(arg, msg): """Check that the argument is a type, and return it (internal helper). As a special case, accept None and return type(None) instead. Also, _TypeAlias instances (e.g. Match, Pattern) are acceptable. The msg argument is a human-readable error message, e.g. "Union[arg,...
Return the repr () of an object special - casing types ( internal helper ).
def _type_repr(obj): """Return the repr() of an object, special-casing types (internal helper). If obj is a type, we return a shorter version than the default type.__repr__, based on the module and qualified name, which is typically enough to uniquely identify a type. For everything else, we fall ...
An internal helper function: replace arg if it is a type variable found in tvars with corresponding substitution from args or with corresponding substitution sub - tree if arg is a generic type.
def _replace_arg(arg, tvars, args): """An internal helper function: replace arg if it is a type variable found in tvars with corresponding substitution from args or with corresponding substitution sub-tree if arg is a generic type. """ if tvars is None: tvars = [] if hasattr(arg, '_subs...
An internal helper function: calculate substitution tree for generic cls after replacing its type parameters with substitutions in tvars - > args ( if any ). Repeat the same following __origin__ s.
def _subs_tree(cls, tvars=None, args=None): """An internal helper function: calculate substitution tree for generic cls after replacing its type parameters with substitutions in tvars -> args (if any). Repeat the same following __origin__'s. Return a list of arguments with all possible substitution...
An internal helper for Union creation and substitution: flatten Union s among parameters then remove duplicates and strict subclasses.
def _remove_dups_flatten(parameters): """An internal helper for Union creation and substitution: flatten Union's among parameters, then remove duplicates and strict subclasses. """ # Flatten out Union[Union[...], ...]. params = [] for p in parameters: if isinstance(p, _Union) and p.__or...
Internal wrapper caching __getitem__ of generic types with a fallback to original function for non - hashable arguments.
def _tp_cache(func): """Internal wrapper caching __getitem__ of generic types with a fallback to original function for non-hashable arguments. """ cached = functools.lru_cache()(func) _cleanups.append(cached.cache_clear) @functools.wraps(func) def inner(*args, **kwds): try: ...
Construct a __subclasshook__ callable that incorporates the associated __extra__ class in subclass checks performed against cls.
def _make_subclasshook(cls): """Construct a __subclasshook__ callable that incorporates the associated __extra__ class in subclass checks performed against cls. """ if isinstance(cls.__extra__, abc.ABCMeta): # The logic mirrors that of ABCMeta.__subclasscheck__. # Registered classes ...
Internal helper: copy class __dict__ and clean slots class variables. ( They will be re - created if necessary by normal class machinery. )
def _no_slots_copy(dct): """Internal helper: copy class __dict__ and clean slots class variables. (They will be re-created if necessary by normal class machinery.) """ dict_copy = dict(dct) if '__slots__' in dict_copy: for slot in dict_copy['__slots__']: dict_copy.pop(slot, None)...
Internal helper to extract the default arguments by name.
def _get_defaults(func): """Internal helper to extract the default arguments, by name.""" try: code = func.__code__ except AttributeError: # Some built-in functions don't have __code__, __defaults__, etc. return {} pos_count = code.co_argcount arg_names = code.co_varnames ...
Return type hints for an object.
def get_type_hints(obj, globalns=None, localns=None): """Return type hints for an object. This is often the same as obj.__annotations__, but it handles forward references encoded as string literals, and if necessary adds Optional[t] if a default value equal to None is set. The argument may be a mo...
Decorator to indicate that annotations are not type hints.
def no_type_check(arg): """Decorator to indicate that annotations are not type hints. The argument must be a class or function; if it is a class, it applies recursively to all methods and classes defined in that class (but not to methods defined in its superclasses or subclasses). This mutates the...
Decorator to give another decorator the @no_type_check effect.
def no_type_check_decorator(decorator): """Decorator to give another decorator the @no_type_check effect. This wraps the decorator with something that wraps the decorated function in @no_type_check. """ @functools.wraps(decorator) def wrapped_decorator(*args, **kwds): func = decorator(...
NewType creates simple unique types with almost zero runtime overhead. NewType ( name tp ) is considered a subtype of tp by static type checkers. At runtime NewType ( name tp ) returns a dummy function that simply returns its argument. Usage::
def NewType(name, tp): """NewType creates simple unique types with almost zero runtime overhead. NewType(name, tp) is considered a subtype of tp by static type checkers. At runtime, NewType(name, tp) returns a dummy function that simply returns its argument. Usage:: UserId = NewType('UserId', i...
Use this method to get one or more messages that belong to a specific chat. You can retrieve up to 200 messages at once.
def get_messages( self, chat_id: Union[int, str], message_ids: Union[int, Iterable[int]] = None, reply_to_message_ids: Union[int, Iterable[int]] = None, replies: int = 1 ) -> Union["pyrogram.Message", "pyrogram.Messages"]: """Use this method to get one or more message...
Use this method to send information about a venue.
def send_venue( self, chat_id: Union[int, str], latitude: float, longitude: float, title: str, address: str, foursquare_id: str = "", foursquare_type: str = "", disable_notification: bool = None, reply_to_message_id: int = None, rep...
Use this method to get bot results via inline queries. You can then send a result using: obj: send_inline_bot_result <pyrogram. Client. send_inline_bot_result >
def get_inline_bot_results( self, bot: Union[int, str], query: str, offset: str = "", latitude: float = None, longitude: float = None ): """Use this method to get bot results via inline queries. You can then send a result using :obj:`send_inline_bot_re...
Use this method to join a group chat or channel.
def join_chat( self, chat_id: str ): """Use this method to join a group chat or channel. Args: chat_id (``str``): Unique identifier for the target chat in form of a *t.me/joinchat/* link or username of the target channel/supergroup (in the...
Use this method to get contacts from your Telegram address book.
def get_contacts(self): """Use this method to get contacts from your Telegram address book. Returns: On success, a list of :obj:`User` objects is returned. Raises: :class:`RPCError <pyrogram.RPCError>` in case of a Telegram RPC error. """ while True: ...
Use this method to update a channel or a supergroup username. To update your own username ( for users only not bots ) you can use: meth: update_username.
def update_chat_username( self, chat_id: Union[int, str], username: Union[str, None] ) -> bool: """Use this method to update a channel or a supergroup username. To update your own username (for users only, not bots) you can use :meth:`update_username`. Args:...
Use this method to send a game.
def send_game( self, chat_id: Union[int, str], game_short_name: str, disable_notification: bool = None, reply_to_message_id: int = None, reply_markup: Union[ "pyrogram.InlineKeyboardMarkup", "pyrogram.ReplyKeyboardMarkup", "pyrogram.Rep...
Use this method to edit only the reply markup of messages sent by the bot or via the bot ( for inline bots ).
def edit_message_reply_markup( self, chat_id: Union[int, str], message_id: int, reply_markup: "pyrogram.InlineKeyboardMarkup" = None ) -> "pyrogram.Message": """Use this method to edit only the reply markup of messages sent by the bot or via the bot (for inline bots). ...
Use this method to delete your own profile photos.
def delete_user_profile_photos( self, id: Union[str, List[str]] ) -> bool: """Use this method to delete your own profile photos. Args: id (``str`` | ``list``): A single :obj:`Photo <pyrogram.Photo>` id as string or multiple ids as list of strings for dele...
Bound method * answer * of: obj: InlineQuery <pyrogram. InlineQuery >.
def answer( self, results: List[InlineQueryResult], cache_time: int = 300, is_personal: bool = None, next_offset: str = "", switch_pm_text: str = "", switch_pm_parameter: str = "" ): """Bound method *answer* of :obj:`InlineQuery <pyrogram.InlineQuery>`...
Use this method to set a new profile photo for the chat. Photos can t be changed for private chats. You must be an administrator in the chat for this to work and must have the appropriate admin rights.
def set_chat_photo( self, chat_id: Union[int, str], photo: str ) -> bool: """Use this method to set a new profile photo for the chat. Photos can't be changed for private chats. You must be an administrator in the chat for this to work and must have the appropriate adm...
Use this method to get a chunk of the members list of a chat.
def get_chat_members( self, chat_id: Union[int, str], offset: int = 0, limit: int = 200, query: str = "", filter: str = Filters.ALL ) -> "pyrogram.ChatMembers": """Use this method to get a chunk of the members list of a chat. You can get up to 200 cha...
Use this method to leave a group chat or channel.
def leave_chat( self, chat_id: Union[int, str], delete: bool = False ): """Use this method to leave a group chat or channel. Args: chat_id (``int`` | ``str``): Unique identifier for the target chat or username of the target channel/supergroup ...
grouper ( 3 abcdefg x ) -- > ( a b c ) ( d e f ) ( g x x )
def grouper(n, iterable, padvalue=None): "grouper(3, 'abcdefg', 'x') --> ('a','b','c'), ('d','e','f'), ('g','x','x')" return zip_longest(*[iter(iterable)]*n, fillvalue=padvalue)
Returns a truncated random walk.
def random_walk(self, path_length, alpha=0, rand=random.Random(), start=None): """ Returns a truncated random walk. path_length: Length of the random walk. alpha: probability of restarts. start: the start node of the random walk. """ G = self if start: path = [start] e...
Counts the word frequences in a list of sentences.
def count_words(file): """ Counts the word frequences in a list of sentences. Note: This is a helper function for parallel execution of `Vocabulary.from_text` method. """ c = Counter() with open(file, 'r') as f: for l in f: words = l.strip().split() c.update(words) return c
Generates the random walks which will be used as the skip - gram input.: return: List of walks. Each walk is a list of nodes.
def parallel_generate_walks(d_graph, global_walk_length, num_walks, cpu_num, sampling_strategy=None, num_walks_key=None, walk_length_key=None, neighbors_key=None, probabilities_key=None, first_travel_key=None, quiet=False): """ Generates the random walks w...
Generated a KeyedVectors instance with all: return:
def as_keyed_vectors(self): """ Generated a KeyedVectors instance with all :return: """ edge_generator = combinations_with_replacement(self.kv.index2word, r=2) if not self.quiet: vocab_size = len(self.kv.vocab) total_size = reduce(lambda x, y: x ...
Precomputes transition probabilities for each node.
def _precompute_probabilities(self): """ Precomputes transition probabilities for each node. """ d_graph = self.d_graph first_travel_done = set() nodes_generator = self.graph.nodes() if self.quiet \ else tqdm(self.graph.nodes(), desc='Computing transition pr...
Generates the random walks which will be used as the skip - gram input.: return: List of walks. Each walk is a list of nodes.
def _generate_walks(self): """ Generates the random walks which will be used as the skip-gram input. :return: List of walks. Each walk is a list of nodes. """ flatten = lambda l: [item for sublist in l for item in sublist] # Split num_walks for each worker num_w...
Creates the embeddings using gensim s Word2Vec.: param skip_gram_params: Parameteres for gensim. models. Word2Vec - do not supply size it is taken from the Node2Vec dimensions parameter: type skip_gram_params: dict: return: A gensim word2vec model
def fit(self, **skip_gram_params): """ Creates the embeddings using gensim's Word2Vec. :param skip_gram_params: Parameteres for gensim.models.Word2Vec - do not supply 'size' it is taken from the Node2Vec 'dimensions' parameter :type skip_gram_params: dict :return: A gensim word2v...
An example of using the query_user_info method: param twitter_user: the twitter user to capture user data: return: twitter_user_data: returns a dictionary of twitter user data
def get_user_info(twitter_user): """ An example of using the query_user_info method :param twitter_user: the twitter user to capture user data :return: twitter_user_data: returns a dictionary of twitter user data """ user_info = query_user_info(user=twitter_user) twitter_user_data = {} t...
Returns tweets from the given URL.
def query_single_page(query, lang, pos, retry=50, from_user=False): """ Returns tweets from the given URL. :param query: The query parameter of the query url :param lang: The language parameter of the query url :param pos: The query url parameter that determines where to start looking :param re...
Queries twitter for all the tweets you want! It will load all pages it gets from twitter. However twitter might out of a sudden stop serving new pages in that case use the query_tweets method.
def query_tweets_once_generator(query, limit=None, lang='', pos=None): """ Queries twitter for all the tweets you want! It will load all pages it gets from twitter. However, twitter might out of a sudden stop serving new pages, in that case, use the `query_tweets` method. Note that this function ca...
Returns the scraped user data from a twitter user page.
def query_user_page(url, retry=10): """ Returns the scraped user data from a twitter user page. :param url: The URL to get the twitter user info from (url contains the user page) :param retry: Number of retries if something goes wrong. :return: Returns the scraped user data from a twitter user page...
Returns the scraped user data from a twitter user page.
def query_user_info(user): """ Returns the scraped user data from a twitter user page. :param user: the twitter user to web scrape its twitter page info """ try: user_info = query_user_page(INIT_URL_USER.format(u=user)) if user_info: logger.info(f"Got user information...
Returns the scraped user data from a twitter user page.
def from_soup(self, tag_prof_header, tag_prof_nav): """ Returns the scraped user data from a twitter user page. :param tag_prof_header: captures the left hand part of user info :param tag_prof_nav: captures the upper part of user info :return: Returns a User object with captured...
: param link_f: latent variables link ( f ): type link_f: Nx1 array: param y: data: type y: Nx1 array: param Y_metadata: includes censoring information in dictionary key censored: returns: likelihood evaluated for this point: rtype: float
def pdf_link(self, link_f, y, Y_metadata=None): """ :param link_f: latent variables link(f) :type link_f: Nx1 array :param y: data :type y: Nx1 array :param Y_metadata: includes censoring information in dictionary key 'censored' :returns: likelihood evaluated for ...
: param link_f: latent variables ( link ( f )): type link_f: Nx1 array: param y: data: type y: Nx1 array: param Y_metadata: includes censoring information in dictionary key censored: returns: likelihood evaluated for this point: rtype: float
def logpdf_link(self, link_f, y, Y_metadata=None): """ :param link_f: latent variables (link(f)) :type link_f: Nx1 array :param y: data :type y: Nx1 array :param Y_metadata: includes censoring information in dictionary key 'censored' :returns: likelihood evaluated...
derivative of logpdf wrt link_f param.. math::
def dlogpdf_dlink(self, link_f, y, Y_metadata=None): """ derivative of logpdf wrt link_f param .. math:: :param link_f: latent variables link(f) :type link_f: Nx1 array :param y: data :type y: Nx1 array :param Y_metadata: includes censoring information in...
Gradient of the log - likelihood function at y given f w. r. t shape parameter
def d3logpdf_dlink3(self, link_f, y, Y_metadata=None): """ Gradient of the log-likelihood function at y given f, w.r.t shape parameter .. math:: :param inv_link_f: latent variables link(f) :type inv_link_f: Nx1 array :param y: data :type y: Nx1 array :pa...
: param link_f: latent variables link ( f ): type link_f: Nx1 array: param y: data: type y: Nx1 array: param Y_metadata: Y_metadata not used in gaussian: returns: derivative of log likelihood evaluated at points link ( f ) w. r. t variance parameter: rtype: Nx1 array
def dlogpdf_dlink_dvar(self, link_f, y, Y_metadata=None): """ :param link_f: latent variables link(f) :type link_f: Nx1 array :param y: data :type y: Nx1 array :param Y_metadata: Y_metadata not used in gaussian :returns: derivative of log likelihood evaluated at p...
: param link_f: latent variables link ( f ): type link_f: Nx1 array: param y: data: type y: Nx1 array: param Y_metadata: Y_metadata not used in gaussian: returns: derivative of log likelihood evaluated at points link ( f ) w. r. t variance parameter: rtype: Nx1 array
def d2logpdf_dlink2_dvar(self, link_f, y, Y_metadata=None): """ :param link_f: latent variables link(f) :type link_f: Nx1 array :param y: data :type y: Nx1 array :param Y_metadata: Y_metadata not used in gaussian :returns: derivative of log likelihood evaluated at...
Returns a set of samples of observations based on a given value of the latent variable.
def samples(self, gp, Y_metadata=None): """ Returns a set of samples of observations based on a given value of the latent variable. :param gp: latent variable """ orig_shape = gp.shape gp = gp.flatten()
Check if the values of the observations correspond to the values assumed by the likelihood function.
def _preprocess_values(self, Y): """ Check if the values of the observations correspond to the values assumed by the likelihood function. ..Note:: Binary classification algorithm works better with classes {-1, 1} """ Y_prep = Y.copy() Y1 = Y[Y.flatten()==1].size ...
Moments match of the marginal approximation in EP algorithm
def moments_match_ep(self, Y_i, tau_i, v_i, Y_metadata_i=None): """ Moments match of the marginal approximation in EP algorithm :param i: number of observation (int) :param tau_i: precision of the cavity distribution (float) :param v_i: mean/variance of the cavity distribution (...
Likelihood function given inverse link of f.
def pdf_link(self, inv_link_f, y, Y_metadata=None): """ Likelihood function given inverse link of f. .. math:: p(y_{i}|\\lambda(f_{i})) = \\lambda(f_{i})^{y_{i}}(1-f_{i})^{1-y_{i}} :param inv_link_f: latent variables inverse link of f. :type inv_link_f: Nx1 array ...
Log Likelihood function given inverse link of f.
def logpdf_link(self, inv_link_f, y, Y_metadata=None): """ Log Likelihood function given inverse link of f. .. math:: \\ln p(y_{i}|\\lambda(f_{i})) = y_{i}\\log\\lambda(f_{i}) + (1-y_{i})\\log (1-f_{i}) :param inv_link_f: latent variables inverse link of f. :type in...
Gradient of the pdf at y given inverse link of f w. r. t inverse link of f.
def dlogpdf_dlink(self, inv_link_f, y, Y_metadata=None): """ Gradient of the pdf at y, given inverse link of f w.r.t inverse link of f. .. math:: \\frac{d\\ln p(y_{i}|\\lambda(f_{i}))}{d\\lambda(f)} = \\frac{y_{i}}{\\lambda(f_{i})} - \\frac{(1 - y_{i})}{(1 - \\lambda(f_{i}))} ...
Hessian at y given inv_link_f w. r. t inv_link_f the hessian will be 0 unless i == j i. e. second derivative logpdf at y given inverse link of f_i and inverse link of f_j w. r. t inverse link of f_i and inverse link of f_j.
def d2logpdf_dlink2(self, inv_link_f, y, Y_metadata=None): """ Hessian at y, given inv_link_f, w.r.t inv_link_f the hessian will be 0 unless i == j i.e. second derivative logpdf at y given inverse link of f_i and inverse link of f_j w.r.t inverse link of f_i and inverse link of f_j. ....
Third order derivative log - likelihood function at y given inverse link of f w. r. t inverse link of f
def d3logpdf_dlink3(self, inv_link_f, y, Y_metadata=None): """ Third order derivative log-likelihood function at y given inverse link of f w.r.t inverse link of f .. math:: \\frac{d^{3} \\ln p(y_{i}|\\lambda(f_{i}))}{d^{3}\\lambda(f)} = \\frac{2y_{i}}{\\lambda(f)^{3}} - \\frac{2(1-y...
Get the quantiles of the binary labels ( Bernoulli draws ). all the quantiles must be either 0 or 1 since those are the only values the draw can take!
def predictive_quantiles(self, mu, var, quantiles, Y_metadata=None): """ Get the "quantiles" of the binary labels (Bernoulli draws). all the quantiles must be either 0 or 1, since those are the only values the draw can take! """ p = self.predictive_mean(mu, var) r...
Returns a set of samples of observations based on a given value of the latent variable.
def samples(self, gp, Y_metadata=None): """ Returns a set of samples of observations based on a given value of the latent variable. :param gp: latent variable """ orig_shape = gp.shape gp = gp.flatten() ns = np.ones_like(gp, dtype=int) Ysim = np.random.bi...
make all of the subplots have the same limits turn off unnecessary ticks
def align_subplots(N,M,xlim=None, ylim=None): """make all of the subplots have the same limits, turn off unnecessary ticks""" #find sensible xlim,ylim if xlim is None: xlim = [np.inf,-np.inf] for i in range(N*M): plt.subplot(N,M,i+1) xlim[0] = min(xlim[0],plt.xlim()[0...
Make all of the axes in the array hae the same limits turn off unnecessary ticks use plt. subplots () to get an array of axes
def align_subplot_array(axes,xlim=None, ylim=None): """ Make all of the axes in the array hae the same limits, turn off unnecessary ticks use plt.subplots() to get an array of axes """ #find sensible xlim,ylim if xlim is None: xlim = [np.inf,-np.inf] for ax in axes.flatten(): ...
Internal helper function for making plots returns a set of input values to plot as well as lower and upper limits
def x_frame2D(X,plot_limits=None,resolution=None): """ Internal helper function for making plots, returns a set of input values to plot as well as lower and upper limits """ assert X.shape[1] ==2, "x_frame2D is defined for two-dimensional inputs" if plot_limits is None: xmin,xmax = X.min(0),...
Creates an instance of a Gamma Prior by specifying the Expected value ( s ) and Variance ( s ) of the distribution.
def from_EV(E, V): """ Creates an instance of a Gamma Prior by specifying the Expected value(s) and Variance(s) of the distribution. :param E: expected value :param V: variance """ a = np.square(E) / V b = E / V return Gamma(a, b)
Returns a set of samples of observations based on a given value of the latent variable.
def samples(self, gp, Y_metadata): """ Returns a set of samples of observations based on a given value of the latent variable. :param gp: latent variable """ N1, N2 = gp.shape Ysim = np.zeros((N1,N2)) ind = Y_metadata['output_index'].flatten() for j in np...
Compute psi - statistics for ss - linear kernel
def psicomputations(variance, Z, variational_posterior, return_psi2_n=False): """ Compute psi-statistics for ss-linear kernel """ # here are the "statistics" for psi0, psi1 and psi2 # Produced intermediate results: # psi0 N # psi1 NxM # psi2 MxM mu = variational_posterior.me...
Z - MxQ mu - NxQ S - NxQ gamma - NxQ
def _psi2computations(dL_dpsi2, variance, Z, mu, S): """ Z - MxQ mu - NxQ S - NxQ gamma - NxQ """ # here are the "statistics" for psi1 and psi2 # Produced intermediate results: # _psi2_dvariance Q # _psi2_dZ MxQ # _psi2_dmu NxQ # _psi2_dS ...
I ve used the fact that we call this method for K_ff when finding the covariance as a hack so I know if I should return K_ff or K_xx. In this case we re returning K_ff!! $K_ { ff } ^ { post } = K_ { ff } - K_ { fx } K_ { xx } ^ { - 1 } K_ { xf } $
def Kdiag(self, X): """I've used the fact that we call this method for K_ff when finding the covariance as a hack so I know if I should return K_ff or K_xx. In this case we're returning K_ff!! $K_{ff}^{post} = K_{ff} - K_{fx} K_{xx}^{-1} K_{xf}$""" K_ff = np.zeros(X.shape[0]) for...
Convenience function to add an offset column to phi. You can use this function to add an offset ( bias on y axis ) to phi in your custom self. _phi ( X ).
def concatenate_offset(self, X): """ Convenience function to add an offset column to phi. You can use this function to add an offset (bias on y axis) to phi in your custom self._phi(X). """ return np.c_[np.ones((X.shape[0], 1)), X]
Do the posterior inference on the parameters given this kernels functions and the model posterior which has to be a GPy posterior usually found at m. posterior if m is a GPy model. If not given we search for the the highest parent to be a model containing the posterior and for X accordingly.
def posterior_inf(self, X=None, posterior=None): """ Do the posterior inference on the parameters given this kernels functions and the model posterior, which has to be a GPy posterior, usually found at m.posterior, if m is a GPy model. If not given we search for the the highest parent to...
Plot the training data - For higher dimensions than two use fixed_inputs to plot the data points with some of the inputs fixed.
def plot_data(self, which_data_rows='all', which_data_ycols='all', visible_dims=None, projection='2d', label=None, **plot_kwargs): """ Plot the training data - For higher dimensions than two, use fixed_inputs to plot the data points with some of the inputs fixed. Can plot only part of...
Plot the training data input error.
def plot_data_error(self, which_data_rows='all', which_data_ycols='all', visible_dims=None, projection='2d', label=None, **error_kwargs): """ Plot the training data input error. For higher dimensions than two, use fixed_inputs to plot the data points with some of the inputs fixed. Can ...
Plot the inducing inputs of a sparse gp model
def plot_inducing(self, visible_dims=None, projection='2d', label='inducing', legend=True, **plot_kwargs): """ Plot the inducing inputs of a sparse gp model :param array-like visible_dims: an array specifying the input dimensions to plot (maximum two) :param kwargs plot_kwargs: keyword arguments for th...
Plot the errorbars of the GP likelihood on the training data. These are the errorbars after the appropriate approximations according to the likelihood are done.
def plot_errorbars_trainset(self, which_data_rows='all', which_data_ycols='all', fixed_inputs=None, plot_raw=False, apply_link=False, label=None, projection='2d', predict_kw=None, **plot_kwargs): """ Plot the errorbars of the GP likelihood on the training data. These are the errorbar...
find a matrix L which satisfies LLT = YYT.
def _get_YYTfactor(self, Y): """ find a matrix L which satisfies LLT = YYT. Note that L may have fewer columns than Y. """ N, D = Y.shape if (N>=D): return Y.view(np.ndarray) else: return jitchol(tdot(Y))
Parameters have now changed
def parameters_changed(self): """ Parameters have now changed """ # Get the model matrices from the kernel (F,L,Qc,H,Pinf,dF,dQc,dPinf) = self.kern.sde() # Use the Kalman filter to evaluate the likelihood self._log_marginal_likelihood = self.kf_likelihood(F,L,Qc,...