text_prompt
stringlengths
157
13.1k
code_prompt
stringlengths
7
19.8k
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 ])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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: json.dump(export, jsonfile, ensure_ascii=False)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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, text in enumerate(conversation): if self.show_training_progress: utils.print_progress_bar( 'List Trainer', ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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_progress(members): sys.stdout.write('.') for member in members: # Thi...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def remove(self, statement_text): """ Removes the statement that matches the input text. Removes any responses from statements where the response text matches th...
Statement = self.get_model('statement') session = self.Session() query = session.query(Statement).filter_by(text=statement_text) record = query.first() session.delete(record) self._session_finish(session)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def filter(self, **kwargs): """ Returns a list of objects from the database. The kwargs parameter can contain any number of attributes. Only objects which contai...
from sqlalchemy import or_ Statement = self.get_model('statement') Tag = self.get_model('tag') session = self.Session() page_size = kwargs.pop('page_size', 1000) order_by = kwargs.pop('order_by', None) tags = kwargs.pop('tags', []) exclude_text = kwarg...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 = None if hasattr(statement, 'id') and statement.id is not None: record = session.query(Statement).get(statement.id...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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_index = random.randrange(0, count) random_statement = session.query(Statement)[random_index...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_database(self): """ Populate the database with the tables. """
from chatterbot.ext.sqlalchemy_app.models import Base Base.metadata.create_all(self.engine)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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({ 'text': [ 'The attribute "text" is required.' ] }, status=400) response = self.chatterbot.get_response(input_dat...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 dotted_path parts = dotted_path.split('.') if parts[0] == 'chatterbot': parts.pop(0) parts[0] = DATA_...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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, recursive=True) else: paths.append(corpus_path) paths.sort() return paths
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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) categories = corpus_data.get('categories', []) yield corpus, categories, file_path
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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: text = text_without_punctuation document = self.nlp(text) if len(text) <= 2: bigram_pairs ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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( text=statement.text, search_text=self.tagger.get_bigram_pair_string(stat...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def remove(self, statement_text): """ Removes the statement that matches the input text. Removes any responses from statements if the response text matches the i...
Statement = self.get_model('statement') statements = Statement.objects.filter(text=statement_text) statements.delete()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 whitespace statement.text = statement.text.strip() # Remove consecutive spaces statement.text = re.sub(' +', ' ', ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 sum(num_list)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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() == 'pm': hour += 12 return {'hours': hour, 'minutes': minute}
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 [ datetime(year, month_start, 1), datetime(year, month_end, calendar.monthrange(year, month_end)...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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.month, base_date.day) ord = convert_string_to_number(ordinal) if dow in year_variations: if time == 'this' or time == 'coming': ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 adverb_date.today() elif name == 'yesterday': return adverb_date - timedelta(days=1) elif name == 'tomorrow' or...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 = base_date - timedelta(days=day_of_week + 1) day = start_of_this_week + t...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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.group(), function(match, base_date), match.span())) # Wrap the matched text with TAG element to prevent nested selec...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def search(self, input_statement, **additional_parameters): """ Search for close matches to the input. Confidence scores for subsequent results will order of inc...
self.chatbot.logger.info('Beginning search for close text match') input_search_text = input_statement.search_text if not input_statement.search_text: self.chatbot.logger.warn( 'No value for search_text was available on the provided input' ) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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') self.usr_input.grid(column=1, row=0, sticky='nesw', padx=3, pady=3) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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.insert( tk.END, "Human: " + user_input + "\n" + "ChatBot: " + str(response.text) + "\n" ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def SvelteComponent(name, path): """Display svelte components in iPython. Args: name: name of svelte component (must match component filename when built) path: p...
if path[-3:] == ".js": js_path = path elif path[-5:] == ".html": print("Trying to build svelte component from html...") js_path = build_svelte(path) js_content = read(js_path, mode='r') def inner(data): id_str = js_id(name) html = _template \ .replace("$js", js_content) \ .r...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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, **object) elif type(object) is list: np.savez(path, *object) else: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 format from handle's url ext. else: raise ValueError("Can only save_img for...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 nee...
is_handle = hasattr(url_or_handle, "write") and hasattr(url_or_handle, "name") if is_handle: _, ext = os.path.splitext(url_or_handle.name) else: _, ext = os.path.splitext(url_or_handle) if not ext: raise RuntimeError("No extension in URL: " + url_or_handle) if ext in savers...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 - bottom) M[3, 1] = (top + bottom) / (top - bottom) M[2, 2] = -(zfar + znear) / (zfar ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def anorm(x, axis=None, keepdims=False): """Compute L2 norms alogn specified axes."""
return np.sqrt((x*x).sum(axis=axis, keepdims=keepdims))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def normalize(v, axis=None, eps=1e-10): """L2 Normalize along specified axes."""
return v / max(anorm(v, axis=axis, keepdims=True), eps)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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.dot(eye) return M
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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(...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def activations(self): """Loads sampled activations, which requires network access."""
if self._activations is None: self._activations = _get_aligned_activations(self) return self._activations
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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: t_prep_input = model_util.forget_xy(t_prep_input) if hasattr(self, "is_BGR") and se...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 multiple instances of the model.') % scope t_input, t_prep_input = self.create_input(t_input, forget_xy_shape) tf.import_graph_def...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 retu...
umap_defaults = dict( n_components=2, n_neighbors=50, min_dist=0.05, verbose=verbose, metric="cosine" ) umap_defaults.update(umap_options) # if passed a list of activations, we combine them and later split the layouts if type(activations) is list or type(activations) is tuple: num...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 enumerate(keys): print("cell", i+1, "/", len(keys), end='\r') cell_image = render(cells[key], params, metadata, layout, summary) # stitch this render...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def aggregate_tile(cells, ti, tj, aggregate, params, metadata, layout, summary): """ Call the user defined aggregation function on each cell and combine into a s...
tile = [] keys = cells.keys() for i,key in enumerate(keys): print("cell", i+1, "/", len(keys), end='\r') cell_json = aggregate(cells[key], params, metadata, layout, summary) tile.append({"aggregate":cell_json, "i":int(key[0]), "j":int(key[1])}) return tile
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 mo...
egl_display = egl.eglGetDisplay(egl.EGL_DEFAULT_DISPLAY) major, minor = egl.EGLint(), egl.EGLint() egl.eglInitialize(egl_display, pointer(major), pointer(minor)) config_attribs = [ egl.EGL_SURFACE_TYPE, egl.EGL_PBUFFER_BIT, egl.EGL_BLUE_SIZE, 8, egl.EGL_GREEN_SIZE, 8, egl.EGL_RED_SIZE, 8, egl.EGL...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 it...
shape = t.get_shape().as_list() target_shape = list(target_shape) assert len(shape) == len(target_shape) # We progressively move through the shape, resizing dimensions... d = 0 while d < len(shape): # If we don't need to deal with the next dimesnion, step over it if shape[d] == target_shape[d]: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_aligned_activations(layer): """Downloads 100k activations of the specified layer sampled from iterating over ImageNet. Activations of all layers where sa...
activation_paths = [ PATH_TEMPLATE.format( sanitize(layer.model_class.name), sanitize(layer.name), page ) for page in range(NUMBER_OF_PAGES) ] activations = np.vstack([load(path) for path in activation_paths]) assert np.all(np.isfinite(activations)) return activa...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def layer_covariance(layer1, layer2=None): """Computes the covariance matrix between the neurons of two layers. If only one layer is passed, computes the symmetr...
layer2 = layer2 or layer1 act1, act2 = layer1.activations, layer2.activations num_datapoints = act1.shape[0] # cast to avoid numpy type promotion during division return np.matmul(act1.T, act2) / float(num_datapoints)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 = layer_covariance(from_layer, to_layer) activation_recorrelated = np.dot(activations_decorrelated, covariance_matrix) return activation_r...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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...
N, M, W, Ch = n_objectives, n_interp_steps, width, channels const_term = sum([lowres_tensor([W, W, Ch], [W//k, W//k, Ch]) for k in [1, 2, 4, 8]]) const_term = tf.reshape(const_term, [1, 1, 1, W, W, Ch]) example_interps = [ sum([lowres_tensor([M, W, W, Ch], [2, W//k, W//k, Ch]) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 t...
grad_f_name = grad_f.__name__ + "_" + str(uuid.uuid4()) tf.RegisterGradient(grad_f_name)(grad_f) return grad_f_name
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 gra...
grad_f_name = register_to_random_name(grad_f) def function_wrapper(f): def inner(*inputs): # TensorFlow only supports (as of writing) overriding the gradient of # individual ops. In order to override the gardient of `f`, we need to # somehow make it appear to be an individual TensorFlow op....
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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...
if sd is not None and init_val is not None: warnings.warn( "`pixel_image` received both an initial value and a sd argument. Ignoring sd in favor of the supplied initial value." ) sd = sd or 0.01 init_val = init_val or np.random.normal(size=shape, scale=sd).astype(np.float32) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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.fftfreq(w)[: w // 2 + 1] return np.sqrt(fx * fx + fy * fy)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 holding the actual 2D fourier coefficients init_val = np.random.normal(size=init_val_size, scale=sd).astype(np...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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_tens...
batch_dims = shape[:-3] w, h, ch = shape[-3:] pyramid = 0 for n in range(n_levels): k = 2 ** n pyramid += lowres_tensor(shape, batch_dims + (w // k, h // k, ch), sd=sd) return pyramid
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def bilinearly_sampled_image(texture, uv): """Build bilinear texture sampling graph. Coordinate transformation rules match OpenGL GL_REPEAT wrapping and GL_LINEA...
h, w = tf.unstack(tf.shape(texture)[:2]) u, v = tf.split(uv, 2, axis=-1) v = 1.0 - v # vertical flip to match GL convention u, v = u * tf.to_float(w) - 0.5, v * tf.to_float(h) - 0.5 u0, u1 = tf.floor(u), tf.ceil(u) v0, v1 = tf.floor(v), tf.ceil(v) uf, vf = u - u0, v - v0 u0, u1, v0, v1...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 tower in op.inputs[1:]: if tower.op.type == 'Relu': tower = tower.op.inputs[0] pre_relus.append(...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def wrap_objective(f, *args, **kwds): """Decorator for creating Objective factories. Changes f from the closure: (args) => () => TF Tensor into an Obejective fac...
objective_func = f(*args, **kwds) objective_name = f.__name__ args_str = " [" + ", ".join([_make_arg_str(arg) for arg in args]) + "]" description = objective_name.title() + args_str return Objective(objective_func, objective_name, description)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 he...
def inner(T): layer = T(layer_name) shape = tf.shape(layer) x_ = shape[1] // 2 if x is None else x y_ = shape[2] // 2 if y is None else y if batch is None: return layer[:, x_, y_, channel_n] else: return layer[batch, x_, y_, channel_n] return inner
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def blur_input_each_step(): """Minimizing this objective is equivelant to blurring input each step. Optimizing (-k)*blur_input_each_step() is equivelant to: inpu...
def inner(T): t_input = T("input") t_input_blurred = tf.stop_gradient(_tf_blur(t_input)) return 0.5*tf.reduce_sum((t_input - t_input_blurred)**2) return inner
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def channel_interpolate(layer1, n_channel1, layer2, n_channel2): """Interpolate between layer1, n_channel1 and layer2, n_channel2. Optimize for a convex combinat...
def inner(T): batch_n = T(layer1).get_shape().as_list()[0] arr1 = T(layer1)[..., n_channel1] arr2 = T(layer2)[..., n_channel2] weights = (np.arange(batch_n)/float(batch_n-1)) S = 0 for n in range(batch_n): S += (1-weights[n]) * tf.reduce_mean(arr1[n]) S += weights[n] * tf.reduce_m...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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...
def inner(T): arr = T("input") # print shp if mask is None: mask_ = np.ones(shp) mask_[:, w:-w, w:-w] = 0 else: mask_ = mask blur = _tf_blur(arr, w=5) diffs = (blur-arr)**2 diffs += 0.8*(arr-C)**2 return -tf.reduce_sum(diffs*mask_) return inner
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def alignment(layer, decay_ratio=2): """Encourage neighboring images to be similar. When visualizing the interpolation between two objectives, it's often desirea...
def inner(T): batch_n = T(layer).get_shape().as_list()[0] arr = T(layer) accum = 0 for d in [1, 2, 3, 4]: for i in range(batch_n - d): a, b = i, i+d arr1, arr2 = arr[a], arr[b] accum += tf.reduce_mean((arr1-arr2)**2) / decay_ratio**float(d) return -accum return inn...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def diversity(layer): """Encourage diversity between each batch element. A neural net feature often responds to multiple things, but naive feature visualization ...
def inner(T): layer_t = T(layer) batch_n, _, _, channels = layer_t.get_shape().as_list() flattened = tf.reshape(layer_t, [batch_n, -1, channels]) grams = tf.matmul(flattened, flattened, transpose_a=True) grams = tf.nn.l2_normalize(grams, axis=[1,2], epsilon=1e-10) return sum([ sum([ tf.redu...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 ...
def inner(T): diff = T("input") - orig_img return tf.sqrt(tf.reduce_mean(diff**2)) return inner
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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.la...
def inner(T): if isinstance(label, int): class_n = label else: class_n = T("labels").index(label) logits = T(layer) logit = tf.reduce_sum(logits[:, class_n]) return logit return inner
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def as_objective(obj): """Convert obj into Objective class. Strings of the form "layer:n" become the Objective channel(layer, n). Objectives are returned unchang...
if isinstance(obj, Objective): return obj elif callable(obj): return obj elif isinstance(obj, str): layer, n = obj.split(":") layer, n = layer.strip(), int(n) return channel(layer, n)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 th...
inp = op.inputs[0] inp_norm = tf.norm(inp) unit_inp = inp / inp_norm grad_projection = dot(unit_inp, grad) parallel_grad = unit_inp * grad_projection is_in_ball = tf.less_equal(inp_norm, 1) is_pointed_inward = tf.less(grad_projection, 0) allow_grad = tf.logical_or(is_in_ball, is_pointed_inward) cli...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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...
x = tf.Variable(tf.zeros(shape)) return constrain_L2(x)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 ...
x = tf.Variable(tf.zeros(shape)) if precondition: return constrain_L_inf_precondition(x) else: return constrain_L_inf(x)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def render_vis(model, objective_f, param_f=None, optimizer=None, transforms=None, thresholds=(512,), print_objectives=None, verbose=True, relu_gradient_override=T...
with tf.Graph().as_default() as graph, tf.Session() as sess: if use_fixed_seed: # does not mean results are reproducible, see Args doc tf.set_random_seed(0) T = make_vis_T(model, objective_f, param_f, optimizer, transforms, relu_gradient_override) print_objective_func = make_...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def make_vis_T(model, objective_f, param_f=None, optimizer=None, transforms=None, relu_gradient_override=False): """Even more flexible optimization-base feature ...
# pylint: disable=unused-variable t_image = make_t_image(param_f) objective_f = objectives.as_objective(objective_f) transform_f = make_transform_f(transforms) optimizer = make_optimizer(optimizer, []) global_step = tf.train.get_or_create_global_step() init_global_step = tf.variables_initializer([globa...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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, **params) #directory=directory, name=name, n_layer=n_layer, n_tile=n_tile, # w...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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] log.warning("`_load_img()` received size: {}, trimming to first two dims!".format(size)) image_pil = i...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 ty...
ext = get_extension(url_or_handle) try: loader = loaders[ext.lower()] message = "Using inferred loader '%s' due to passed file extension '%s'." log.debug(message, loader.__name__[6:], ext) return load_using_loader(url_or_handle, loader, cache, **kwargs) except KeyError: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 i...
def inner(t_image): return tf.image.resize_image_with_crop_or_pad(t_image, height, width) return inner
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _normalize_array(array, domain=(0, 1)): """Given an arbitrary rank-3 NumPy array, produce one representing an image. This ensures the resulting array has a d...
# first copy the input so we're never mutating the user's data array = np.array(array) # squeeze helps both with batch=1 and B/W and PIL's mode inference array = np.squeeze(array) assert len(array.shape) <= 3 assert np.issubdtype(array.dtype, np.number) assert not np.isnan(array).any() low, high = np....
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _serialize_normalized_array(array, fmt='png', quality=70): """Given a normalized array, returns byte representation of image encoding. Args: array: NumPy arr...
dtype = array.dtype assert np.issubdtype(dtype, np.unsignedinteger) assert np.max(array) <= np.iinfo(dtype).max assert array.shape[-1] > 1 # array dims must have been squeezed image = PIL.Image.fromarray(array) image_bytes = BytesIO() image.save(image_bytes, fmt, quality=quality) # TODO: Python 3 cou...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def serialize_array(array, domain=(0, 1), fmt='png', quality=70): """Given an arbitrary rank-3 NumPy array, returns the byte representation of the encoded image....
normalized = _normalize_array(array, domain=domain) return _serialize_normalized_array(normalized, fmt=fmt, quality=quality)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _apply_flat(cls, f, acts): """Utility for applying f to inner dimension of acts. Flattens acts into a 2D tensor, applies f, then unflattens so that all dimes...
orig_shape = acts.shape acts_flat = acts.reshape([-1, acts.shape[-1]]) new_flat = f(acts_flat) if not isinstance(new_flat, np.ndarray): return new_flat shape = list(orig_shape[:-1]) + [-1] return new_flat.reshape(shape)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _image_url(array, fmt='png', mode="data", quality=90, domain=None): """Create a data URL representing an image from a PIL.Image. Args: image: a numpy mode: p...
supported_modes = ("data") if mode not in supported_modes: message = "Unsupported mode '%s', should be one of '%s'." raise ValueError(message, mode, supported_modes) image_data = serialize_array(array, fmt=fmt, quality=quality) base64_byte_string = base64.b64encode(image_data).decode('ascii') return...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def image(array, domain=None, width=None, format='png', **kwargs): """Display an image. Args: array: NumPy array representing the image fmt: Image format e.g. pn...
image_data = serialize_array(array, fmt=format, domain=domain) image = IPython.display.Image(data=image_data, format=format, width=width) IPython.display.display(image)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def show(thing, domain=(0, 1), **kwargs): """Display a nupmy array without having to specify what it represents. This module will attempt to infer how to display...
if isinstance(thing, np.ndarray): rank = len(thing.shape) if rank == 4: log.debug("Show is assuming rank 4 tensor to be a list of images.") images(thing, domain=domain, **kwargs) elif rank in (2, 3): log.debug("Show is assuming rank 2 or 3 tensor to be an image.") image(thing, dom...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _strip_consts(graph_def, max_const_size=32): """Strip large constant values from graph_def. This is mostly a utility function for graph(), and also originate...
strip_def = tf.GraphDef() for n0 in graph_def.node: n = strip_def.node.add() n.MergeFrom(n0) if n.op == 'Const': tensor = n.attr['value'].tensor size = len(tensor.tensor_content) if size > max_const_size: tensor.tensor_content = tf.com...