id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
26,400
gunthercox/ChatterBot
chatterbot/logic/logic_adapter.py
LogicAdapter.get_default_response
def get_default_response(self, input_statement): """ This method is called when a logic adapter is unable to generate any other meaningful response. """ from random import choice if self.default_responses: response = choice(self.default_responses) els...
python
def get_default_response(self, input_statement): """ This method is called when a logic adapter is unable to generate any other meaningful response. """ from random import choice if self.default_responses: response = choice(self.default_responses) els...
[ "def", "get_default_response", "(", "self", ",", "input_statement", ")", ":", "from", "random", "import", "choice", "if", "self", ".", "default_responses", ":", "response", "=", "choice", "(", "self", ".", "default_responses", ")", "else", ":", "try", ":", "...
This method is called when a logic adapter is unable to generate any other meaningful response.
[ "This", "method", "is", "called", "when", "a", "logic", "adapter", "is", "unable", "to", "generate", "any", "other", "meaningful", "response", "." ]
1a03dcb45cba7bdc24d3db5e750582e0cb1518e2
https://github.com/gunthercox/ChatterBot/blob/1a03dcb45cba7bdc24d3db5e750582e0cb1518e2/chatterbot/logic/logic_adapter.py#L103-L125
26,401
gunthercox/ChatterBot
chatterbot/logic/time_adapter.py
TimeLogicAdapter.time_question_features
def time_question_features(self, text): """ Provide an analysis of significant features in the string. """ features = {} # A list of all words from the known sentences all_words = " ".join(self.positive + self.negative).split() # A list of the first word in each...
python
def time_question_features(self, text): """ Provide an analysis of significant features in the string. """ features = {} # A list of all words from the known sentences all_words = " ".join(self.positive + self.negative).split() # A list of the first word in each...
[ "def", "time_question_features", "(", "self", ",", "text", ")", ":", "features", "=", "{", "}", "# A list of all words from the known sentences", "all_words", "=", "\" \"", ".", "join", "(", "self", ".", "positive", "+", "self", ".", "negative", ")", ".", "spl...
Provide an analysis of significant features in the string.
[ "Provide", "an", "analysis", "of", "significant", "features", "in", "the", "string", "." ]
1a03dcb45cba7bdc24d3db5e750582e0cb1518e2
https://github.com/gunthercox/ChatterBot/blob/1a03dcb45cba7bdc24d3db5e750582e0cb1518e2/chatterbot/logic/time_adapter.py#L56-L82
26,402
gunthercox/ChatterBot
chatterbot/logic/mathematical_evaluation.py
MathematicalEvaluation.can_process
def can_process(self, statement): """ Determines whether it is appropriate for this adapter to respond to the user input. """ response = self.process(statement) self.cache[statement.text] = response return response.confidence == 1
python
def can_process(self, statement): """ Determines whether it is appropriate for this adapter to respond to the user input. """ response = self.process(statement) self.cache[statement.text] = response return response.confidence == 1
[ "def", "can_process", "(", "self", ",", "statement", ")", ":", "response", "=", "self", ".", "process", "(", "statement", ")", "self", ".", "cache", "[", "statement", ".", "text", "]", "=", "response", "return", "response", ".", "confidence", "==", "1" ]
Determines whether it is appropriate for this adapter to respond to the user input.
[ "Determines", "whether", "it", "is", "appropriate", "for", "this", "adapter", "to", "respond", "to", "the", "user", "input", "." ]
1a03dcb45cba7bdc24d3db5e750582e0cb1518e2
https://github.com/gunthercox/ChatterBot/blob/1a03dcb45cba7bdc24d3db5e750582e0cb1518e2/chatterbot/logic/mathematical_evaluation.py#L28-L35
26,403
gunthercox/ChatterBot
chatterbot/logic/mathematical_evaluation.py
MathematicalEvaluation.process
def process(self, statement, additional_response_selection_parameters=None): """ Takes a statement string. Returns the equation from the statement with the mathematical terms solved. """ from mathparse import mathparse input_text = statement.text # Use the resul...
python
def process(self, statement, additional_response_selection_parameters=None): """ Takes a statement string. Returns the equation from the statement with the mathematical terms solved. """ from mathparse import mathparse input_text = statement.text # Use the resul...
[ "def", "process", "(", "self", ",", "statement", ",", "additional_response_selection_parameters", "=", "None", ")", ":", "from", "mathparse", "import", "mathparse", "input_text", "=", "statement", ".", "text", "# Use the result cached by the process method if it exists", ...
Takes a statement string. Returns the equation from the statement with the mathematical terms solved.
[ "Takes", "a", "statement", "string", ".", "Returns", "the", "equation", "from", "the", "statement", "with", "the", "mathematical", "terms", "solved", "." ]
1a03dcb45cba7bdc24d3db5e750582e0cb1518e2
https://github.com/gunthercox/ChatterBot/blob/1a03dcb45cba7bdc24d3db5e750582e0cb1518e2/chatterbot/logic/mathematical_evaluation.py#L37-L67
26,404
gunthercox/ChatterBot
chatterbot/filters.py
get_recent_repeated_responses
def get_recent_repeated_responses(chatbot, conversation, sample=10, threshold=3, quantity=3): """ A filter that eliminates possibly repetitive responses to prevent a chat bot from repeating statements that it has recently said. """ from collections import Counter # Get the most recent statement...
python
def get_recent_repeated_responses(chatbot, conversation, sample=10, threshold=3, quantity=3): """ A filter that eliminates possibly repetitive responses to prevent a chat bot from repeating statements that it has recently said. """ from collections import Counter # Get the most recent statement...
[ "def", "get_recent_repeated_responses", "(", "chatbot", ",", "conversation", ",", "sample", "=", "10", ",", "threshold", "=", "3", ",", "quantity", "=", "3", ")", ":", "from", "collections", "import", "Counter", "# Get the most recent statements from the conversation"...
A filter that eliminates possibly repetitive responses to prevent a chat bot from repeating statements that it has recently said.
[ "A", "filter", "that", "eliminates", "possibly", "repetitive", "responses", "to", "prevent", "a", "chat", "bot", "from", "repeating", "statements", "that", "it", "has", "recently", "said", "." ]
1a03dcb45cba7bdc24d3db5e750582e0cb1518e2
https://github.com/gunthercox/ChatterBot/blob/1a03dcb45cba7bdc24d3db5e750582e0cb1518e2/chatterbot/filters.py#L1-L26
26,405
gunthercox/ChatterBot
chatterbot/comparisons.py
JaccardSimilarity.compare
def compare(self, statement_a, statement_b): """ Return the calculated similarity of two statements based on the Jaccard index. """ # Make both strings lowercase document_a = self.nlp(statement_a.text.lower()) document_b = self.nlp(statement_b.text.lower()) ...
python
def compare(self, statement_a, statement_b): """ Return the calculated similarity of two statements based on the Jaccard index. """ # Make both strings lowercase document_a = self.nlp(statement_a.text.lower()) document_b = self.nlp(statement_b.text.lower()) ...
[ "def", "compare", "(", "self", ",", "statement_a", ",", "statement_b", ")", ":", "# Make both strings lowercase", "document_a", "=", "self", ".", "nlp", "(", "statement_a", ".", "text", ".", "lower", "(", ")", ")", "document_b", "=", "self", ".", "nlp", "(...
Return the calculated similarity of two statements based on the Jaccard index.
[ "Return", "the", "calculated", "similarity", "of", "two", "statements", "based", "on", "the", "Jaccard", "index", "." ]
1a03dcb45cba7bdc24d3db5e750582e0cb1518e2
https://github.com/gunthercox/ChatterBot/blob/1a03dcb45cba7bdc24d3db5e750582e0cb1518e2/chatterbot/comparisons.py#L114-L135
26,406
gunthercox/ChatterBot
chatterbot/storage/mongodb.py
MongoDatabaseAdapter.get_statement_model
def get_statement_model(self): """ Return the class for the statement model. """ from chatterbot.conversation import Statement # Create a storage-aware statement statement = Statement statement.storage = self return statement
python
def get_statement_model(self): """ Return the class for the statement model. """ from chatterbot.conversation import Statement # Create a storage-aware statement statement = Statement statement.storage = self return statement
[ "def", "get_statement_model", "(", "self", ")", ":", "from", "chatterbot", ".", "conversation", "import", "Statement", "# Create a storage-aware statement", "statement", "=", "Statement", "statement", ".", "storage", "=", "self", "return", "statement" ]
Return the class for the statement model.
[ "Return", "the", "class", "for", "the", "statement", "model", "." ]
1a03dcb45cba7bdc24d3db5e750582e0cb1518e2
https://github.com/gunthercox/ChatterBot/blob/1a03dcb45cba7bdc24d3db5e750582e0cb1518e2/chatterbot/storage/mongodb.py#L44-L54
26,407
gunthercox/ChatterBot
chatterbot/storage/mongodb.py
MongoDatabaseAdapter.mongo_to_object
def mongo_to_object(self, statement_data): """ Return Statement object when given data returned from Mongo DB. """ Statement = self.get_model('statement') statement_data['id'] = statement_data['_id'] return Statement(**statement_data)
python
def mongo_to_object(self, statement_data): """ Return Statement object when given data returned from Mongo DB. """ Statement = self.get_model('statement') statement_data['id'] = statement_data['_id'] return Statement(**statement_data)
[ "def", "mongo_to_object", "(", "self", ",", "statement_data", ")", ":", "Statement", "=", "self", ".", "get_model", "(", "'statement'", ")", "statement_data", "[", "'id'", "]", "=", "statement_data", "[", "'_id'", "]", "return", "Statement", "(", "*", "*", ...
Return Statement object when given data returned from Mongo DB.
[ "Return", "Statement", "object", "when", "given", "data", "returned", "from", "Mongo", "DB", "." ]
1a03dcb45cba7bdc24d3db5e750582e0cb1518e2
https://github.com/gunthercox/ChatterBot/blob/1a03dcb45cba7bdc24d3db5e750582e0cb1518e2/chatterbot/storage/mongodb.py#L59-L68
26,408
gunthercox/ChatterBot
chatterbot/ext/sqlalchemy_app/models.py
Statement.add_tags
def add_tags(self, *tags): """ Add a list of strings to the statement as tags. """ self.tags.extend([ Tag(name=tag) for tag in tags ])
python
def add_tags(self, *tags): """ Add a list of strings to the statement as tags. """ self.tags.extend([ Tag(name=tag) for tag in tags ])
[ "def", "add_tags", "(", "self", ",", "*", "tags", ")", ":", "self", ".", "tags", ".", "extend", "(", "[", "Tag", "(", "name", "=", "tag", ")", "for", "tag", "in", "tags", "]", ")" ]
Add a list of strings to the statement as tags.
[ "Add", "a", "list", "of", "strings", "to", "the", "statement", "as", "tags", "." ]
1a03dcb45cba7bdc24d3db5e750582e0cb1518e2
https://github.com/gunthercox/ChatterBot/blob/1a03dcb45cba7bdc24d3db5e750582e0cb1518e2/chatterbot/ext/sqlalchemy_app/models.py#L108-L114
26,409
gunthercox/ChatterBot
chatterbot/trainers.py
Trainer.get_preprocessed_statement
def get_preprocessed_statement(self, input_statement): """ Preprocess the input statement. """ for preprocessor in self.chatbot.preprocessors: input_statement = preprocessor(input_statement) return input_statement
python
def get_preprocessed_statement(self, input_statement): """ Preprocess the input statement. """ for preprocessor in self.chatbot.preprocessors: input_statement = preprocessor(input_statement) return input_statement
[ "def", "get_preprocessed_statement", "(", "self", ",", "input_statement", ")", ":", "for", "preprocessor", "in", "self", ".", "chatbot", ".", "preprocessors", ":", "input_statement", "=", "preprocessor", "(", "input_statement", ")", "return", "input_statement" ]
Preprocess the input statement.
[ "Preprocess", "the", "input", "statement", "." ]
1a03dcb45cba7bdc24d3db5e750582e0cb1518e2
https://github.com/gunthercox/ChatterBot/blob/1a03dcb45cba7bdc24d3db5e750582e0cb1518e2/chatterbot/trainers.py#L30-L37
26,410
gunthercox/ChatterBot
chatterbot/trainers.py
Trainer.export_for_training
def export_for_training(self, file_path='./export.json'): """ Create a file from the database that can be used to train other chat bots. """ import json export = {'conversations': self._generate_export_data()} with open(file_path, 'w+') as jsonfile: js...
python
def export_for_training(self, file_path='./export.json'): """ Create a file from the database that can be used to train other chat bots. """ import json export = {'conversations': self._generate_export_data()} with open(file_path, 'w+') as jsonfile: js...
[ "def", "export_for_training", "(", "self", ",", "file_path", "=", "'./export.json'", ")", ":", "import", "json", "export", "=", "{", "'conversations'", ":", "self", ".", "_generate_export_data", "(", ")", "}", "with", "open", "(", "file_path", ",", "'w+'", "...
Create a file from the database that can be used to train other chat bots.
[ "Create", "a", "file", "from", "the", "database", "that", "can", "be", "used", "to", "train", "other", "chat", "bots", "." ]
1a03dcb45cba7bdc24d3db5e750582e0cb1518e2
https://github.com/gunthercox/ChatterBot/blob/1a03dcb45cba7bdc24d3db5e750582e0cb1518e2/chatterbot/trainers.py#L66-L74
26,411
gunthercox/ChatterBot
chatterbot/trainers.py
ListTrainer.train
def train(self, conversation): """ Train the chat bot based on the provided list of statements that represents a single conversation. """ previous_statement_text = None previous_statement_search_text = '' statements_to_create = [] for conversation_count,...
python
def train(self, conversation): """ Train the chat bot based on the provided list of statements that represents a single conversation. """ previous_statement_text = None previous_statement_search_text = '' statements_to_create = [] for conversation_count,...
[ "def", "train", "(", "self", ",", "conversation", ")", ":", "previous_statement_text", "=", "None", "previous_statement_search_text", "=", "''", "statements_to_create", "=", "[", "]", "for", "conversation_count", ",", "text", "in", "enumerate", "(", "conversation", ...
Train the chat bot based on the provided list of statements that represents a single conversation.
[ "Train", "the", "chat", "bot", "based", "on", "the", "provided", "list", "of", "statements", "that", "represents", "a", "single", "conversation", "." ]
1a03dcb45cba7bdc24d3db5e750582e0cb1518e2
https://github.com/gunthercox/ChatterBot/blob/1a03dcb45cba7bdc24d3db5e750582e0cb1518e2/chatterbot/trainers.py#L83-L117
26,412
gunthercox/ChatterBot
chatterbot/trainers.py
UbuntuCorpusTrainer.is_downloaded
def is_downloaded(self, file_path): """ Check if the data file is already downloaded. """ if os.path.exists(file_path): self.chatbot.logger.info('File is already downloaded') return True return False
python
def is_downloaded(self, file_path): """ Check if the data file is already downloaded. """ if os.path.exists(file_path): self.chatbot.logger.info('File is already downloaded') return True return False
[ "def", "is_downloaded", "(", "self", ",", "file_path", ")", ":", "if", "os", ".", "path", ".", "exists", "(", "file_path", ")", ":", "self", ".", "chatbot", ".", "logger", ".", "info", "(", "'File is already downloaded'", ")", "return", "True", "return", ...
Check if the data file is already downloaded.
[ "Check", "if", "the", "data", "file", "is", "already", "downloaded", "." ]
1a03dcb45cba7bdc24d3db5e750582e0cb1518e2
https://github.com/gunthercox/ChatterBot/blob/1a03dcb45cba7bdc24d3db5e750582e0cb1518e2/chatterbot/trainers.py#L203-L211
26,413
gunthercox/ChatterBot
chatterbot/trainers.py
UbuntuCorpusTrainer.is_extracted
def is_extracted(self, file_path): """ Check if the data file is already extracted. """ if os.path.isdir(file_path): self.chatbot.logger.info('File is already extracted') return True return False
python
def is_extracted(self, file_path): """ Check if the data file is already extracted. """ if os.path.isdir(file_path): self.chatbot.logger.info('File is already extracted') return True return False
[ "def", "is_extracted", "(", "self", ",", "file_path", ")", ":", "if", "os", ".", "path", ".", "isdir", "(", "file_path", ")", ":", "self", ".", "chatbot", ".", "logger", ".", "info", "(", "'File is already extracted'", ")", "return", "True", "return", "F...
Check if the data file is already extracted.
[ "Check", "if", "the", "data", "file", "is", "already", "extracted", "." ]
1a03dcb45cba7bdc24d3db5e750582e0cb1518e2
https://github.com/gunthercox/ChatterBot/blob/1a03dcb45cba7bdc24d3db5e750582e0cb1518e2/chatterbot/trainers.py#L213-L221
26,414
gunthercox/ChatterBot
chatterbot/trainers.py
UbuntuCorpusTrainer.extract
def extract(self, file_path): """ Extract a tar file at the specified file path. """ import tarfile print('Extracting {}'.format(file_path)) if not os.path.exists(self.extracted_data_directory): os.makedirs(self.extracted_data_directory) def track_p...
python
def extract(self, file_path): """ Extract a tar file at the specified file path. """ import tarfile print('Extracting {}'.format(file_path)) if not os.path.exists(self.extracted_data_directory): os.makedirs(self.extracted_data_directory) def track_p...
[ "def", "extract", "(", "self", ",", "file_path", ")", ":", "import", "tarfile", "print", "(", "'Extracting {}'", ".", "format", "(", "file_path", ")", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "self", ".", "extracted_data_directory", ")", ...
Extract a tar file at the specified file path.
[ "Extract", "a", "tar", "file", "at", "the", "specified", "file", "path", "." ]
1a03dcb45cba7bdc24d3db5e750582e0cb1518e2
https://github.com/gunthercox/ChatterBot/blob/1a03dcb45cba7bdc24d3db5e750582e0cb1518e2/chatterbot/trainers.py#L263-L285
26,415
gunthercox/ChatterBot
chatterbot/storage/sql_storage.py
SQLStorageAdapter.count
def count(self): """ Return the number of entries in the database. """ Statement = self.get_model('statement') session = self.Session() statement_count = session.query(Statement).count() session.close() return statement_count
python
def count(self): """ Return the number of entries in the database. """ Statement = self.get_model('statement') session = self.Session() statement_count = session.query(Statement).count() session.close() return statement_count
[ "def", "count", "(", "self", ")", ":", "Statement", "=", "self", ".", "get_model", "(", "'statement'", ")", "session", "=", "self", ".", "Session", "(", ")", "statement_count", "=", "session", ".", "query", "(", "Statement", ")", ".", "count", "(", ")"...
Return the number of entries in the database.
[ "Return", "the", "number", "of", "entries", "in", "the", "database", "." ]
1a03dcb45cba7bdc24d3db5e750582e0cb1518e2
https://github.com/gunthercox/ChatterBot/blob/1a03dcb45cba7bdc24d3db5e750582e0cb1518e2/chatterbot/storage/sql_storage.py#L70-L79
26,416
gunthercox/ChatterBot
chatterbot/storage/sql_storage.py
SQLStorageAdapter.remove
def remove(self, statement_text): """ Removes the statement that matches the input text. Removes any responses from statements where the response text matches the input text. """ Statement = self.get_model('statement') session = self.Session() query = ses...
python
def remove(self, statement_text): """ Removes the statement that matches the input text. Removes any responses from statements where the response text matches the input text. """ Statement = self.get_model('statement') session = self.Session() query = ses...
[ "def", "remove", "(", "self", ",", "statement_text", ")", ":", "Statement", "=", "self", ".", "get_model", "(", "'statement'", ")", "session", "=", "self", ".", "Session", "(", ")", "query", "=", "session", ".", "query", "(", "Statement", ")", ".", "fi...
Removes the statement that matches the input text. Removes any responses from statements where the response text matches the input text.
[ "Removes", "the", "statement", "that", "matches", "the", "input", "text", ".", "Removes", "any", "responses", "from", "statements", "where", "the", "response", "text", "matches", "the", "input", "text", "." ]
1a03dcb45cba7bdc24d3db5e750582e0cb1518e2
https://github.com/gunthercox/ChatterBot/blob/1a03dcb45cba7bdc24d3db5e750582e0cb1518e2/chatterbot/storage/sql_storage.py#L81-L95
26,417
gunthercox/ChatterBot
chatterbot/storage/sql_storage.py
SQLStorageAdapter.filter
def filter(self, **kwargs): """ Returns a list of objects from the database. The kwargs parameter can contain any number of attributes. Only objects which contain all listed attributes and in which all values match for all listed attributes will be returned. """ ...
python
def filter(self, **kwargs): """ Returns a list of objects from the database. The kwargs parameter can contain any number of attributes. Only objects which contain all listed attributes and in which all values match for all listed attributes will be returned. """ ...
[ "def", "filter", "(", "self", ",", "*", "*", "kwargs", ")", ":", "from", "sqlalchemy", "import", "or_", "Statement", "=", "self", ".", "get_model", "(", "'statement'", ")", "Tag", "=", "self", ".", "get_model", "(", "'tag'", ")", "session", "=", "self"...
Returns a list of objects from the database. The kwargs parameter can contain any number of attributes. Only objects which contain all listed attributes and in which all values match for all listed attributes will be returned.
[ "Returns", "a", "list", "of", "objects", "from", "the", "database", ".", "The", "kwargs", "parameter", "can", "contain", "any", "number", "of", "attributes", ".", "Only", "objects", "which", "contain", "all", "listed", "attributes", "and", "in", "which", "al...
1a03dcb45cba7bdc24d3db5e750582e0cb1518e2
https://github.com/gunthercox/ChatterBot/blob/1a03dcb45cba7bdc24d3db5e750582e0cb1518e2/chatterbot/storage/sql_storage.py#L97-L174
26,418
gunthercox/ChatterBot
chatterbot/storage/sql_storage.py
SQLStorageAdapter.update
def update(self, statement): """ Modifies an entry in the database. Creates an entry if one does not exist. """ Statement = self.get_model('statement') Tag = self.get_model('tag') if statement is not None: session = self.Session() record =...
python
def update(self, statement): """ Modifies an entry in the database. Creates an entry if one does not exist. """ Statement = self.get_model('statement') Tag = self.get_model('tag') if statement is not None: session = self.Session() record =...
[ "def", "update", "(", "self", ",", "statement", ")", ":", "Statement", "=", "self", ".", "get_model", "(", "'statement'", ")", "Tag", "=", "self", ".", "get_model", "(", "'tag'", ")", "if", "statement", "is", "not", "None", ":", "session", "=", "self",...
Modifies an entry in the database. Creates an entry if one does not exist.
[ "Modifies", "an", "entry", "in", "the", "database", ".", "Creates", "an", "entry", "if", "one", "does", "not", "exist", "." ]
1a03dcb45cba7bdc24d3db5e750582e0cb1518e2
https://github.com/gunthercox/ChatterBot/blob/1a03dcb45cba7bdc24d3db5e750582e0cb1518e2/chatterbot/storage/sql_storage.py#L269-L318
26,419
gunthercox/ChatterBot
chatterbot/storage/sql_storage.py
SQLStorageAdapter.get_random
def get_random(self): """ Returns a random statement from the database. """ import random Statement = self.get_model('statement') session = self.Session() count = self.count() if count < 1: raise self.EmptyDatabaseException() random_...
python
def get_random(self): """ Returns a random statement from the database. """ import random Statement = self.get_model('statement') session = self.Session() count = self.count() if count < 1: raise self.EmptyDatabaseException() random_...
[ "def", "get_random", "(", "self", ")", ":", "import", "random", "Statement", "=", "self", ".", "get_model", "(", "'statement'", ")", "session", "=", "self", ".", "Session", "(", ")", "count", "=", "self", ".", "count", "(", ")", "if", "count", "<", "...
Returns a random statement from the database.
[ "Returns", "a", "random", "statement", "from", "the", "database", "." ]
1a03dcb45cba7bdc24d3db5e750582e0cb1518e2
https://github.com/gunthercox/ChatterBot/blob/1a03dcb45cba7bdc24d3db5e750582e0cb1518e2/chatterbot/storage/sql_storage.py#L320-L339
26,420
gunthercox/ChatterBot
chatterbot/storage/sql_storage.py
SQLStorageAdapter.drop
def drop(self): """ Drop the database. """ Statement = self.get_model('statement') Tag = self.get_model('tag') session = self.Session() session.query(Statement).delete() session.query(Tag).delete() session.commit() session.close()
python
def drop(self): """ Drop the database. """ Statement = self.get_model('statement') Tag = self.get_model('tag') session = self.Session() session.query(Statement).delete() session.query(Tag).delete() session.commit() session.close()
[ "def", "drop", "(", "self", ")", ":", "Statement", "=", "self", ".", "get_model", "(", "'statement'", ")", "Tag", "=", "self", ".", "get_model", "(", "'tag'", ")", "session", "=", "self", ".", "Session", "(", ")", "session", ".", "query", "(", "State...
Drop the database.
[ "Drop", "the", "database", "." ]
1a03dcb45cba7bdc24d3db5e750582e0cb1518e2
https://github.com/gunthercox/ChatterBot/blob/1a03dcb45cba7bdc24d3db5e750582e0cb1518e2/chatterbot/storage/sql_storage.py#L341-L354
26,421
gunthercox/ChatterBot
chatterbot/storage/sql_storage.py
SQLStorageAdapter.create_database
def create_database(self): """ Populate the database with the tables. """ from chatterbot.ext.sqlalchemy_app.models import Base Base.metadata.create_all(self.engine)
python
def create_database(self): """ Populate the database with the tables. """ from chatterbot.ext.sqlalchemy_app.models import Base Base.metadata.create_all(self.engine)
[ "def", "create_database", "(", "self", ")", ":", "from", "chatterbot", ".", "ext", ".", "sqlalchemy_app", ".", "models", "import", "Base", "Base", ".", "metadata", ".", "create_all", "(", "self", ".", "engine", ")" ]
Populate the database with the tables.
[ "Populate", "the", "database", "with", "the", "tables", "." ]
1a03dcb45cba7bdc24d3db5e750582e0cb1518e2
https://github.com/gunthercox/ChatterBot/blob/1a03dcb45cba7bdc24d3db5e750582e0cb1518e2/chatterbot/storage/sql_storage.py#L356-L361
26,422
gunthercox/ChatterBot
examples/django_app/example_app/views.py
ChatterBotApiView.post
def post(self, request, *args, **kwargs): """ Return a response to the statement in the posted data. * The JSON data should contain a 'text' attribute. """ input_data = json.loads(request.body.decode('utf-8')) if 'text' not in input_data: return JsonResponse...
python
def post(self, request, *args, **kwargs): """ Return a response to the statement in the posted data. * The JSON data should contain a 'text' attribute. """ input_data = json.loads(request.body.decode('utf-8')) if 'text' not in input_data: return JsonResponse...
[ "def", "post", "(", "self", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "input_data", "=", "json", ".", "loads", "(", "request", ".", "body", ".", "decode", "(", "'utf-8'", ")", ")", "if", "'text'", "not", "in", "input_data...
Return a response to the statement in the posted data. * The JSON data should contain a 'text' attribute.
[ "Return", "a", "response", "to", "the", "statement", "in", "the", "posted", "data", "." ]
1a03dcb45cba7bdc24d3db5e750582e0cb1518e2
https://github.com/gunthercox/ChatterBot/blob/1a03dcb45cba7bdc24d3db5e750582e0cb1518e2/examples/django_app/example_app/views.py#L20-L39
26,423
gunthercox/ChatterBot
chatterbot/corpus.py
get_file_path
def get_file_path(dotted_path, extension='json'): """ Reads a dotted file path and returns the file path. """ # If the operating system's file path seperator character is in the string if os.sep in dotted_path or '/' in dotted_path: # Assume the path is a valid file path return dotte...
python
def get_file_path(dotted_path, extension='json'): """ Reads a dotted file path and returns the file path. """ # If the operating system's file path seperator character is in the string if os.sep in dotted_path or '/' in dotted_path: # Assume the path is a valid file path return dotte...
[ "def", "get_file_path", "(", "dotted_path", ",", "extension", "=", "'json'", ")", ":", "# If the operating system's file path seperator character is in the string", "if", "os", ".", "sep", "in", "dotted_path", "or", "'/'", "in", "dotted_path", ":", "# Assume the path is a...
Reads a dotted file path and returns the file path.
[ "Reads", "a", "dotted", "file", "path", "and", "returns", "the", "file", "path", "." ]
1a03dcb45cba7bdc24d3db5e750582e0cb1518e2
https://github.com/gunthercox/ChatterBot/blob/1a03dcb45cba7bdc24d3db5e750582e0cb1518e2/chatterbot/corpus.py#L11-L30
26,424
gunthercox/ChatterBot
chatterbot/corpus.py
read_corpus
def read_corpus(file_name): """ Read and return the data from a corpus json file. """ with io.open(file_name, encoding='utf-8') as data_file: return yaml.load(data_file)
python
def read_corpus(file_name): """ Read and return the data from a corpus json file. """ with io.open(file_name, encoding='utf-8') as data_file: return yaml.load(data_file)
[ "def", "read_corpus", "(", "file_name", ")", ":", "with", "io", ".", "open", "(", "file_name", ",", "encoding", "=", "'utf-8'", ")", "as", "data_file", ":", "return", "yaml", ".", "load", "(", "data_file", ")" ]
Read and return the data from a corpus json file.
[ "Read", "and", "return", "the", "data", "from", "a", "corpus", "json", "file", "." ]
1a03dcb45cba7bdc24d3db5e750582e0cb1518e2
https://github.com/gunthercox/ChatterBot/blob/1a03dcb45cba7bdc24d3db5e750582e0cb1518e2/chatterbot/corpus.py#L33-L38
26,425
gunthercox/ChatterBot
chatterbot/corpus.py
list_corpus_files
def list_corpus_files(dotted_path): """ Return a list of file paths to each data file in the specified corpus. """ corpus_path = get_file_path(dotted_path, extension=CORPUS_EXTENSION) paths = [] if os.path.isdir(corpus_path): paths = glob.glob(corpus_path + '/**/*.' + CORPUS_EXTENSION, ...
python
def list_corpus_files(dotted_path): """ Return a list of file paths to each data file in the specified corpus. """ corpus_path = get_file_path(dotted_path, extension=CORPUS_EXTENSION) paths = [] if os.path.isdir(corpus_path): paths = glob.glob(corpus_path + '/**/*.' + CORPUS_EXTENSION, ...
[ "def", "list_corpus_files", "(", "dotted_path", ")", ":", "corpus_path", "=", "get_file_path", "(", "dotted_path", ",", "extension", "=", "CORPUS_EXTENSION", ")", "paths", "=", "[", "]", "if", "os", ".", "path", ".", "isdir", "(", "corpus_path", ")", ":", ...
Return a list of file paths to each data file in the specified corpus.
[ "Return", "a", "list", "of", "file", "paths", "to", "each", "data", "file", "in", "the", "specified", "corpus", "." ]
1a03dcb45cba7bdc24d3db5e750582e0cb1518e2
https://github.com/gunthercox/ChatterBot/blob/1a03dcb45cba7bdc24d3db5e750582e0cb1518e2/chatterbot/corpus.py#L41-L54
26,426
gunthercox/ChatterBot
chatterbot/corpus.py
load_corpus
def load_corpus(*data_file_paths): """ Return the data contained within a specified corpus. """ for file_path in data_file_paths: corpus = [] corpus_data = read_corpus(file_path) conversations = corpus_data.get('conversations', []) corpus.extend(conversations) c...
python
def load_corpus(*data_file_paths): """ Return the data contained within a specified corpus. """ for file_path in data_file_paths: corpus = [] corpus_data = read_corpus(file_path) conversations = corpus_data.get('conversations', []) corpus.extend(conversations) c...
[ "def", "load_corpus", "(", "*", "data_file_paths", ")", ":", "for", "file_path", "in", "data_file_paths", ":", "corpus", "=", "[", "]", "corpus_data", "=", "read_corpus", "(", "file_path", ")", "conversations", "=", "corpus_data", ".", "get", "(", "'conversati...
Return the data contained within a specified corpus.
[ "Return", "the", "data", "contained", "within", "a", "specified", "corpus", "." ]
1a03dcb45cba7bdc24d3db5e750582e0cb1518e2
https://github.com/gunthercox/ChatterBot/blob/1a03dcb45cba7bdc24d3db5e750582e0cb1518e2/chatterbot/corpus.py#L57-L70
26,427
gunthercox/ChatterBot
chatterbot/tagging.py
PosLemmaTagger.get_bigram_pair_string
def get_bigram_pair_string(self, text): """ Return a string of text containing part-of-speech, lemma pairs. """ bigram_pairs = [] if len(text) <= 2: text_without_punctuation = text.translate(self.punctuation_table) if len(text_without_punctuation) >= 1: ...
python
def get_bigram_pair_string(self, text): """ Return a string of text containing part-of-speech, lemma pairs. """ bigram_pairs = [] if len(text) <= 2: text_without_punctuation = text.translate(self.punctuation_table) if len(text_without_punctuation) >= 1: ...
[ "def", "get_bigram_pair_string", "(", "self", ",", "text", ")", ":", "bigram_pairs", "=", "[", "]", "if", "len", "(", "text", ")", "<=", "2", ":", "text_without_punctuation", "=", "text", ".", "translate", "(", "self", ".", "punctuation_table", ")", "if", ...
Return a string of text containing part-of-speech, lemma pairs.
[ "Return", "a", "string", "of", "text", "containing", "part", "-", "of", "-", "speech", "lemma", "pairs", "." ]
1a03dcb45cba7bdc24d3db5e750582e0cb1518e2
https://github.com/gunthercox/ChatterBot/blob/1a03dcb45cba7bdc24d3db5e750582e0cb1518e2/chatterbot/tagging.py#L15-L53
26,428
gunthercox/ChatterBot
chatterbot/storage/django_storage.py
DjangoStorageAdapter.update
def update(self, statement): """ Update the provided statement. """ Statement = self.get_model('statement') Tag = self.get_model('tag') if hasattr(statement, 'id'): statement.save() else: statement = Statement.objects.create( ...
python
def update(self, statement): """ Update the provided statement. """ Statement = self.get_model('statement') Tag = self.get_model('tag') if hasattr(statement, 'id'): statement.save() else: statement = Statement.objects.create( ...
[ "def", "update", "(", "self", ",", "statement", ")", ":", "Statement", "=", "self", ".", "get_model", "(", "'statement'", ")", "Tag", "=", "self", ".", "get_model", "(", "'tag'", ")", "if", "hasattr", "(", "statement", ",", "'id'", ")", ":", "statement...
Update the provided statement.
[ "Update", "the", "provided", "statement", "." ]
1a03dcb45cba7bdc24d3db5e750582e0cb1518e2
https://github.com/gunthercox/ChatterBot/blob/1a03dcb45cba7bdc24d3db5e750582e0cb1518e2/chatterbot/storage/django_storage.py#L159-L183
26,429
gunthercox/ChatterBot
chatterbot/storage/django_storage.py
DjangoStorageAdapter.remove
def remove(self, statement_text): """ Removes the statement that matches the input text. Removes any responses from statements if the response text matches the input text. """ Statement = self.get_model('statement') statements = Statement.objects.filter(text=stat...
python
def remove(self, statement_text): """ Removes the statement that matches the input text. Removes any responses from statements if the response text matches the input text. """ Statement = self.get_model('statement') statements = Statement.objects.filter(text=stat...
[ "def", "remove", "(", "self", ",", "statement_text", ")", ":", "Statement", "=", "self", ".", "get_model", "(", "'statement'", ")", "statements", "=", "Statement", ".", "objects", ".", "filter", "(", "text", "=", "statement_text", ")", "statements", ".", "...
Removes the statement that matches the input text. Removes any responses from statements if the response text matches the input text.
[ "Removes", "the", "statement", "that", "matches", "the", "input", "text", ".", "Removes", "any", "responses", "from", "statements", "if", "the", "response", "text", "matches", "the", "input", "text", "." ]
1a03dcb45cba7bdc24d3db5e750582e0cb1518e2
https://github.com/gunthercox/ChatterBot/blob/1a03dcb45cba7bdc24d3db5e750582e0cb1518e2/chatterbot/storage/django_storage.py#L198-L208
26,430
gunthercox/ChatterBot
chatterbot/storage/django_storage.py
DjangoStorageAdapter.drop
def drop(self): """ Remove all data from the database. """ Statement = self.get_model('statement') Tag = self.get_model('tag') Statement.objects.all().delete() Tag.objects.all().delete()
python
def drop(self): """ Remove all data from the database. """ Statement = self.get_model('statement') Tag = self.get_model('tag') Statement.objects.all().delete() Tag.objects.all().delete()
[ "def", "drop", "(", "self", ")", ":", "Statement", "=", "self", ".", "get_model", "(", "'statement'", ")", "Tag", "=", "self", ".", "get_model", "(", "'tag'", ")", "Statement", ".", "objects", ".", "all", "(", ")", ".", "delete", "(", ")", "Tag", "...
Remove all data from the database.
[ "Remove", "all", "data", "from", "the", "database", "." ]
1a03dcb45cba7bdc24d3db5e750582e0cb1518e2
https://github.com/gunthercox/ChatterBot/blob/1a03dcb45cba7bdc24d3db5e750582e0cb1518e2/chatterbot/storage/django_storage.py#L210-L218
26,431
gunthercox/ChatterBot
chatterbot/preprocessors.py
clean_whitespace
def clean_whitespace(statement): """ Remove any consecutive whitespace characters from the statement text. """ import re # Replace linebreaks and tabs with spaces statement.text = statement.text.replace('\n', ' ').replace('\r', ' ').replace('\t', ' ') # Remove any leeding or trailing white...
python
def clean_whitespace(statement): """ Remove any consecutive whitespace characters from the statement text. """ import re # Replace linebreaks and tabs with spaces statement.text = statement.text.replace('\n', ' ').replace('\r', ' ').replace('\t', ' ') # Remove any leeding or trailing white...
[ "def", "clean_whitespace", "(", "statement", ")", ":", "import", "re", "# Replace linebreaks and tabs with spaces", "statement", ".", "text", "=", "statement", ".", "text", ".", "replace", "(", "'\\n'", ",", "' '", ")", ".", "replace", "(", "'\\r'", ",", "' '"...
Remove any consecutive whitespace characters from the statement text.
[ "Remove", "any", "consecutive", "whitespace", "characters", "from", "the", "statement", "text", "." ]
1a03dcb45cba7bdc24d3db5e750582e0cb1518e2
https://github.com/gunthercox/ChatterBot/blob/1a03dcb45cba7bdc24d3db5e750582e0cb1518e2/chatterbot/preprocessors.py#L6-L21
26,432
gunthercox/ChatterBot
chatterbot/parsing.py
convert_string_to_number
def convert_string_to_number(value): """ Convert strings to numbers """ if value is None: return 1 if isinstance(value, int): return value if value.isdigit(): return int(value) num_list = map(lambda s: NUMBERS[s], re.findall(numbers + '+', value.lower())) return s...
python
def convert_string_to_number(value): """ Convert strings to numbers """ if value is None: return 1 if isinstance(value, int): return value if value.isdigit(): return int(value) num_list = map(lambda s: NUMBERS[s], re.findall(numbers + '+', value.lower())) return s...
[ "def", "convert_string_to_number", "(", "value", ")", ":", "if", "value", "is", "None", ":", "return", "1", "if", "isinstance", "(", "value", ",", "int", ")", ":", "return", "value", "if", "value", ".", "isdigit", "(", ")", ":", "return", "int", "(", ...
Convert strings to numbers
[ "Convert", "strings", "to", "numbers" ]
1a03dcb45cba7bdc24d3db5e750582e0cb1518e2
https://github.com/gunthercox/ChatterBot/blob/1a03dcb45cba7bdc24d3db5e750582e0cb1518e2/chatterbot/parsing.py#L506-L517
26,433
gunthercox/ChatterBot
chatterbot/parsing.py
convert_time_to_hour_minute
def convert_time_to_hour_minute(hour, minute, convention): """ Convert time to hour, minute """ if hour is None: hour = 0 if minute is None: minute = 0 if convention is None: convention = 'am' hour = int(hour) minute = int(minute) if convention.lower() == 'p...
python
def convert_time_to_hour_minute(hour, minute, convention): """ Convert time to hour, minute """ if hour is None: hour = 0 if minute is None: minute = 0 if convention is None: convention = 'am' hour = int(hour) minute = int(minute) if convention.lower() == 'p...
[ "def", "convert_time_to_hour_minute", "(", "hour", ",", "minute", ",", "convention", ")", ":", "if", "hour", "is", "None", ":", "hour", "=", "0", "if", "minute", "is", "None", ":", "minute", "=", "0", "if", "convention", "is", "None", ":", "convention", ...
Convert time to hour, minute
[ "Convert", "time", "to", "hour", "minute" ]
1a03dcb45cba7bdc24d3db5e750582e0cb1518e2
https://github.com/gunthercox/ChatterBot/blob/1a03dcb45cba7bdc24d3db5e750582e0cb1518e2/chatterbot/parsing.py#L520-L537
26,434
gunthercox/ChatterBot
chatterbot/parsing.py
date_from_quarter
def date_from_quarter(base_date, ordinal, year): """ Extract date from quarter of a year """ interval = 3 month_start = interval * (ordinal - 1) if month_start < 0: month_start = 9 month_end = month_start + interval if month_start == 0: month_start = 1 return [ ...
python
def date_from_quarter(base_date, ordinal, year): """ Extract date from quarter of a year """ interval = 3 month_start = interval * (ordinal - 1) if month_start < 0: month_start = 9 month_end = month_start + interval if month_start == 0: month_start = 1 return [ ...
[ "def", "date_from_quarter", "(", "base_date", ",", "ordinal", ",", "year", ")", ":", "interval", "=", "3", "month_start", "=", "interval", "*", "(", "ordinal", "-", "1", ")", "if", "month_start", "<", "0", ":", "month_start", "=", "9", "month_end", "=", ...
Extract date from quarter of a year
[ "Extract", "date", "from", "quarter", "of", "a", "year" ]
1a03dcb45cba7bdc24d3db5e750582e0cb1518e2
https://github.com/gunthercox/ChatterBot/blob/1a03dcb45cba7bdc24d3db5e750582e0cb1518e2/chatterbot/parsing.py#L540-L554
26,435
gunthercox/ChatterBot
chatterbot/parsing.py
date_from_relative_week_year
def date_from_relative_week_year(base_date, time, dow, ordinal=1): """ Converts relative day to time Eg. this tuesday, last tuesday """ # If there is an ordinal (next 3 weeks) => return a start and end range # Reset date to start of the day relative_date = datetime(base_date.year, base_date....
python
def date_from_relative_week_year(base_date, time, dow, ordinal=1): """ Converts relative day to time Eg. this tuesday, last tuesday """ # If there is an ordinal (next 3 weeks) => return a start and end range # Reset date to start of the day relative_date = datetime(base_date.year, base_date....
[ "def", "date_from_relative_week_year", "(", "base_date", ",", "time", ",", "dow", ",", "ordinal", "=", "1", ")", ":", "# If there is an ordinal (next 3 weeks) => return a start and end range", "# Reset date to start of the day", "relative_date", "=", "datetime", "(", "base_da...
Converts relative day to time Eg. this tuesday, last tuesday
[ "Converts", "relative", "day", "to", "time", "Eg", ".", "this", "tuesday", "last", "tuesday" ]
1a03dcb45cba7bdc24d3db5e750582e0cb1518e2
https://github.com/gunthercox/ChatterBot/blob/1a03dcb45cba7bdc24d3db5e750582e0cb1518e2/chatterbot/parsing.py#L580-L636
26,436
gunthercox/ChatterBot
chatterbot/parsing.py
date_from_adverb
def date_from_adverb(base_date, name): """ Convert Day adverbs to dates Tomorrow => Date Today => Date """ # Reset date to start of the day adverb_date = datetime(base_date.year, base_date.month, base_date.day) if name == 'today' or name == 'tonite' or name == 'tonight': return a...
python
def date_from_adverb(base_date, name): """ Convert Day adverbs to dates Tomorrow => Date Today => Date """ # Reset date to start of the day adverb_date = datetime(base_date.year, base_date.month, base_date.day) if name == 'today' or name == 'tonite' or name == 'tonight': return a...
[ "def", "date_from_adverb", "(", "base_date", ",", "name", ")", ":", "# Reset date to start of the day", "adverb_date", "=", "datetime", "(", "base_date", ".", "year", ",", "base_date", ".", "month", ",", "base_date", ".", "day", ")", "if", "name", "==", "'toda...
Convert Day adverbs to dates Tomorrow => Date Today => Date
[ "Convert", "Day", "adverbs", "to", "dates", "Tomorrow", "=", ">", "Date", "Today", "=", ">", "Date" ]
1a03dcb45cba7bdc24d3db5e750582e0cb1518e2
https://github.com/gunthercox/ChatterBot/blob/1a03dcb45cba7bdc24d3db5e750582e0cb1518e2/chatterbot/parsing.py#L639-L652
26,437
gunthercox/ChatterBot
chatterbot/parsing.py
this_week_day
def this_week_day(base_date, weekday): """ Finds coming weekday """ day_of_week = base_date.weekday() # If today is Tuesday and the query is `this monday` # We should output the next_week monday if day_of_week > weekday: return next_week_day(base_date, weekday) start_of_this_week...
python
def this_week_day(base_date, weekday): """ Finds coming weekday """ day_of_week = base_date.weekday() # If today is Tuesday and the query is `this monday` # We should output the next_week monday if day_of_week > weekday: return next_week_day(base_date, weekday) start_of_this_week...
[ "def", "this_week_day", "(", "base_date", ",", "weekday", ")", ":", "day_of_week", "=", "base_date", ".", "weekday", "(", ")", "# If today is Tuesday and the query is `this monday`", "# We should output the next_week monday", "if", "day_of_week", ">", "weekday", ":", "ret...
Finds coming weekday
[ "Finds", "coming", "weekday" ]
1a03dcb45cba7bdc24d3db5e750582e0cb1518e2
https://github.com/gunthercox/ChatterBot/blob/1a03dcb45cba7bdc24d3db5e750582e0cb1518e2/chatterbot/parsing.py#L685-L698
26,438
gunthercox/ChatterBot
chatterbot/parsing.py
previous_week_day
def previous_week_day(base_date, weekday): """ Finds previous weekday """ day = base_date - timedelta(days=1) while day.weekday() != weekday: day = day - timedelta(days=1) return day
python
def previous_week_day(base_date, weekday): """ Finds previous weekday """ day = base_date - timedelta(days=1) while day.weekday() != weekday: day = day - timedelta(days=1) return day
[ "def", "previous_week_day", "(", "base_date", ",", "weekday", ")", ":", "day", "=", "base_date", "-", "timedelta", "(", "days", "=", "1", ")", "while", "day", ".", "weekday", "(", ")", "!=", "weekday", ":", "day", "=", "day", "-", "timedelta", "(", "...
Finds previous weekday
[ "Finds", "previous", "weekday" ]
1a03dcb45cba7bdc24d3db5e750582e0cb1518e2
https://github.com/gunthercox/ChatterBot/blob/1a03dcb45cba7bdc24d3db5e750582e0cb1518e2/chatterbot/parsing.py#L701-L708
26,439
gunthercox/ChatterBot
chatterbot/parsing.py
next_week_day
def next_week_day(base_date, weekday): """ Finds next weekday """ day_of_week = base_date.weekday() end_of_this_week = base_date + timedelta(days=6 - day_of_week) day = end_of_this_week + timedelta(days=1) while day.weekday() != weekday: day = day + timedelta(days=1) return day
python
def next_week_day(base_date, weekday): """ Finds next weekday """ day_of_week = base_date.weekday() end_of_this_week = base_date + timedelta(days=6 - day_of_week) day = end_of_this_week + timedelta(days=1) while day.weekday() != weekday: day = day + timedelta(days=1) return day
[ "def", "next_week_day", "(", "base_date", ",", "weekday", ")", ":", "day_of_week", "=", "base_date", ".", "weekday", "(", ")", "end_of_this_week", "=", "base_date", "+", "timedelta", "(", "days", "=", "6", "-", "day_of_week", ")", "day", "=", "end_of_this_we...
Finds next weekday
[ "Finds", "next", "weekday" ]
1a03dcb45cba7bdc24d3db5e750582e0cb1518e2
https://github.com/gunthercox/ChatterBot/blob/1a03dcb45cba7bdc24d3db5e750582e0cb1518e2/chatterbot/parsing.py#L711-L720
26,440
gunthercox/ChatterBot
chatterbot/parsing.py
datetime_parsing
def datetime_parsing(text, base_date=datetime.now()): """ Extract datetime objects from a string of text. """ matches = [] found_array = [] # Find the position in the string for expression, function in regex: for match in expression.finditer(text): matches.append((match....
python
def datetime_parsing(text, base_date=datetime.now()): """ Extract datetime objects from a string of text. """ matches = [] found_array = [] # Find the position in the string for expression, function in regex: for match in expression.finditer(text): matches.append((match....
[ "def", "datetime_parsing", "(", "text", ",", "base_date", "=", "datetime", ".", "now", "(", ")", ")", ":", "matches", "=", "[", "]", "found_array", "=", "[", "]", "# Find the position in the string", "for", "expression", ",", "function", "in", "regex", ":", ...
Extract datetime objects from a string of text.
[ "Extract", "datetime", "objects", "from", "a", "string", "of", "text", "." ]
1a03dcb45cba7bdc24d3db5e750582e0cb1518e2
https://github.com/gunthercox/ChatterBot/blob/1a03dcb45cba7bdc24d3db5e750582e0cb1518e2/chatterbot/parsing.py#L723-L746
26,441
gunthercox/ChatterBot
chatterbot/search.py
IndexedTextSearch.search
def search(self, input_statement, **additional_parameters): """ Search for close matches to the input. Confidence scores for subsequent results will order of increasing value. :param input_statement: A statement. :type input_statement: chatterbot.conversation.Statement ...
python
def search(self, input_statement, **additional_parameters): """ Search for close matches to the input. Confidence scores for subsequent results will order of increasing value. :param input_statement: A statement. :type input_statement: chatterbot.conversation.Statement ...
[ "def", "search", "(", "self", ",", "input_statement", ",", "*", "*", "additional_parameters", ")", ":", "self", ".", "chatbot", ".", "logger", ".", "info", "(", "'Beginning search for close text match'", ")", "input_search_text", "=", "input_statement", ".", "sear...
Search for close matches to the input. Confidence scores for subsequent results will order of increasing value. :param input_statement: A statement. :type input_statement: chatterbot.conversation.Statement :param **additional_parameters: Additional parameters to be passed t...
[ "Search", "for", "close", "matches", "to", "the", "input", ".", "Confidence", "scores", "for", "subsequent", "results", "will", "order", "of", "increasing", "value", "." ]
1a03dcb45cba7bdc24d3db5e750582e0cb1518e2
https://github.com/gunthercox/ChatterBot/blob/1a03dcb45cba7bdc24d3db5e750582e0cb1518e2/chatterbot/search.py#L35-L89
26,442
gunthercox/ChatterBot
examples/tkinter_gui.py
TkinterGUIExample.initialize
def initialize(self): """ Set window layout. """ self.grid() self.respond = ttk.Button(self, text='Get Response', command=self.get_response) self.respond.grid(column=0, row=0, sticky='nesw', padx=3, pady=3) self.usr_input = ttk.Entry(self, state='normal') ...
python
def initialize(self): """ Set window layout. """ self.grid() self.respond = ttk.Button(self, text='Get Response', command=self.get_response) self.respond.grid(column=0, row=0, sticky='nesw', padx=3, pady=3) self.usr_input = ttk.Entry(self, state='normal') ...
[ "def", "initialize", "(", "self", ")", ":", "self", ".", "grid", "(", ")", "self", ".", "respond", "=", "ttk", ".", "Button", "(", "self", ",", "text", "=", "'Get Response'", ",", "command", "=", "self", ".", "get_response", ")", "self", ".", "respon...
Set window layout.
[ "Set", "window", "layout", "." ]
1a03dcb45cba7bdc24d3db5e750582e0cb1518e2
https://github.com/gunthercox/ChatterBot/blob/1a03dcb45cba7bdc24d3db5e750582e0cb1518e2/examples/tkinter_gui.py#L33-L49
26,443
gunthercox/ChatterBot
examples/tkinter_gui.py
TkinterGUIExample.get_response
def get_response(self): """ Get a response from the chatbot and display it. """ user_input = self.usr_input.get() self.usr_input.delete(0, tk.END) response = self.chatbot.get_response(user_input) self.conversation['state'] = 'normal' self.conversation.in...
python
def get_response(self): """ Get a response from the chatbot and display it. """ user_input = self.usr_input.get() self.usr_input.delete(0, tk.END) response = self.chatbot.get_response(user_input) self.conversation['state'] = 'normal' self.conversation.in...
[ "def", "get_response", "(", "self", ")", ":", "user_input", "=", "self", ".", "usr_input", ".", "get", "(", ")", "self", ".", "usr_input", ".", "delete", "(", "0", ",", "tk", ".", "END", ")", "response", "=", "self", ".", "chatbot", ".", "get_respons...
Get a response from the chatbot and display it.
[ "Get", "a", "response", "from", "the", "chatbot", "and", "display", "it", "." ]
1a03dcb45cba7bdc24d3db5e750582e0cb1518e2
https://github.com/gunthercox/ChatterBot/blob/1a03dcb45cba7bdc24d3db5e750582e0cb1518e2/examples/tkinter_gui.py#L51-L66
26,444
tensorflow/lucid
lucid/scratch/web/svelte.py
SvelteComponent
def SvelteComponent(name, path): """Display svelte components in iPython. Args: name: name of svelte component (must match component filename when built) path: path to compile svelte .js file or source svelte .html file. (If html file, we try to call svelte and build the file.) Returns: A func...
python
def SvelteComponent(name, path): """Display svelte components in iPython. Args: name: name of svelte component (must match component filename when built) path: path to compile svelte .js file or source svelte .html file. (If html file, we try to call svelte and build the file.) Returns: A func...
[ "def", "SvelteComponent", "(", "name", ",", "path", ")", ":", "if", "path", "[", "-", "3", ":", "]", "==", "\".js\"", ":", "js_path", "=", "path", "elif", "path", "[", "-", "5", ":", "]", "==", "\".html\"", ":", "print", "(", "\"Trying to build svelt...
Display svelte components in iPython. Args: name: name of svelte component (must match component filename when built) path: path to compile svelte .js file or source svelte .html file. (If html file, we try to call svelte and build the file.) Returns: A function mapping data to a rendered svelte...
[ "Display", "svelte", "components", "in", "iPython", "." ]
d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e
https://github.com/tensorflow/lucid/blob/d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e/lucid/scratch/web/svelte.py#L43-L68
26,445
tensorflow/lucid
lucid/misc/io/saving.py
save_json
def save_json(object, handle, indent=2): """Save object as json on CNS.""" obj_json = json.dumps(object, indent=indent, cls=NumpyJSONEncoder) handle.write(obj_json)
python
def save_json(object, handle, indent=2): """Save object as json on CNS.""" obj_json = json.dumps(object, indent=indent, cls=NumpyJSONEncoder) handle.write(obj_json)
[ "def", "save_json", "(", "object", ",", "handle", ",", "indent", "=", "2", ")", ":", "obj_json", "=", "json", ".", "dumps", "(", "object", ",", "indent", "=", "indent", ",", "cls", "=", "NumpyJSONEncoder", ")", "handle", ".", "write", "(", "obj_json", ...
Save object as json on CNS.
[ "Save", "object", "as", "json", "on", "CNS", "." ]
d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e
https://github.com/tensorflow/lucid/blob/d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e/lucid/misc/io/saving.py#L58-L61
26,446
tensorflow/lucid
lucid/misc/io/saving.py
save_npz
def save_npz(object, handle): """Save dict of numpy array as npz file.""" # there is a bug where savez doesn't actually accept a file handle. log.warning("Saving npz files currently only works locally. :/") path = handle.name handle.close() if type(object) is dict: np.savez(path, **objec...
python
def save_npz(object, handle): """Save dict of numpy array as npz file.""" # there is a bug where savez doesn't actually accept a file handle. log.warning("Saving npz files currently only works locally. :/") path = handle.name handle.close() if type(object) is dict: np.savez(path, **objec...
[ "def", "save_npz", "(", "object", ",", "handle", ")", ":", "# there is a bug where savez doesn't actually accept a file handle.", "log", ".", "warning", "(", "\"Saving npz files currently only works locally. :/\"", ")", "path", "=", "handle", ".", "name", "handle", ".", "...
Save dict of numpy array as npz file.
[ "Save", "dict", "of", "numpy", "array", "as", "npz", "file", "." ]
d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e
https://github.com/tensorflow/lucid/blob/d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e/lucid/misc/io/saving.py#L69-L81
26,447
tensorflow/lucid
lucid/misc/io/saving.py
save_img
def save_img(object, handle, **kwargs): """Save numpy array as image file on CNS.""" if isinstance(object, np.ndarray): normalized = _normalize_array(object) object = PIL.Image.fromarray(normalized) if isinstance(object, PIL.Image.Image): object.save(handle, **kwargs) # will infer...
python
def save_img(object, handle, **kwargs): """Save numpy array as image file on CNS.""" if isinstance(object, np.ndarray): normalized = _normalize_array(object) object = PIL.Image.fromarray(normalized) if isinstance(object, PIL.Image.Image): object.save(handle, **kwargs) # will infer...
[ "def", "save_img", "(", "object", ",", "handle", ",", "*", "*", "kwargs", ")", ":", "if", "isinstance", "(", "object", ",", "np", ".", "ndarray", ")", ":", "normalized", "=", "_normalize_array", "(", "object", ")", "object", "=", "PIL", ".", "Image", ...
Save numpy array as image file on CNS.
[ "Save", "numpy", "array", "as", "image", "file", "on", "CNS", "." ]
d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e
https://github.com/tensorflow/lucid/blob/d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e/lucid/misc/io/saving.py#L84-L94
26,448
tensorflow/lucid
lucid/misc/io/saving.py
save
def save(thing, url_or_handle, **kwargs): """Save object to file on CNS. File format is inferred from path. Use save_img(), save_npy(), or save_json() if you need to force a particular format. Args: obj: object to save. path: CNS path. Raises: RuntimeError: If file extension not...
python
def save(thing, url_or_handle, **kwargs): """Save object to file on CNS. File format is inferred from path. Use save_img(), save_npy(), or save_json() if you need to force a particular format. Args: obj: object to save. path: CNS path. Raises: RuntimeError: If file extension not...
[ "def", "save", "(", "thing", ",", "url_or_handle", ",", "*", "*", "kwargs", ")", ":", "is_handle", "=", "hasattr", "(", "url_or_handle", ",", "\"write\"", ")", "and", "hasattr", "(", "url_or_handle", ",", "\"name\"", ")", "if", "is_handle", ":", "_", ","...
Save object to file on CNS. File format is inferred from path. Use save_img(), save_npy(), or save_json() if you need to force a particular format. Args: obj: object to save. path: CNS path. Raises: RuntimeError: If file extension not supported.
[ "Save", "object", "to", "file", "on", "CNS", "." ]
d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e
https://github.com/tensorflow/lucid/blob/d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e/lucid/misc/io/saving.py#L135-L166
26,449
tensorflow/lucid
lucid/misc/gl/meshutil.py
frustum
def frustum(left, right, bottom, top, znear, zfar): """Create view frustum matrix.""" assert right != left assert bottom != top assert znear != zfar M = np.zeros((4, 4), dtype=np.float32) M[0, 0] = +2.0 * znear / (right - left) M[2, 0] = (right + left) / (right - left) M[1, 1] = +2.0 * znear / (top - b...
python
def frustum(left, right, bottom, top, znear, zfar): """Create view frustum matrix.""" assert right != left assert bottom != top assert znear != zfar M = np.zeros((4, 4), dtype=np.float32) M[0, 0] = +2.0 * znear / (right - left) M[2, 0] = (right + left) / (right - left) M[1, 1] = +2.0 * znear / (top - b...
[ "def", "frustum", "(", "left", ",", "right", ",", "bottom", ",", "top", ",", "znear", ",", "zfar", ")", ":", "assert", "right", "!=", "left", "assert", "bottom", "!=", "top", "assert", "znear", "!=", "zfar", "M", "=", "np", ".", "zeros", "(", "(", ...
Create view frustum matrix.
[ "Create", "view", "frustum", "matrix", "." ]
d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e
https://github.com/tensorflow/lucid/blob/d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e/lucid/misc/gl/meshutil.py#L8-L22
26,450
tensorflow/lucid
lucid/misc/gl/meshutil.py
anorm
def anorm(x, axis=None, keepdims=False): """Compute L2 norms alogn specified axes.""" return np.sqrt((x*x).sum(axis=axis, keepdims=keepdims))
python
def anorm(x, axis=None, keepdims=False): """Compute L2 norms alogn specified axes.""" return np.sqrt((x*x).sum(axis=axis, keepdims=keepdims))
[ "def", "anorm", "(", "x", ",", "axis", "=", "None", ",", "keepdims", "=", "False", ")", ":", "return", "np", ".", "sqrt", "(", "(", "x", "*", "x", ")", ".", "sum", "(", "axis", "=", "axis", ",", "keepdims", "=", "keepdims", ")", ")" ]
Compute L2 norms alogn specified axes.
[ "Compute", "L2", "norms", "alogn", "specified", "axes", "." ]
d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e
https://github.com/tensorflow/lucid/blob/d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e/lucid/misc/gl/meshutil.py#L33-L35
26,451
tensorflow/lucid
lucid/misc/gl/meshutil.py
normalize
def normalize(v, axis=None, eps=1e-10): """L2 Normalize along specified axes.""" return v / max(anorm(v, axis=axis, keepdims=True), eps)
python
def normalize(v, axis=None, eps=1e-10): """L2 Normalize along specified axes.""" return v / max(anorm(v, axis=axis, keepdims=True), eps)
[ "def", "normalize", "(", "v", ",", "axis", "=", "None", ",", "eps", "=", "1e-10", ")", ":", "return", "v", "/", "max", "(", "anorm", "(", "v", ",", "axis", "=", "axis", ",", "keepdims", "=", "True", ")", ",", "eps", ")" ]
L2 Normalize along specified axes.
[ "L2", "Normalize", "along", "specified", "axes", "." ]
d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e
https://github.com/tensorflow/lucid/blob/d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e/lucid/misc/gl/meshutil.py#L38-L40
26,452
tensorflow/lucid
lucid/misc/gl/meshutil.py
lookat
def lookat(eye, target=[0, 0, 0], up=[0, 1, 0]): """Generate LookAt modelview matrix.""" eye = np.float32(eye) forward = normalize(target - eye) side = normalize(np.cross(forward, up)) up = np.cross(side, forward) M = np.eye(4, dtype=np.float32) R = M[:3, :3] R[:] = [side, up, -forward] M[:3, 3] = -R....
python
def lookat(eye, target=[0, 0, 0], up=[0, 1, 0]): """Generate LookAt modelview matrix.""" eye = np.float32(eye) forward = normalize(target - eye) side = normalize(np.cross(forward, up)) up = np.cross(side, forward) M = np.eye(4, dtype=np.float32) R = M[:3, :3] R[:] = [side, up, -forward] M[:3, 3] = -R....
[ "def", "lookat", "(", "eye", ",", "target", "=", "[", "0", ",", "0", ",", "0", "]", ",", "up", "=", "[", "0", ",", "1", ",", "0", "]", ")", ":", "eye", "=", "np", ".", "float32", "(", "eye", ")", "forward", "=", "normalize", "(", "target", ...
Generate LookAt modelview matrix.
[ "Generate", "LookAt", "modelview", "matrix", "." ]
d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e
https://github.com/tensorflow/lucid/blob/d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e/lucid/misc/gl/meshutil.py#L43-L53
26,453
tensorflow/lucid
lucid/misc/gl/meshutil.py
sample_view
def sample_view(min_dist, max_dist=None): '''Sample random camera position. Sample origin directed camera position in given distance range from the origin. ModelView matrix is returned. ''' if max_dist is None: max_dist = min_dist dist = np.random.uniform(min_dist, max_dist) eye = np.random.normal(...
python
def sample_view(min_dist, max_dist=None): '''Sample random camera position. Sample origin directed camera position in given distance range from the origin. ModelView matrix is returned. ''' if max_dist is None: max_dist = min_dist dist = np.random.uniform(min_dist, max_dist) eye = np.random.normal(...
[ "def", "sample_view", "(", "min_dist", ",", "max_dist", "=", "None", ")", ":", "if", "max_dist", "is", "None", ":", "max_dist", "=", "min_dist", "dist", "=", "np", ".", "random", ".", "uniform", "(", "min_dist", ",", "max_dist", ")", "eye", "=", "np", ...
Sample random camera position. Sample origin directed camera position in given distance range from the origin. ModelView matrix is returned.
[ "Sample", "random", "camera", "position", ".", "Sample", "origin", "directed", "camera", "position", "in", "given", "distance", "range", "from", "the", "origin", ".", "ModelView", "matrix", "is", "returned", "." ]
d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e
https://github.com/tensorflow/lucid/blob/d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e/lucid/misc/gl/meshutil.py#L56-L67
26,454
tensorflow/lucid
lucid/misc/gl/meshutil.py
_unify_rows
def _unify_rows(a): """Unify lengths of each row of a.""" lens = np.fromiter(map(len, a), np.int32) if not (lens[0] == lens).all(): out = np.zeros((len(a), lens.max()), np.float32) for i, row in enumerate(a): out[i, :lens[i]] = row else: out = np.float32(a) return out
python
def _unify_rows(a): """Unify lengths of each row of a.""" lens = np.fromiter(map(len, a), np.int32) if not (lens[0] == lens).all(): out = np.zeros((len(a), lens.max()), np.float32) for i, row in enumerate(a): out[i, :lens[i]] = row else: out = np.float32(a) return out
[ "def", "_unify_rows", "(", "a", ")", ":", "lens", "=", "np", ".", "fromiter", "(", "map", "(", "len", ",", "a", ")", ",", "np", ".", "int32", ")", "if", "not", "(", "lens", "[", "0", "]", "==", "lens", ")", ".", "all", "(", ")", ":", "out",...
Unify lengths of each row of a.
[ "Unify", "lengths", "of", "each", "row", "of", "a", "." ]
d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e
https://github.com/tensorflow/lucid/blob/d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e/lucid/misc/gl/meshutil.py#L87-L96
26,455
tensorflow/lucid
lucid/misc/gl/meshutil.py
normalize_mesh
def normalize_mesh(mesh): '''Scale mesh to fit into -1..1 cube''' mesh = dict(mesh) pos = mesh['position'][:,:3].copy() pos -= (pos.max(0)+pos.min(0)) / 2.0 pos /= np.abs(pos).max() mesh['position'] = pos return mesh
python
def normalize_mesh(mesh): '''Scale mesh to fit into -1..1 cube''' mesh = dict(mesh) pos = mesh['position'][:,:3].copy() pos -= (pos.max(0)+pos.min(0)) / 2.0 pos /= np.abs(pos).max() mesh['position'] = pos return mesh
[ "def", "normalize_mesh", "(", "mesh", ")", ":", "mesh", "=", "dict", "(", "mesh", ")", "pos", "=", "mesh", "[", "'position'", "]", "[", ":", ",", ":", "3", "]", ".", "copy", "(", ")", "pos", "-=", "(", "pos", ".", "max", "(", "0", ")", "+", ...
Scale mesh to fit into -1..1 cube
[ "Scale", "mesh", "to", "fit", "into", "-", "1", "..", "1", "cube" ]
d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e
https://github.com/tensorflow/lucid/blob/d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e/lucid/misc/gl/meshutil.py#L161-L168
26,456
tensorflow/lucid
lucid/modelzoo/vision_base.py
Layer.activations
def activations(self): """Loads sampled activations, which requires network access.""" if self._activations is None: self._activations = _get_aligned_activations(self) return self._activations
python
def activations(self): """Loads sampled activations, which requires network access.""" if self._activations is None: self._activations = _get_aligned_activations(self) return self._activations
[ "def", "activations", "(", "self", ")", ":", "if", "self", ".", "_activations", "is", "None", ":", "self", ".", "_activations", "=", "_get_aligned_activations", "(", "self", ")", "return", "self", ".", "_activations" ]
Loads sampled activations, which requires network access.
[ "Loads", "sampled", "activations", "which", "requires", "network", "access", "." ]
d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e
https://github.com/tensorflow/lucid/blob/d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e/lucid/modelzoo/vision_base.py#L71-L75
26,457
tensorflow/lucid
lucid/modelzoo/vision_base.py
Model.create_input
def create_input(self, t_input=None, forget_xy_shape=True): """Create input tensor.""" if t_input is None: t_input = tf.placeholder(tf.float32, self.image_shape) t_prep_input = t_input if len(t_prep_input.shape) == 3: t_prep_input = tf.expand_dims(t_prep_input, 0) if forget_xy_shape: ...
python
def create_input(self, t_input=None, forget_xy_shape=True): """Create input tensor.""" if t_input is None: t_input = tf.placeholder(tf.float32, self.image_shape) t_prep_input = t_input if len(t_prep_input.shape) == 3: t_prep_input = tf.expand_dims(t_prep_input, 0) if forget_xy_shape: ...
[ "def", "create_input", "(", "self", ",", "t_input", "=", "None", ",", "forget_xy_shape", "=", "True", ")", ":", "if", "t_input", "is", "None", ":", "t_input", "=", "tf", ".", "placeholder", "(", "tf", ".", "float32", ",", "self", ".", "image_shape", ")...
Create input tensor.
[ "Create", "input", "tensor", "." ]
d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e
https://github.com/tensorflow/lucid/blob/d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e/lucid/modelzoo/vision_base.py#L161-L174
26,458
tensorflow/lucid
lucid/modelzoo/vision_base.py
Model.import_graph
def import_graph(self, t_input=None, scope='import', forget_xy_shape=True): """Import model GraphDef into the current graph.""" graph = tf.get_default_graph() assert graph.unique_name(scope, False) == scope, ( 'Scope "%s" already exists. Provide explicit scope names when ' 'importing multipl...
python
def import_graph(self, t_input=None, scope='import', forget_xy_shape=True): """Import model GraphDef into the current graph.""" graph = tf.get_default_graph() assert graph.unique_name(scope, False) == scope, ( 'Scope "%s" already exists. Provide explicit scope names when ' 'importing multipl...
[ "def", "import_graph", "(", "self", ",", "t_input", "=", "None", ",", "scope", "=", "'import'", ",", "forget_xy_shape", "=", "True", ")", ":", "graph", "=", "tf", ".", "get_default_graph", "(", ")", "assert", "graph", ".", "unique_name", "(", "scope", ",...
Import model GraphDef into the current graph.
[ "Import", "model", "GraphDef", "into", "the", "current", "graph", "." ]
d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e
https://github.com/tensorflow/lucid/blob/d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e/lucid/modelzoo/vision_base.py#L176-L185
26,459
tensorflow/lucid
lucid/recipes/activation_atlas/layout.py
aligned_umap
def aligned_umap(activations, umap_options={}, normalize=True, verbose=False): """`activations` can be a list of ndarrays. In that case a list of layouts is returned.""" umap_defaults = dict( n_components=2, n_neighbors=50, min_dist=0.05, verbose=verbose, metric="cosine" ) umap_defaults.update(...
python
def aligned_umap(activations, umap_options={}, normalize=True, verbose=False): """`activations` can be a list of ndarrays. In that case a list of layouts is returned.""" umap_defaults = dict( n_components=2, n_neighbors=50, min_dist=0.05, verbose=verbose, metric="cosine" ) umap_defaults.update(...
[ "def", "aligned_umap", "(", "activations", ",", "umap_options", "=", "{", "}", ",", "normalize", "=", "True", ",", "verbose", "=", "False", ")", ":", "umap_defaults", "=", "dict", "(", "n_components", "=", "2", ",", "n_neighbors", "=", "50", ",", "min_di...
`activations` can be a list of ndarrays. In that case a list of layouts is returned.
[ "activations", "can", "be", "a", "list", "of", "ndarrays", ".", "In", "that", "case", "a", "list", "of", "layouts", "is", "returned", "." ]
d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e
https://github.com/tensorflow/lucid/blob/d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e/lucid/recipes/activation_atlas/layout.py#L46-L74
26,460
tensorflow/lucid
lucid/scratch/atlas_pipeline/render_tile.py
render_tile
def render_tile(cells, ti, tj, render, params, metadata, layout, summary): """ Render each cell in the tile and stitch it into a single image """ image_size = params["cell_size"] * params["n_tile"] tile = Image.new("RGB", (image_size, image_size), (255,255,255)) keys = cells.keys() for i,key in enumerat...
python
def render_tile(cells, ti, tj, render, params, metadata, layout, summary): """ Render each cell in the tile and stitch it into a single image """ image_size = params["cell_size"] * params["n_tile"] tile = Image.new("RGB", (image_size, image_size), (255,255,255)) keys = cells.keys() for i,key in enumerat...
[ "def", "render_tile", "(", "cells", ",", "ti", ",", "tj", ",", "render", ",", "params", ",", "metadata", ",", "layout", ",", "summary", ")", ":", "image_size", "=", "params", "[", "\"cell_size\"", "]", "*", "params", "[", "\"n_tile\"", "]", "tile", "="...
Render each cell in the tile and stitch it into a single image
[ "Render", "each", "cell", "in", "the", "tile", "and", "stitch", "it", "into", "a", "single", "image" ]
d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e
https://github.com/tensorflow/lucid/blob/d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e/lucid/scratch/atlas_pipeline/render_tile.py#L11-L51
26,461
tensorflow/lucid
lucid/scratch/atlas_pipeline/render_tile.py
aggregate_tile
def aggregate_tile(cells, ti, tj, aggregate, params, metadata, layout, summary): """ Call the user defined aggregation function on each cell and combine into a single json object """ tile = [] keys = cells.keys() for i,key in enumerate(keys): print("cell", i+1, "/", len(keys), end='\r') cell_json ...
python
def aggregate_tile(cells, ti, tj, aggregate, params, metadata, layout, summary): """ Call the user defined aggregation function on each cell and combine into a single json object """ tile = [] keys = cells.keys() for i,key in enumerate(keys): print("cell", i+1, "/", len(keys), end='\r') cell_json ...
[ "def", "aggregate_tile", "(", "cells", ",", "ti", ",", "tj", ",", "aggregate", ",", "params", ",", "metadata", ",", "layout", ",", "summary", ")", ":", "tile", "=", "[", "]", "keys", "=", "cells", ".", "keys", "(", ")", "for", "i", ",", "key", "i...
Call the user defined aggregation function on each cell and combine into a single json object
[ "Call", "the", "user", "defined", "aggregation", "function", "on", "each", "cell", "and", "combine", "into", "a", "single", "json", "object" ]
d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e
https://github.com/tensorflow/lucid/blob/d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e/lucid/scratch/atlas_pipeline/render_tile.py#L54-L64
26,462
tensorflow/lucid
lucid/misc/gl/glcontext.py
create_opengl_context
def create_opengl_context(surface_size=(640, 480)): """Create offscreen OpenGL context and make it current. Users are expected to directly use EGL API in case more advanced context management is required. Args: surface_size: (width, height), size of the offscreen rendering surface. """ egl_display = e...
python
def create_opengl_context(surface_size=(640, 480)): """Create offscreen OpenGL context and make it current. Users are expected to directly use EGL API in case more advanced context management is required. Args: surface_size: (width, height), size of the offscreen rendering surface. """ egl_display = e...
[ "def", "create_opengl_context", "(", "surface_size", "=", "(", "640", ",", "480", ")", ")", ":", "egl_display", "=", "egl", ".", "eglGetDisplay", "(", "egl", ".", "EGL_DEFAULT_DISPLAY", ")", "major", ",", "minor", "=", "egl", ".", "EGLint", "(", ")", ","...
Create offscreen OpenGL context and make it current. Users are expected to directly use EGL API in case more advanced context management is required. Args: surface_size: (width, height), size of the offscreen rendering surface.
[ "Create", "offscreen", "OpenGL", "context", "and", "make", "it", "current", "." ]
d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e
https://github.com/tensorflow/lucid/blob/d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e/lucid/misc/gl/glcontext.py#L79-L120
26,463
tensorflow/lucid
lucid/optvis/param/resize_bilinear_nd.py
resize_bilinear_nd
def resize_bilinear_nd(t, target_shape): """Bilinear resizes a tensor t to have shape target_shape. This function bilinearly resizes a n-dimensional tensor by iteratively applying tf.image.resize_bilinear (which can only resize 2 dimensions). For bilinear interpolation, the order in which it is applied does no...
python
def resize_bilinear_nd(t, target_shape): """Bilinear resizes a tensor t to have shape target_shape. This function bilinearly resizes a n-dimensional tensor by iteratively applying tf.image.resize_bilinear (which can only resize 2 dimensions). For bilinear interpolation, the order in which it is applied does no...
[ "def", "resize_bilinear_nd", "(", "t", ",", "target_shape", ")", ":", "shape", "=", "t", ".", "get_shape", "(", ")", ".", "as_list", "(", ")", "target_shape", "=", "list", "(", "target_shape", ")", "assert", "len", "(", "shape", ")", "==", "len", "(", ...
Bilinear resizes a tensor t to have shape target_shape. This function bilinearly resizes a n-dimensional tensor by iteratively applying tf.image.resize_bilinear (which can only resize 2 dimensions). For bilinear interpolation, the order in which it is applied does not matter. Args: t: tensor to be resized...
[ "Bilinear", "resizes", "a", "tensor", "t", "to", "have", "shape", "target_shape", "." ]
d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e
https://github.com/tensorflow/lucid/blob/d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e/lucid/optvis/param/resize_bilinear_nd.py#L68-L116
26,464
tensorflow/lucid
lucid/modelzoo/aligned_activations.py
get_aligned_activations
def get_aligned_activations(layer): """Downloads 100k activations of the specified layer sampled from iterating over ImageNet. Activations of all layers where sampled at the same spatial positions for each image, allowing the calculation of correlations.""" activation_paths = [ PATH_TEMPLATE.for...
python
def get_aligned_activations(layer): """Downloads 100k activations of the specified layer sampled from iterating over ImageNet. Activations of all layers where sampled at the same spatial positions for each image, allowing the calculation of correlations.""" activation_paths = [ PATH_TEMPLATE.for...
[ "def", "get_aligned_activations", "(", "layer", ")", ":", "activation_paths", "=", "[", "PATH_TEMPLATE", ".", "format", "(", "sanitize", "(", "layer", ".", "model_class", ".", "name", ")", ",", "sanitize", "(", "layer", ".", "name", ")", ",", "page", ")", ...
Downloads 100k activations of the specified layer sampled from iterating over ImageNet. Activations of all layers where sampled at the same spatial positions for each image, allowing the calculation of correlations.
[ "Downloads", "100k", "activations", "of", "the", "specified", "layer", "sampled", "from", "iterating", "over", "ImageNet", ".", "Activations", "of", "all", "layers", "where", "sampled", "at", "the", "same", "spatial", "positions", "for", "each", "image", "allowi...
d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e
https://github.com/tensorflow/lucid/blob/d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e/lucid/modelzoo/aligned_activations.py#L35-L47
26,465
tensorflow/lucid
lucid/modelzoo/aligned_activations.py
layer_covariance
def layer_covariance(layer1, layer2=None): """Computes the covariance matrix between the neurons of two layers. If only one layer is passed, computes the symmetric covariance matrix of that layer.""" layer2 = layer2 or layer1 act1, act2 = layer1.activations, layer2.activations num_datapoints = act1....
python
def layer_covariance(layer1, layer2=None): """Computes the covariance matrix between the neurons of two layers. If only one layer is passed, computes the symmetric covariance matrix of that layer.""" layer2 = layer2 or layer1 act1, act2 = layer1.activations, layer2.activations num_datapoints = act1....
[ "def", "layer_covariance", "(", "layer1", ",", "layer2", "=", "None", ")", ":", "layer2", "=", "layer2", "or", "layer1", "act1", ",", "act2", "=", "layer1", ".", "activations", ",", "layer2", ".", "activations", "num_datapoints", "=", "act1", ".", "shape",...
Computes the covariance matrix between the neurons of two layers. If only one layer is passed, computes the symmetric covariance matrix of that layer.
[ "Computes", "the", "covariance", "matrix", "between", "the", "neurons", "of", "two", "layers", ".", "If", "only", "one", "layer", "is", "passed", "computes", "the", "symmetric", "covariance", "matrix", "of", "that", "layer", "." ]
d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e
https://github.com/tensorflow/lucid/blob/d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e/lucid/modelzoo/aligned_activations.py#L51-L57
26,466
tensorflow/lucid
lucid/modelzoo/aligned_activations.py
push_activations
def push_activations(activations, from_layer, to_layer): """Push activations from one model to another using prerecorded correlations""" inverse_covariance_matrix = layer_inverse_covariance(from_layer) activations_decorrelated = np.dot(inverse_covariance_matrix, activations.T).T covariance_matrix = laye...
python
def push_activations(activations, from_layer, to_layer): """Push activations from one model to another using prerecorded correlations""" inverse_covariance_matrix = layer_inverse_covariance(from_layer) activations_decorrelated = np.dot(inverse_covariance_matrix, activations.T).T covariance_matrix = laye...
[ "def", "push_activations", "(", "activations", ",", "from_layer", ",", "to_layer", ")", ":", "inverse_covariance_matrix", "=", "layer_inverse_covariance", "(", "from_layer", ")", "activations_decorrelated", "=", "np", ".", "dot", "(", "inverse_covariance_matrix", ",", ...
Push activations from one model to another using prerecorded correlations
[ "Push", "activations", "from", "one", "model", "to", "another", "using", "prerecorded", "correlations" ]
d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e
https://github.com/tensorflow/lucid/blob/d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e/lucid/modelzoo/aligned_activations.py#L66-L72
26,467
tensorflow/lucid
lucid/recipes/image_interpolation_params.py
multi_interpolation_basis
def multi_interpolation_basis(n_objectives=6, n_interp_steps=5, width=128, channels=3): """A paramaterization for interpolating between each pair of N objectives. Sometimes you want to interpolate between optimizing a bunch of objectives, in a paramaterization that encourages images...
python
def multi_interpolation_basis(n_objectives=6, n_interp_steps=5, width=128, channels=3): """A paramaterization for interpolating between each pair of N objectives. Sometimes you want to interpolate between optimizing a bunch of objectives, in a paramaterization that encourages images...
[ "def", "multi_interpolation_basis", "(", "n_objectives", "=", "6", ",", "n_interp_steps", "=", "5", ",", "width", "=", "128", ",", "channels", "=", "3", ")", ":", "N", ",", "M", ",", "W", ",", "Ch", "=", "n_objectives", ",", "n_interp_steps", ",", "wid...
A paramaterization for interpolating between each pair of N objectives. Sometimes you want to interpolate between optimizing a bunch of objectives, in a paramaterization that encourages images to align. Args: n_objectives: number of objectives you want interpolate between n_interp_steps: number of inter...
[ "A", "paramaterization", "for", "interpolating", "between", "each", "pair", "of", "N", "objectives", "." ]
d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e
https://github.com/tensorflow/lucid/blob/d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e/lucid/recipes/image_interpolation_params.py#L22-L82
26,468
tensorflow/lucid
lucid/optvis/overrides/gradient_override.py
register_to_random_name
def register_to_random_name(grad_f): """Register a gradient function to a random string. In order to use a custom gradient in TensorFlow, it must be registered to a string. This is both a hassle, and -- because only one function can every be registered to a string -- annoying to iterate on in an interactive ...
python
def register_to_random_name(grad_f): """Register a gradient function to a random string. In order to use a custom gradient in TensorFlow, it must be registered to a string. This is both a hassle, and -- because only one function can every be registered to a string -- annoying to iterate on in an interactive ...
[ "def", "register_to_random_name", "(", "grad_f", ")", ":", "grad_f_name", "=", "grad_f", ".", "__name__", "+", "\"_\"", "+", "str", "(", "uuid", ".", "uuid4", "(", ")", ")", "tf", ".", "RegisterGradient", "(", "grad_f_name", ")", "(", "grad_f", ")", "ret...
Register a gradient function to a random string. In order to use a custom gradient in TensorFlow, it must be registered to a string. This is both a hassle, and -- because only one function can every be registered to a string -- annoying to iterate on in an interactive environemnt. This function registers a ...
[ "Register", "a", "gradient", "function", "to", "a", "random", "string", "." ]
d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e
https://github.com/tensorflow/lucid/blob/d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e/lucid/optvis/overrides/gradient_override.py#L50-L73
26,469
tensorflow/lucid
lucid/optvis/overrides/gradient_override.py
use_gradient
def use_gradient(grad_f): """Decorator for easily setting custom gradients for TensorFlow functions. * DO NOT use this function if you need to serialize your graph. * This function will cause the decorated function to run slower. Example: def _foo_grad(op, grad): ... @use_gradient(_foo_grad) def...
python
def use_gradient(grad_f): """Decorator for easily setting custom gradients for TensorFlow functions. * DO NOT use this function if you need to serialize your graph. * This function will cause the decorated function to run slower. Example: def _foo_grad(op, grad): ... @use_gradient(_foo_grad) def...
[ "def", "use_gradient", "(", "grad_f", ")", ":", "grad_f_name", "=", "register_to_random_name", "(", "grad_f", ")", "def", "function_wrapper", "(", "f", ")", ":", "def", "inner", "(", "*", "inputs", ")", ":", "# TensorFlow only supports (as of writing) overriding the...
Decorator for easily setting custom gradients for TensorFlow functions. * DO NOT use this function if you need to serialize your graph. * This function will cause the decorated function to run slower. Example: def _foo_grad(op, grad): ... @use_gradient(_foo_grad) def foo(x1, x2, x3): ... Args: ...
[ "Decorator", "for", "easily", "setting", "custom", "gradients", "for", "TensorFlow", "functions", "." ]
d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e
https://github.com/tensorflow/lucid/blob/d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e/lucid/optvis/overrides/gradient_override.py#L107-L178
26,470
tensorflow/lucid
lucid/optvis/param/spatial.py
pixel_image
def pixel_image(shape, sd=None, init_val=None): """A naive, pixel-based image parameterization. Defaults to a random initialization, but can take a supplied init_val argument instead. Args: shape: shape of resulting image, [batch, width, height, channels]. sd: standard deviation of param in...
python
def pixel_image(shape, sd=None, init_val=None): """A naive, pixel-based image parameterization. Defaults to a random initialization, but can take a supplied init_val argument instead. Args: shape: shape of resulting image, [batch, width, height, channels]. sd: standard deviation of param in...
[ "def", "pixel_image", "(", "shape", ",", "sd", "=", "None", ",", "init_val", "=", "None", ")", ":", "if", "sd", "is", "not", "None", "and", "init_val", "is", "not", "None", ":", "warnings", ".", "warn", "(", "\"`pixel_image` received both an initial value an...
A naive, pixel-based image parameterization. Defaults to a random initialization, but can take a supplied init_val argument instead. Args: shape: shape of resulting image, [batch, width, height, channels]. sd: standard deviation of param initialization noise. init_val: an initial value to...
[ "A", "naive", "pixel", "-", "based", "image", "parameterization", ".", "Defaults", "to", "a", "random", "initialization", "but", "can", "take", "a", "supplied", "init_val", "argument", "instead", "." ]
d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e
https://github.com/tensorflow/lucid/blob/d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e/lucid/optvis/param/spatial.py#L24-L45
26,471
tensorflow/lucid
lucid/optvis/param/spatial.py
rfft2d_freqs
def rfft2d_freqs(h, w): """Computes 2D spectrum frequencies.""" fy = np.fft.fftfreq(h)[:, None] # when we have an odd input dimension we need to keep one additional # frequency and later cut off 1 pixel if w % 2 == 1: fx = np.fft.fftfreq(w)[: w // 2 + 2] else: fx = np.fft.fftfre...
python
def rfft2d_freqs(h, w): """Computes 2D spectrum frequencies.""" fy = np.fft.fftfreq(h)[:, None] # when we have an odd input dimension we need to keep one additional # frequency and later cut off 1 pixel if w % 2 == 1: fx = np.fft.fftfreq(w)[: w // 2 + 2] else: fx = np.fft.fftfre...
[ "def", "rfft2d_freqs", "(", "h", ",", "w", ")", ":", "fy", "=", "np", ".", "fft", ".", "fftfreq", "(", "h", ")", "[", ":", ",", "None", "]", "# when we have an odd input dimension we need to keep one additional", "# frequency and later cut off 1 pixel", "if", "w",...
Computes 2D spectrum frequencies.
[ "Computes", "2D", "spectrum", "frequencies", "." ]
d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e
https://github.com/tensorflow/lucid/blob/d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e/lucid/optvis/param/spatial.py#L48-L58
26,472
tensorflow/lucid
lucid/optvis/param/spatial.py
fft_image
def fft_image(shape, sd=None, decay_power=1): """An image paramaterization using 2D Fourier coefficients.""" sd = sd or 0.01 batch, h, w, ch = shape freqs = rfft2d_freqs(h, w) init_val_size = (2, ch) + freqs.shape images = [] for _ in range(batch): # Create a random variable holdin...
python
def fft_image(shape, sd=None, decay_power=1): """An image paramaterization using 2D Fourier coefficients.""" sd = sd or 0.01 batch, h, w, ch = shape freqs = rfft2d_freqs(h, w) init_val_size = (2, ch) + freqs.shape images = [] for _ in range(batch): # Create a random variable holdin...
[ "def", "fft_image", "(", "shape", ",", "sd", "=", "None", ",", "decay_power", "=", "1", ")", ":", "sd", "=", "sd", "or", "0.01", "batch", ",", "h", ",", "w", ",", "ch", "=", "shape", "freqs", "=", "rfft2d_freqs", "(", "h", ",", "w", ")", "init_...
An image paramaterization using 2D Fourier coefficients.
[ "An", "image", "paramaterization", "using", "2D", "Fourier", "coefficients", "." ]
d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e
https://github.com/tensorflow/lucid/blob/d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e/lucid/optvis/param/spatial.py#L61-L93
26,473
tensorflow/lucid
lucid/optvis/param/spatial.py
laplacian_pyramid_image
def laplacian_pyramid_image(shape, n_levels=4, sd=None): """Simple laplacian pyramid paramaterization of an image. For more flexibility, use a sum of lowres_tensor()s. Args: shape: shape of resulting image, [batch, width, height, channels]. n_levels: number of levels of laplacian pyarmid. ...
python
def laplacian_pyramid_image(shape, n_levels=4, sd=None): """Simple laplacian pyramid paramaterization of an image. For more flexibility, use a sum of lowres_tensor()s. Args: shape: shape of resulting image, [batch, width, height, channels]. n_levels: number of levels of laplacian pyarmid. ...
[ "def", "laplacian_pyramid_image", "(", "shape", ",", "n_levels", "=", "4", ",", "sd", "=", "None", ")", ":", "batch_dims", "=", "shape", "[", ":", "-", "3", "]", "w", ",", "h", ",", "ch", "=", "shape", "[", "-", "3", ":", "]", "pyramid", "=", "...
Simple laplacian pyramid paramaterization of an image. For more flexibility, use a sum of lowres_tensor()s. Args: shape: shape of resulting image, [batch, width, height, channels]. n_levels: number of levels of laplacian pyarmid. sd: standard deviation of param initialization. Returns: ...
[ "Simple", "laplacian", "pyramid", "paramaterization", "of", "an", "image", "." ]
d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e
https://github.com/tensorflow/lucid/blob/d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e/lucid/optvis/param/spatial.py#L96-L115
26,474
tensorflow/lucid
lucid/optvis/param/spatial.py
bilinearly_sampled_image
def bilinearly_sampled_image(texture, uv): """Build bilinear texture sampling graph. Coordinate transformation rules match OpenGL GL_REPEAT wrapping and GL_LINEAR interpolation modes. Args: texture: [tex_h, tex_w, channel_n] tensor. uv: [frame_h, frame_h, 2] tensor with per-pixel UV coordi...
python
def bilinearly_sampled_image(texture, uv): """Build bilinear texture sampling graph. Coordinate transformation rules match OpenGL GL_REPEAT wrapping and GL_LINEAR interpolation modes. Args: texture: [tex_h, tex_w, channel_n] tensor. uv: [frame_h, frame_h, 2] tensor with per-pixel UV coordi...
[ "def", "bilinearly_sampled_image", "(", "texture", ",", "uv", ")", ":", "h", ",", "w", "=", "tf", ".", "unstack", "(", "tf", ".", "shape", "(", "texture", ")", "[", ":", "2", "]", ")", "u", ",", "v", "=", "tf", ".", "split", "(", "uv", ",", "...
Build bilinear texture sampling graph. Coordinate transformation rules match OpenGL GL_REPEAT wrapping and GL_LINEAR interpolation modes. Args: texture: [tex_h, tex_w, channel_n] tensor. uv: [frame_h, frame_h, 2] tensor with per-pixel UV coordinates in range [0..1] Returns: [frame_h...
[ "Build", "bilinear", "texture", "sampling", "graph", "." ]
d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e
https://github.com/tensorflow/lucid/blob/d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e/lucid/optvis/param/spatial.py#L118-L149
26,475
tensorflow/lucid
lucid/modelzoo/other_models/InceptionV1.py
_populate_inception_bottlenecks
def _populate_inception_bottlenecks(scope): """Add Inception bottlenecks and their pre-Relu versions to the graph.""" graph = tf.get_default_graph() for op in graph.get_operations(): if op.name.startswith(scope+'/') and 'Concat' in op.type: name = op.name.split('/')[1] pre_relus = [] for tow...
python
def _populate_inception_bottlenecks(scope): """Add Inception bottlenecks and their pre-Relu versions to the graph.""" graph = tf.get_default_graph() for op in graph.get_operations(): if op.name.startswith(scope+'/') and 'Concat' in op.type: name = op.name.split('/')[1] pre_relus = [] for tow...
[ "def", "_populate_inception_bottlenecks", "(", "scope", ")", ":", "graph", "=", "tf", ".", "get_default_graph", "(", ")", "for", "op", "in", "graph", ".", "get_operations", "(", ")", ":", "if", "op", ".", "name", ".", "startswith", "(", "scope", "+", "'/...
Add Inception bottlenecks and their pre-Relu versions to the graph.
[ "Add", "Inception", "bottlenecks", "and", "their", "pre", "-", "Relu", "versions", "to", "the", "graph", "." ]
d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e
https://github.com/tensorflow/lucid/blob/d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e/lucid/modelzoo/other_models/InceptionV1.py#L22-L34
26,476
tensorflow/lucid
lucid/optvis/objectives.py
wrap_objective
def wrap_objective(f, *args, **kwds): """Decorator for creating Objective factories. Changes f from the closure: (args) => () => TF Tensor into an Obejective factory: (args) => Objective while perserving function name, arg info, docs... for interactive python. """ objective_func = f(*args, **kwds) objec...
python
def wrap_objective(f, *args, **kwds): """Decorator for creating Objective factories. Changes f from the closure: (args) => () => TF Tensor into an Obejective factory: (args) => Objective while perserving function name, arg info, docs... for interactive python. """ objective_func = f(*args, **kwds) objec...
[ "def", "wrap_objective", "(", "f", ",", "*", "args", ",", "*", "*", "kwds", ")", ":", "objective_func", "=", "f", "(", "*", "args", ",", "*", "*", "kwds", ")", "objective_name", "=", "f", ".", "__name__", "args_str", "=", "\" [\"", "+", "\", \"", "...
Decorator for creating Objective factories. Changes f from the closure: (args) => () => TF Tensor into an Obejective factory: (args) => Objective while perserving function name, arg info, docs... for interactive python.
[ "Decorator", "for", "creating", "Objective", "factories", "." ]
d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e
https://github.com/tensorflow/lucid/blob/d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e/lucid/optvis/objectives.py#L117-L129
26,477
tensorflow/lucid
lucid/optvis/objectives.py
neuron
def neuron(layer_name, channel_n, x=None, y=None, batch=None): """Visualize a single neuron of a single channel. Defaults to the center neuron. When width and height are even numbers, we choose the neuron in the bottom right of the center 2x2 neurons. Odd width & height: Even width & height: ...
python
def neuron(layer_name, channel_n, x=None, y=None, batch=None): """Visualize a single neuron of a single channel. Defaults to the center neuron. When width and height are even numbers, we choose the neuron in the bottom right of the center 2x2 neurons. Odd width & height: Even width & height: ...
[ "def", "neuron", "(", "layer_name", ",", "channel_n", ",", "x", "=", "None", ",", "y", "=", "None", ",", "batch", "=", "None", ")", ":", "def", "inner", "(", "T", ")", ":", "layer", "=", "T", "(", "layer_name", ")", "shape", "=", "tf", ".", "sh...
Visualize a single neuron of a single channel. Defaults to the center neuron. When width and height are even numbers, we choose the neuron in the bottom right of the center 2x2 neurons. Odd width & height: Even width & height: +---+---+---+ +---+---+---+---+ | | | | ...
[ "Visualize", "a", "single", "neuron", "of", "a", "single", "channel", "." ]
d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e
https://github.com/tensorflow/lucid/blob/d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e/lucid/optvis/objectives.py#L133-L161
26,478
tensorflow/lucid
lucid/optvis/objectives.py
channel
def channel(layer, n_channel, batch=None): """Visualize a single channel""" if batch is None: return lambda T: tf.reduce_mean(T(layer)[..., n_channel]) else: return lambda T: tf.reduce_mean(T(layer)[batch, ..., n_channel])
python
def channel(layer, n_channel, batch=None): """Visualize a single channel""" if batch is None: return lambda T: tf.reduce_mean(T(layer)[..., n_channel]) else: return lambda T: tf.reduce_mean(T(layer)[batch, ..., n_channel])
[ "def", "channel", "(", "layer", ",", "n_channel", ",", "batch", "=", "None", ")", ":", "if", "batch", "is", "None", ":", "return", "lambda", "T", ":", "tf", ".", "reduce_mean", "(", "T", "(", "layer", ")", "[", "...", ",", "n_channel", "]", ")", ...
Visualize a single channel
[ "Visualize", "a", "single", "channel" ]
d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e
https://github.com/tensorflow/lucid/blob/d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e/lucid/optvis/objectives.py#L165-L170
26,479
tensorflow/lucid
lucid/optvis/objectives.py
direction
def direction(layer, vec, batch=None, cossim_pow=0): """Visualize a direction""" if batch is None: vec = vec[None, None, None] return lambda T: _dot_cossim(T(layer), vec) else: vec = vec[None, None] return lambda T: _dot_cossim(T(layer)[batch], vec)
python
def direction(layer, vec, batch=None, cossim_pow=0): """Visualize a direction""" if batch is None: vec = vec[None, None, None] return lambda T: _dot_cossim(T(layer), vec) else: vec = vec[None, None] return lambda T: _dot_cossim(T(layer)[batch], vec)
[ "def", "direction", "(", "layer", ",", "vec", ",", "batch", "=", "None", ",", "cossim_pow", "=", "0", ")", ":", "if", "batch", "is", "None", ":", "vec", "=", "vec", "[", "None", ",", "None", ",", "None", "]", "return", "lambda", "T", ":", "_dot_c...
Visualize a direction
[ "Visualize", "a", "direction" ]
d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e
https://github.com/tensorflow/lucid/blob/d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e/lucid/optvis/objectives.py#L189-L196
26,480
tensorflow/lucid
lucid/optvis/objectives.py
L1
def L1(layer="input", constant=0, batch=None): """L1 norm of layer. Generally used as penalty.""" if batch is None: return lambda T: tf.reduce_sum(tf.abs(T(layer) - constant)) else: return lambda T: tf.reduce_sum(tf.abs(T(layer)[batch] - constant))
python
def L1(layer="input", constant=0, batch=None): """L1 norm of layer. Generally used as penalty.""" if batch is None: return lambda T: tf.reduce_sum(tf.abs(T(layer) - constant)) else: return lambda T: tf.reduce_sum(tf.abs(T(layer)[batch] - constant))
[ "def", "L1", "(", "layer", "=", "\"input\"", ",", "constant", "=", "0", ",", "batch", "=", "None", ")", ":", "if", "batch", "is", "None", ":", "return", "lambda", "T", ":", "tf", ".", "reduce_sum", "(", "tf", ".", "abs", "(", "T", "(", "layer", ...
L1 norm of layer. Generally used as penalty.
[ "L1", "norm", "of", "layer", ".", "Generally", "used", "as", "penalty", "." ]
d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e
https://github.com/tensorflow/lucid/blob/d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e/lucid/optvis/objectives.py#L247-L252
26,481
tensorflow/lucid
lucid/optvis/objectives.py
L2
def L2(layer="input", constant=0, epsilon=1e-6, batch=None): """L2 norm of layer. Generally used as penalty.""" if batch is None: return lambda T: tf.sqrt(epsilon + tf.reduce_sum((T(layer) - constant) ** 2)) else: return lambda T: tf.sqrt(epsilon + tf.reduce_sum((T(layer)[batch] - constant) ** 2))
python
def L2(layer="input", constant=0, epsilon=1e-6, batch=None): """L2 norm of layer. Generally used as penalty.""" if batch is None: return lambda T: tf.sqrt(epsilon + tf.reduce_sum((T(layer) - constant) ** 2)) else: return lambda T: tf.sqrt(epsilon + tf.reduce_sum((T(layer)[batch] - constant) ** 2))
[ "def", "L2", "(", "layer", "=", "\"input\"", ",", "constant", "=", "0", ",", "epsilon", "=", "1e-6", ",", "batch", "=", "None", ")", ":", "if", "batch", "is", "None", ":", "return", "lambda", "T", ":", "tf", ".", "sqrt", "(", "epsilon", "+", "tf"...
L2 norm of layer. Generally used as penalty.
[ "L2", "norm", "of", "layer", ".", "Generally", "used", "as", "penalty", "." ]
d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e
https://github.com/tensorflow/lucid/blob/d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e/lucid/optvis/objectives.py#L256-L261
26,482
tensorflow/lucid
lucid/optvis/objectives.py
blur_input_each_step
def blur_input_each_step(): """Minimizing this objective is equivelant to blurring input each step. Optimizing (-k)*blur_input_each_step() is equivelant to: input <- (1-k)*input + k*blur(input) An operation that was used in early feature visualization work. See Nguyen, et al., 2015. """ def inner(T):...
python
def blur_input_each_step(): """Minimizing this objective is equivelant to blurring input each step. Optimizing (-k)*blur_input_each_step() is equivelant to: input <- (1-k)*input + k*blur(input) An operation that was used in early feature visualization work. See Nguyen, et al., 2015. """ def inner(T):...
[ "def", "blur_input_each_step", "(", ")", ":", "def", "inner", "(", "T", ")", ":", "t_input", "=", "T", "(", "\"input\"", ")", "t_input_blurred", "=", "tf", ".", "stop_gradient", "(", "_tf_blur", "(", "t_input", ")", ")", "return", "0.5", "*", "tf", "."...
Minimizing this objective is equivelant to blurring input each step. Optimizing (-k)*blur_input_each_step() is equivelant to: input <- (1-k)*input + k*blur(input) An operation that was used in early feature visualization work. See Nguyen, et al., 2015.
[ "Minimizing", "this", "objective", "is", "equivelant", "to", "blurring", "input", "each", "step", "." ]
d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e
https://github.com/tensorflow/lucid/blob/d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e/lucid/optvis/objectives.py#L277-L291
26,483
tensorflow/lucid
lucid/optvis/objectives.py
channel_interpolate
def channel_interpolate(layer1, n_channel1, layer2, n_channel2): """Interpolate between layer1, n_channel1 and layer2, n_channel2. Optimize for a convex combination of layer1, n_channel1 and layer2, n_channel2, transitioning across the batch. Args: layer1: layer to optimize 100% at batch=0. n_channel1...
python
def channel_interpolate(layer1, n_channel1, layer2, n_channel2): """Interpolate between layer1, n_channel1 and layer2, n_channel2. Optimize for a convex combination of layer1, n_channel1 and layer2, n_channel2, transitioning across the batch. Args: layer1: layer to optimize 100% at batch=0. n_channel1...
[ "def", "channel_interpolate", "(", "layer1", ",", "n_channel1", ",", "layer2", ",", "n_channel2", ")", ":", "def", "inner", "(", "T", ")", ":", "batch_n", "=", "T", "(", "layer1", ")", ".", "get_shape", "(", ")", ".", "as_list", "(", ")", "[", "0", ...
Interpolate between layer1, n_channel1 and layer2, n_channel2. Optimize for a convex combination of layer1, n_channel1 and layer2, n_channel2, transitioning across the batch. Args: layer1: layer to optimize 100% at batch=0. n_channel1: neuron index to optimize 100% at batch=0. layer2: layer to optim...
[ "Interpolate", "between", "layer1", "n_channel1", "and", "layer2", "n_channel2", "." ]
d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e
https://github.com/tensorflow/lucid/blob/d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e/lucid/optvis/objectives.py#L303-L328
26,484
tensorflow/lucid
lucid/optvis/objectives.py
penalize_boundary_complexity
def penalize_boundary_complexity(shp, w=20, mask=None, C=0.5): """Encourage the boundaries of an image to have less variation and of color C. Args: shp: shape of T("input") because this may not be known. w: width of boundary to penalize. Ignored if mask is set. mask: mask describing what area should be...
python
def penalize_boundary_complexity(shp, w=20, mask=None, C=0.5): """Encourage the boundaries of an image to have less variation and of color C. Args: shp: shape of T("input") because this may not be known. w: width of boundary to penalize. Ignored if mask is set. mask: mask describing what area should be...
[ "def", "penalize_boundary_complexity", "(", "shp", ",", "w", "=", "20", ",", "mask", "=", "None", ",", "C", "=", "0.5", ")", ":", "def", "inner", "(", "T", ")", ":", "arr", "=", "T", "(", "\"input\"", ")", "# print shp", "if", "mask", "is", "None",...
Encourage the boundaries of an image to have less variation and of color C. Args: shp: shape of T("input") because this may not be known. w: width of boundary to penalize. Ignored if mask is set. mask: mask describing what area should be penalized. Returns: Objective.
[ "Encourage", "the", "boundaries", "of", "an", "image", "to", "have", "less", "variation", "and", "of", "color", "C", "." ]
d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e
https://github.com/tensorflow/lucid/blob/d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e/lucid/optvis/objectives.py#L332-L358
26,485
tensorflow/lucid
lucid/optvis/objectives.py
alignment
def alignment(layer, decay_ratio=2): """Encourage neighboring images to be similar. When visualizing the interpolation between two objectives, it's often desireable to encourage analagous boejcts to be drawn in the same position, to make them more comparable. This term penalizes L2 distance between neighbor...
python
def alignment(layer, decay_ratio=2): """Encourage neighboring images to be similar. When visualizing the interpolation between two objectives, it's often desireable to encourage analagous boejcts to be drawn in the same position, to make them more comparable. This term penalizes L2 distance between neighbor...
[ "def", "alignment", "(", "layer", ",", "decay_ratio", "=", "2", ")", ":", "def", "inner", "(", "T", ")", ":", "batch_n", "=", "T", "(", "layer", ")", ".", "get_shape", "(", ")", ".", "as_list", "(", ")", "[", "0", "]", "arr", "=", "T", "(", "...
Encourage neighboring images to be similar. When visualizing the interpolation between two objectives, it's often desireable to encourage analagous boejcts to be drawn in the same position, to make them more comparable. This term penalizes L2 distance between neighboring images, as evaluated at layer. In...
[ "Encourage", "neighboring", "images", "to", "be", "similar", "." ]
d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e
https://github.com/tensorflow/lucid/blob/d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e/lucid/optvis/objectives.py#L362-L393
26,486
tensorflow/lucid
lucid/optvis/objectives.py
diversity
def diversity(layer): """Encourage diversity between each batch element. A neural net feature often responds to multiple things, but naive feature visualization often only shows us one. If you optimize a batch of images, this objective will encourage them all to be different. In particular, it caculuates th...
python
def diversity(layer): """Encourage diversity between each batch element. A neural net feature often responds to multiple things, but naive feature visualization often only shows us one. If you optimize a batch of images, this objective will encourage them all to be different. In particular, it caculuates th...
[ "def", "diversity", "(", "layer", ")", ":", "def", "inner", "(", "T", ")", ":", "layer_t", "=", "T", "(", "layer", ")", "batch_n", ",", "_", ",", "_", ",", "channels", "=", "layer_t", ".", "get_shape", "(", ")", ".", "as_list", "(", ")", "flatten...
Encourage diversity between each batch element. A neural net feature often responds to multiple things, but naive feature visualization often only shows us one. If you optimize a batch of images, this objective will encourage them all to be different. In particular, it caculuates the correlation matrix of act...
[ "Encourage", "diversity", "between", "each", "batch", "element", "." ]
d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e
https://github.com/tensorflow/lucid/blob/d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e/lucid/optvis/objectives.py#L396-L425
26,487
tensorflow/lucid
lucid/optvis/objectives.py
input_diff
def input_diff(orig_img): """Average L2 difference between optimized image and orig_img. This objective is usually mutliplied by a negative number and used as a penalty in making advarsarial counterexamples. """ def inner(T): diff = T("input") - orig_img return tf.sqrt(tf.reduce_mean(diff**2)) retu...
python
def input_diff(orig_img): """Average L2 difference between optimized image and orig_img. This objective is usually mutliplied by a negative number and used as a penalty in making advarsarial counterexamples. """ def inner(T): diff = T("input") - orig_img return tf.sqrt(tf.reduce_mean(diff**2)) retu...
[ "def", "input_diff", "(", "orig_img", ")", ":", "def", "inner", "(", "T", ")", ":", "diff", "=", "T", "(", "\"input\"", ")", "-", "orig_img", "return", "tf", ".", "sqrt", "(", "tf", ".", "reduce_mean", "(", "diff", "**", "2", ")", ")", "return", ...
Average L2 difference between optimized image and orig_img. This objective is usually mutliplied by a negative number and used as a penalty in making advarsarial counterexamples.
[ "Average", "L2", "difference", "between", "optimized", "image", "and", "orig_img", "." ]
d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e
https://github.com/tensorflow/lucid/blob/d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e/lucid/optvis/objectives.py#L429-L438
26,488
tensorflow/lucid
lucid/optvis/objectives.py
class_logit
def class_logit(layer, label): """Like channel, but for softmax layers. Args: layer: A layer name string. label: Either a string (refering to a label in model.labels) or an int label position. Returns: Objective maximizing a logit. """ def inner(T): if isinstance(label, int): cla...
python
def class_logit(layer, label): """Like channel, but for softmax layers. Args: layer: A layer name string. label: Either a string (refering to a label in model.labels) or an int label position. Returns: Objective maximizing a logit. """ def inner(T): if isinstance(label, int): cla...
[ "def", "class_logit", "(", "layer", ",", "label", ")", ":", "def", "inner", "(", "T", ")", ":", "if", "isinstance", "(", "label", ",", "int", ")", ":", "class_n", "=", "label", "else", ":", "class_n", "=", "T", "(", "\"labels\"", ")", ".", "index",...
Like channel, but for softmax layers. Args: layer: A layer name string. label: Either a string (refering to a label in model.labels) or an int label position. Returns: Objective maximizing a logit.
[ "Like", "channel", "but", "for", "softmax", "layers", "." ]
d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e
https://github.com/tensorflow/lucid/blob/d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e/lucid/optvis/objectives.py#L442-L461
26,489
tensorflow/lucid
lucid/optvis/objectives.py
as_objective
def as_objective(obj): """Convert obj into Objective class. Strings of the form "layer:n" become the Objective channel(layer, n). Objectives are returned unchanged. Args: obj: string or Objective. Returns: Objective """ if isinstance(obj, Objective): return obj elif callable(obj): ret...
python
def as_objective(obj): """Convert obj into Objective class. Strings of the form "layer:n" become the Objective channel(layer, n). Objectives are returned unchanged. Args: obj: string or Objective. Returns: Objective """ if isinstance(obj, Objective): return obj elif callable(obj): ret...
[ "def", "as_objective", "(", "obj", ")", ":", "if", "isinstance", "(", "obj", ",", "Objective", ")", ":", "return", "obj", "elif", "callable", "(", "obj", ")", ":", "return", "obj", "elif", "isinstance", "(", "obj", ",", "str", ")", ":", "layer", ",",...
Convert obj into Objective class. Strings of the form "layer:n" become the Objective channel(layer, n). Objectives are returned unchanged. Args: obj: string or Objective. Returns: Objective
[ "Convert", "obj", "into", "Objective", "class", "." ]
d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e
https://github.com/tensorflow/lucid/blob/d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e/lucid/optvis/objectives.py#L464-L483
26,490
tensorflow/lucid
lucid/optvis/param/unit_balls.py
_constrain_L2_grad
def _constrain_L2_grad(op, grad): """Gradient for constrained optimization on an L2 unit ball. This function projects the gradient onto the ball if you are on the boundary (or outside!), but leaves it untouched if you are inside the ball. Args: op: the tensorflow op we're computing the gradient for. g...
python
def _constrain_L2_grad(op, grad): """Gradient for constrained optimization on an L2 unit ball. This function projects the gradient onto the ball if you are on the boundary (or outside!), but leaves it untouched if you are inside the ball. Args: op: the tensorflow op we're computing the gradient for. g...
[ "def", "_constrain_L2_grad", "(", "op", ",", "grad", ")", ":", "inp", "=", "op", ".", "inputs", "[", "0", "]", "inp_norm", "=", "tf", ".", "norm", "(", "inp", ")", "unit_inp", "=", "inp", "/", "inp_norm", "grad_projection", "=", "dot", "(", "unit_inp...
Gradient for constrained optimization on an L2 unit ball. This function projects the gradient onto the ball if you are on the boundary (or outside!), but leaves it untouched if you are inside the ball. Args: op: the tensorflow op we're computing the gradient for. grad: gradient we need to backprop Re...
[ "Gradient", "for", "constrained", "optimization", "on", "an", "L2", "unit", "ball", "." ]
d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e
https://github.com/tensorflow/lucid/blob/d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e/lucid/optvis/param/unit_balls.py#L20-L47
26,491
tensorflow/lucid
lucid/optvis/param/unit_balls.py
unit_ball_L2
def unit_ball_L2(shape): """A tensorflow variable tranfomed to be constrained in a L2 unit ball. EXPERIMENTAL: Do not use for adverserial examples if you need to be confident they are strong attacks. We are not yet confident in this code. """ x = tf.Variable(tf.zeros(shape)) return constrain_L2(x)
python
def unit_ball_L2(shape): """A tensorflow variable tranfomed to be constrained in a L2 unit ball. EXPERIMENTAL: Do not use for adverserial examples if you need to be confident they are strong attacks. We are not yet confident in this code. """ x = tf.Variable(tf.zeros(shape)) return constrain_L2(x)
[ "def", "unit_ball_L2", "(", "shape", ")", ":", "x", "=", "tf", ".", "Variable", "(", "tf", ".", "zeros", "(", "shape", ")", ")", "return", "constrain_L2", "(", "x", ")" ]
A tensorflow variable tranfomed to be constrained in a L2 unit ball. EXPERIMENTAL: Do not use for adverserial examples if you need to be confident they are strong attacks. We are not yet confident in this code.
[ "A", "tensorflow", "variable", "tranfomed", "to", "be", "constrained", "in", "a", "L2", "unit", "ball", "." ]
d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e
https://github.com/tensorflow/lucid/blob/d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e/lucid/optvis/param/unit_balls.py#L55-L62
26,492
tensorflow/lucid
lucid/optvis/param/unit_balls.py
unit_ball_L_inf
def unit_ball_L_inf(shape, precondition=True): """A tensorflow variable tranfomed to be constrained in a L_inf unit ball. Note that this code also preconditions the gradient to go in the L_inf direction of steepest descent. EXPERIMENTAL: Do not use for adverserial examples if you need to be confident they a...
python
def unit_ball_L_inf(shape, precondition=True): """A tensorflow variable tranfomed to be constrained in a L_inf unit ball. Note that this code also preconditions the gradient to go in the L_inf direction of steepest descent. EXPERIMENTAL: Do not use for adverserial examples if you need to be confident they a...
[ "def", "unit_ball_L_inf", "(", "shape", ",", "precondition", "=", "True", ")", ":", "x", "=", "tf", ".", "Variable", "(", "tf", ".", "zeros", "(", "shape", ")", ")", "if", "precondition", ":", "return", "constrain_L_inf_precondition", "(", "x", ")", "els...
A tensorflow variable tranfomed to be constrained in a L_inf unit ball. Note that this code also preconditions the gradient to go in the L_inf direction of steepest descent. EXPERIMENTAL: Do not use for adverserial examples if you need to be confident they are strong attacks. We are not yet confident in this ...
[ "A", "tensorflow", "variable", "tranfomed", "to", "be", "constrained", "in", "a", "L_inf", "unit", "ball", "." ]
d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e
https://github.com/tensorflow/lucid/blob/d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e/lucid/optvis/param/unit_balls.py#L106-L119
26,493
tensorflow/lucid
lucid/optvis/render.py
render_vis
def render_vis(model, objective_f, param_f=None, optimizer=None, transforms=None, thresholds=(512,), print_objectives=None, verbose=True, relu_gradient_override=True, use_fixed_seed=False): """Flexible optimization-base feature vis. There's a lot of ways one might wish to customize ot...
python
def render_vis(model, objective_f, param_f=None, optimizer=None, transforms=None, thresholds=(512,), print_objectives=None, verbose=True, relu_gradient_override=True, use_fixed_seed=False): """Flexible optimization-base feature vis. There's a lot of ways one might wish to customize ot...
[ "def", "render_vis", "(", "model", ",", "objective_f", ",", "param_f", "=", "None", ",", "optimizer", "=", "None", ",", "transforms", "=", "None", ",", "thresholds", "=", "(", "512", ",", ")", ",", "print_objectives", "=", "None", ",", "verbose", "=", ...
Flexible optimization-base feature vis. There's a lot of ways one might wish to customize otpimization-based feature visualization. It's hard to create an abstraction that stands up to all the things one might wish to try. This function probably can't do *everything* you want, but it's much more flexible th...
[ "Flexible", "optimization", "-", "base", "feature", "vis", "." ]
d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e
https://github.com/tensorflow/lucid/blob/d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e/lucid/optvis/render.py#L44-L115
26,494
tensorflow/lucid
lucid/optvis/render.py
make_vis_T
def make_vis_T(model, objective_f, param_f=None, optimizer=None, transforms=None, relu_gradient_override=False): """Even more flexible optimization-base feature vis. This function is the inner core of render_vis(), and can be used when render_vis() isn't flexible enough. Unfortunately, it's a bit ...
python
def make_vis_T(model, objective_f, param_f=None, optimizer=None, transforms=None, relu_gradient_override=False): """Even more flexible optimization-base feature vis. This function is the inner core of render_vis(), and can be used when render_vis() isn't flexible enough. Unfortunately, it's a bit ...
[ "def", "make_vis_T", "(", "model", ",", "objective_f", ",", "param_f", "=", "None", ",", "optimizer", "=", "None", ",", "transforms", "=", "None", ",", "relu_gradient_override", "=", "False", ")", ":", "# pylint: disable=unused-variable", "t_image", "=", "make_t...
Even more flexible optimization-base feature vis. This function is the inner core of render_vis(), and can be used when render_vis() isn't flexible enough. Unfortunately, it's a bit more tedious to use: > with tf.Graph().as_default() as graph, tf.Session() as sess: > > T = make_vis_T(model, "mixed4a_p...
[ "Even", "more", "flexible", "optimization", "-", "base", "feature", "vis", "." ]
d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e
https://github.com/tensorflow/lucid/blob/d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e/lucid/optvis/render.py#L118-L192
26,495
tensorflow/lucid
lucid/scratch/atlas_pipeline/grid.py
write_grid_local
def write_grid_local(tiles, params): """ Write a file for each tile """ # TODO: this isn't being used right now, will need to be # ported to gfile if we want to keep it for ti,tj,tile in enumerate_tiles(tiles): filename = "{directory}/{name}/tile_{n_layer}_{n_tile}_{ti}_{tj}".format(ti=ti, tj=tj, **para...
python
def write_grid_local(tiles, params): """ Write a file for each tile """ # TODO: this isn't being used right now, will need to be # ported to gfile if we want to keep it for ti,tj,tile in enumerate_tiles(tiles): filename = "{directory}/{name}/tile_{n_layer}_{n_tile}_{ti}_{tj}".format(ti=ti, tj=tj, **para...
[ "def", "write_grid_local", "(", "tiles", ",", "params", ")", ":", "# TODO: this isn't being used right now, will need to be", "# ported to gfile if we want to keep it", "for", "ti", ",", "tj", ",", "tile", "in", "enumerate_tiles", "(", "tiles", ")", ":", "filename", "="...
Write a file for each tile
[ "Write", "a", "file", "for", "each", "tile" ]
d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e
https://github.com/tensorflow/lucid/blob/d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e/lucid/scratch/atlas_pipeline/grid.py#L70-L84
26,496
tensorflow/lucid
lucid/misc/io/loading.py
_load_img
def _load_img(handle, target_dtype=np.float32, size=None, **kwargs): """Load image file as numpy array.""" image_pil = PIL.Image.open(handle, **kwargs) # resize the image to the requested size, if one was specified if size is not None: if len(size) > 2: size = size[:2] ...
python
def _load_img(handle, target_dtype=np.float32, size=None, **kwargs): """Load image file as numpy array.""" image_pil = PIL.Image.open(handle, **kwargs) # resize the image to the requested size, if one was specified if size is not None: if len(size) > 2: size = size[:2] ...
[ "def", "_load_img", "(", "handle", ",", "target_dtype", "=", "np", ".", "float32", ",", "size", "=", "None", ",", "*", "*", "kwargs", ")", ":", "image_pil", "=", "PIL", ".", "Image", ".", "open", "(", "handle", ",", "*", "*", "kwargs", ")", "# resi...
Load image file as numpy array.
[ "Load", "image", "file", "as", "numpy", "array", "." ]
d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e
https://github.com/tensorflow/lucid/blob/d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e/lucid/misc/io/loading.py#L47-L78
26,497
tensorflow/lucid
lucid/misc/io/loading.py
_load_text
def _load_text(handle, split=False, encoding="utf-8"): """Load and decode a string.""" string = handle.read().decode(encoding) return string.splitlines() if split else string
python
def _load_text(handle, split=False, encoding="utf-8"): """Load and decode a string.""" string = handle.read().decode(encoding) return string.splitlines() if split else string
[ "def", "_load_text", "(", "handle", ",", "split", "=", "False", ",", "encoding", "=", "\"utf-8\"", ")", ":", "string", "=", "handle", ".", "read", "(", ")", ".", "decode", "(", "encoding", ")", "return", "string", ".", "splitlines", "(", ")", "if", "...
Load and decode a string.
[ "Load", "and", "decode", "a", "string", "." ]
d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e
https://github.com/tensorflow/lucid/blob/d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e/lucid/misc/io/loading.py#L86-L89
26,498
tensorflow/lucid
lucid/misc/io/loading.py
load
def load(url_or_handle, cache=None, **kwargs): """Load a file. File format is inferred from url. File retrieval strategy is inferred from URL. Returned object type is inferred from url extension. Args: url_or_handle: a (reachable) URL, or an already open file handle Raises: RuntimeErr...
python
def load(url_or_handle, cache=None, **kwargs): """Load a file. File format is inferred from url. File retrieval strategy is inferred from URL. Returned object type is inferred from url extension. Args: url_or_handle: a (reachable) URL, or an already open file handle Raises: RuntimeErr...
[ "def", "load", "(", "url_or_handle", ",", "cache", "=", "None", ",", "*", "*", "kwargs", ")", ":", "ext", "=", "get_extension", "(", "url_or_handle", ")", "try", ":", "loader", "=", "loaders", "[", "ext", ".", "lower", "(", ")", "]", "message", "=", ...
Load a file. File format is inferred from url. File retrieval strategy is inferred from URL. Returned object type is inferred from url extension. Args: url_or_handle: a (reachable) URL, or an already open file handle Raises: RuntimeError: If file extension or URL is not supported.
[ "Load", "a", "file", "." ]
d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e
https://github.com/tensorflow/lucid/blob/d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e/lucid/misc/io/loading.py#L120-L152
26,499
tensorflow/lucid
lucid/optvis/transform.py
crop_or_pad_to
def crop_or_pad_to(height, width): """Ensures the specified spatial shape by either padding or cropping. Meant to be used as a last transform for architectures insisting on a specific spatial shape of their inputs. """ def inner(t_image): return tf.image.resize_image_with_crop_or_pad(t_image...
python
def crop_or_pad_to(height, width): """Ensures the specified spatial shape by either padding or cropping. Meant to be used as a last transform for architectures insisting on a specific spatial shape of their inputs. """ def inner(t_image): return tf.image.resize_image_with_crop_or_pad(t_image...
[ "def", "crop_or_pad_to", "(", "height", ",", "width", ")", ":", "def", "inner", "(", "t_image", ")", ":", "return", "tf", ".", "image", ".", "resize_image_with_crop_or_pad", "(", "t_image", ",", "height", ",", "width", ")", "return", "inner" ]
Ensures the specified spatial shape by either padding or cropping. Meant to be used as a last transform for architectures insisting on a specific spatial shape of their inputs.
[ "Ensures", "the", "specified", "spatial", "shape", "by", "either", "padding", "or", "cropping", ".", "Meant", "to", "be", "used", "as", "a", "last", "transform", "for", "architectures", "insisting", "on", "a", "specific", "spatial", "shape", "of", "their", "...
d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e
https://github.com/tensorflow/lucid/blob/d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e/lucid/optvis/transform.py#L154-L161