Code
stringlengths
103
85.9k
Summary
listlengths
0
94
Please provide a description of the function:def previous_week_day(base_date, weekday): day = base_date - timedelta(days=1) while day.weekday() != weekday: day = day - timedelta(days=1) return day
[ "\n Finds previous weekday\n " ]
Please provide a description of the function: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_week + timedelta(days=1) while day.weekday() != weekday: day = day + timedelta(days=1) r...
[ "\n Finds next weekday\n " ]
Please provide a description of the function:def datetime_parsing(text, base_date=datetime.now()): 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(...
[ "\n Extract datetime objects from a string of text.\n " ]
Please provide a description of the function:def search(self, input_statement, **additional_parameters): 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.logge...
[ "\n Search for close matches to the input. Confidence scores for\n subsequent results will order of increasing value.\n\n :param input_statement: A statement.\n :type input_statement: chatterbot.conversation.Statement\n\n :param **additional_parameters: Additional parameters to be...
Please provide a description of the function:def initialize(self): 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') ...
[ "\n Set window layout.\n " ]
Please provide a description of the function:def get_response(self): 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, ...
[ "\n Get a response from the chatbot and display it.\n " ]
Please provide a description of the function:def add_tags(self, *tags): for _tag in tags: self.tags.get_or_create(name=_tag)
[ "\n Add a list of strings to the statement as tags.\n (Overrides the method from StatementMixin)\n " ]
Please provide a description of the function:def SvelteComponent(name, path): 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_...
[ "Display svelte components in iPython.\n\n Args:\n name: name of svelte component (must match component filename when built)\n path: path to compile svelte .js file or source svelte .html file.\n (If html file, we try to call svelte and build the file.)\n\n Returns:\n A function mapping data to a re...
Please provide a description of the function: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." ]
Please provide a description of the function: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.close() if type(object) is dict: np.savez(path, **obj...
[ "Save dict of numpy array as npz file." ]
Please provide a description of the function:def save_img(object, handle, **kwargs): 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 infe...
[ "Save numpy array as image file on CNS." ]
Please provide a description of the function:def save(thing, url_or_handle, **kwargs): 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...
[ "Save object to file on CNS.\n\n File format is inferred from path. Use save_img(), save_npy(), or save_json()\n if you need to force a particular format.\n\n Args:\n obj: object to save.\n path: CNS path.\n\n Raises:\n RuntimeError: If file extension not supported.\n " ]
Please provide a description of the function:def frustum(left, right, bottom, top, znear, zfar): 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 * znea...
[ "Create view frustum matrix." ]
Please provide a description of the function:def anorm(x, axis=None, keepdims=False): return np.sqrt((x*x).sum(axis=axis, keepdims=keepdims))
[ "Compute L2 norms alogn specified axes." ]
Please provide a description of the function:def normalize(v, axis=None, eps=1e-10): return v / max(anorm(v, axis=axis, keepdims=True), eps)
[ "L2 Normalize along specified axes." ]
Please provide a description of the function:def lookat(eye, target=[0, 0, 0], up=[0, 1, 0]): 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]...
[ "Generate LookAt modelview matrix." ]
Please provide a description of the function: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(...
[]
Please provide a description of the function:def _parse_vertex_tuple(s): vt = [0, 0, 0] for i, c in enumerate(s.split('/')): if c: vt[i] = int(c) return tuple(vt)
[ "Parse vertex indices in '/' separated form (like 'i/j/k', 'i//k' ...)." ]
Please provide a description of the function:def _unify_rows(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
[ "Unify lengths of each row of a." ]
Please provide a description of the function:def load_obj(fn): position = [np.zeros(3, dtype=np.float32)] normal = [np.zeros(3, dtype=np.float32)] uv = [np.zeros(2, dtype=np.float32)] tuple2idx = OrderedDict() trinagle_indices = [] input_file = open(fn) if isinstance(fn, str) else fn for line in ...
[ "Load 3d mesh form .obj' file.\n \n Args:\n fn: Input file name or file-like object.\n \n Returns:\n dictionary with the following keys (some of which may be missing):\n position: np.float32, (n, 3) array, vertex positions\n uv: np.float32, (n, 2) array, vertex uv coordinates\n normal: np...
Please provide a description of the function: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
[]
Please provide a description of the function:def activations(self): if self._activations is None: self._activations = _get_aligned_activations(self) return self._activations
[ "Loads sampled activations, which requires network access." ]
Please provide a description of the function: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) t_prep_input = t_input if len(t_prep_input.shape) == 3: t_prep_input = tf.expand_dims(t_prep_input, 0) if f...
[ "Create input tensor." ]
Please provide a description of the function:def import_graph(self, t_input=None, scope='import', forget_xy_shape=True): graph = tf.get_default_graph() assert graph.unique_name(scope, False) == scope, ( 'Scope "%s" already exists. Provide explicit scope names when ' 'importing multiple inst...
[ "Import model GraphDef into the current graph." ]
Please provide a description of the function:def normalize_layout(layout, min_percentile=1, max_percentile=99, relative_margin=0.1): # compute percentiles mins = np.percentile(layout, min_percentile, axis=(0)) maxs = np.percentile(layout, max_percentile, axis=(0)) # add margins mins -= relati...
[ "Removes outliers and scales layout to between [0,1]." ]
Please provide a description of the function:def aligned_umap(activations, umap_options={}, normalize=True, verbose=False): 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 acti...
[ "`activations` can be a list of ndarrays. In that case a list of layouts is returned." ]
Please provide a description of the function:def render_tile(cells, ti, tj, render, params, metadata, layout, summary): 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,...
[ "\n Render each cell in the tile and stitch it into a single image\n " ]
Please provide a description of the function:def aggregate_tile(cells, ti, tj, aggregate, params, metadata, layout, summary): 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) ...
[ "\n Call the user defined aggregation function on each cell and combine into a single json object\n " ]
Please provide a description of the function:def create_opengl_context(surface_size=(640, 480)): 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, e...
[ "Create offscreen OpenGL context and make it current.\n\n Users are expected to directly use EGL API in case more advanced\n context management is required.\n\n Args:\n surface_size: (width, height), size of the offscreen rendering surface.\n " ]
Please provide a description of the function:def collapse_shape(shape, a, b): shape = list(shape) if a < 0: n_pad = -a pad = n_pad * [1] return collapse_shape(pad + shape, a + n_pad, b + n_pad) if b > len(shape): n_pad = b - len(shape) pad = n_pad * [1] return collapse_shape(shape + pad...
[ "Collapse `shape` outside the interval (`a`,`b`).\n\n This function collapses `shape` outside the interval (`a`,`b`) by\n multiplying the dimensions before `a` into a single dimension,\n and mutliplying the dimensions after `b` into a single dimension.\n\n Args:\n shape: a tensor shape\n a: integer, posit...
Please provide a description of the function:def resize_bilinear_nd(t, target_shape): 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 ...
[ "Bilinear resizes a tensor t to have shape target_shape.\n\n This function bilinearly resizes a n-dimensional tensor by iteratively\n applying tf.image.resize_bilinear (which can only resize 2 dimensions).\n For bilinear interpolation, the order in which it is applied does not matter.\n\n Args:\n t: tensor t...
Please provide a description of the function:def get_aligned_activations(layer): 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 pat...
[ "Downloads 100k activations of the specified layer sampled from iterating over\n ImageNet. Activations of all layers where sampled at the same spatial positions for\n each image, allowing the calculation of correlations." ]
Please provide a description of the function:def layer_covariance(layer1, layer2=None): 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_datap...
[ "Computes the covariance matrix between the neurons of two layers. If only one\n layer is passed, computes the symmetric covariance matrix of that layer." ]
Please provide a description of the function:def push_activations(activations, from_layer, to_layer): 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)...
[ "Push activations from one model to another using prerecorded correlations" ]
Please provide a description of the function:def multi_interpolation_basis(n_objectives=6, n_interp_steps=5, width=128, channels=3): 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 i...
[ "A paramaterization for interpolating between each pair of N objectives.\n\n Sometimes you want to interpolate between optimizing a bunch of objectives,\n in a paramaterization that encourages images to align.\n\n Args:\n n_objectives: number of objectives you want interpolate between\n n_interp_steps: num...
Please provide a description of the function:def register_to_random_name(grad_f): grad_f_name = grad_f.__name__ + "_" + str(uuid.uuid4()) tf.RegisterGradient(grad_f_name)(grad_f) return grad_f_name
[ "Register a gradient function to a random string.\n\n In order to use a custom gradient in TensorFlow, it must be registered to a\n string. This is both a hassle, and -- because only one function can every be\n registered to a string -- annoying to iterate on in an interactive\n environemnt.\n\n This function ...
Please provide a description of the function:def gradient_override_map(override_dict): override_dict_by_name = {} for (op_name, grad_f) in override_dict.items(): if isinstance(grad_f, str): override_dict_by_name[op_name] = grad_f else: override_dict_by_name[op_name] = register_to_random_name...
[ "Convenience wrapper for graph.gradient_override_map().\n\n This functions provides two conveniences over normal tensorflow gradient\n overrides: it auomatically uses the default graph instead of you needing to\n find the graph, and it automatically\n\n Example:\n\n def _foo_grad_alt(op, grad): ...\n\n wi...
Please provide a description of the function: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 gradient of # individual ops. In order to override the gardient of `f`, we ...
[ "Decorator for easily setting custom gradients for TensorFlow functions.\n\n * DO NOT use this function if you need to serialize your graph.\n * This function will cause the decorated function to run slower.\n\n Example:\n\n def _foo_grad(op, grad): ...\n\n @use_gradient(_foo_grad)\n def foo(x1, x2, x3)...
Please provide a description of the function: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 and a sd argument. Ignoring sd in favor of the supplied initial value." ) sd = s...
[ "A naive, pixel-based image parameterization.\n Defaults to a random initialization, but can take a supplied init_val argument\n instead.\n\n Args:\n shape: shape of resulting image, [batch, width, height, channels].\n sd: standard deviation of param initialization noise.\n init_val: an init...
Please provide a description of the function: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 % 2 == 1: fx = np.fft.fftfreq(w)[: w // 2 + 2] else: fx = np.fft....
[ "Computes 2D spectrum frequencies." ]
Please provide a description of the function: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_val_size = (2, ch) + freqs.shape images = [] for _ in range(batch): # Create a random variable holding the actual 2D f...
[ "An image paramaterization using 2D Fourier coefficients." ]
Please provide a description of the function:def laplacian_pyramid_image(shape, n_levels=4, sd=None): 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 p...
[ "Simple laplacian pyramid paramaterization of an image.\n\n For more flexibility, use a sum of lowres_tensor()s.\n\n Args:\n shape: shape of resulting image, [batch, width, height, channels].\n n_levels: number of levels of laplacian pyarmid.\n sd: standard deviation of param initialization.\n\...
Please provide a description of the function:def bilinearly_sampled_image(texture, uv): 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...
[ "Build bilinear texture sampling graph.\n\n Coordinate transformation rules match OpenGL GL_REPEAT wrapping and GL_LINEAR\n interpolation modes.\n\n Args:\n texture: [tex_h, tex_w, channel_n] tensor.\n uv: [frame_h, frame_h, 2] tensor with per-pixel UV coordinates in range [0..1]\n\n Returns:\...
Please provide a description of the function:def _linear_decorelate_color(t): # check that inner dimension is 3? t_flat = tf.reshape(t, [-1, 3]) color_correlation_normalized = color_correlation_svd_sqrt / max_norm_svd_sqrt t_flat = tf.matmul(t_flat, color_correlation_normalized.T) t = tf.reshape(t_flat, tf...
[ "Multiply input by sqrt of emperical (ImageNet) color correlation matrix.\n \n If you interpret t's innermost dimension as describing colors in a\n decorrelated version of the color space (which is a very natural way to\n describe colors -- see discussion in Feature Visualization article) the way\n to map back...
Please provide a description of the function:def to_valid_rgb(t, decorrelate=False, sigmoid=True): if decorrelate: t = _linear_decorelate_color(t) if decorrelate and not sigmoid: t += color_mean if sigmoid: return tf.nn.sigmoid(t) else: return constrain_L_inf(2*t-1)/2 + 0.5
[ "Transform inner dimension of t to valid rgb colors.\n \n In practice this consistes of two parts: \n (1) If requested, transform the colors from a decorrelated color space to RGB.\n (2) Constrain the color channels to be in [0,1], either using a sigmoid\n function or clipping.\n \n Args:\n t: input t...
Please provide a description of the function:def _populate_inception_bottlenecks(scope): 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:]: ...
[ "Add Inception bottlenecks and their pre-Relu versions to the graph." ]
Please provide a description of the function:def wrap_objective(f, *args, **kwds): 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...
[ "Decorator for creating Objective factories.\n\n Changes f from the closure: (args) => () => TF Tensor\n into an Obejective factory: (args) => Objective\n\n while perserving function name, arg info, docs... for interactive python.\n " ]
Please provide a description of the function:def neuron(layer_name, channel_n, x=None, y=None, batch=None): 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_, ...
[ "Visualize a single neuron of a single channel.\n\n Defaults to the center neuron. When width and height are even numbers, we\n choose the neuron in the bottom right of the center 2x2 neurons.\n\n Odd width & height: Even width & height:\n\n +---+---+---+ +---+---+---+---+\n |...
Please provide a description of the function:def channel(layer, n_channel, batch=None): 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])
[ "Visualize a single channel" ]
Please provide a description of the function:def direction(layer, vec, batch=None, cossim_pow=0): 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)
[ "Visualize a direction" ]
Please provide a description of the function:def direction_neuron(layer_name, vec, batch=None, x=None, y=None, cossim_pow=0): 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 ...
[ "Visualize a single (x, y) position along the given direction" ]
Please provide a description of the function:def direction_cossim(layer, vec, batch=None): def inner(T): act_mags = tf.sqrt(tf.reduce_sum(T(layer)**2, -1, keepdims=True)) vec_mag = tf.sqrt(tf.reduce_sum(vec**2)) mags = act_mags * vec_mag if batch is None: return tf.reduce_mean(T(layer) * vec....
[ "Visualize a direction (cossine similarity)" ]
Please provide a description of the function:def L1(layer="input", constant=0, batch=None): 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))
[ "L1 norm of layer. Generally used as penalty." ]
Please provide a description of the function:def L2(layer="input", constant=0, epsilon=1e-6, batch=None): 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))
[ "L2 norm of layer. Generally used as penalty." ]
Please provide a description of the function: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.reduce_sum((t_input - t_input_blurred)**2) return inner
[ "Minimizing this objective is equivelant to blurring input each step.\n\n Optimizing (-k)*blur_input_each_step() is equivelant to:\n\n input <- (1-k)*input + k*blur(input)\n\n An operation that was used in early feature visualization work.\n See Nguyen, et al., 2015.\n " ]
Please provide a description of the function:def channel_interpolate(layer1, n_channel1, layer2, n_channel2): 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 ...
[ "Interpolate between layer1, n_channel1 and layer2, n_channel2.\n\n Optimize for a convex combination of layer1, n_channel1 and\n layer2, n_channel2, transitioning across the batch.\n\n Args:\n layer1: layer to optimize 100% at batch=0.\n n_channel1: neuron index to optimize 100% at batch=0.\n layer2: l...
Please provide a description of the function:def penalize_boundary_complexity(shp, w=20, mask=None, C=0.5): 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 = (blu...
[ "Encourage the boundaries of an image to have less variation and of color C.\n\n Args:\n shp: shape of T(\"input\") because this may not be known.\n w: width of boundary to penalize. Ignored if mask is set.\n mask: mask describing what area should be penalized.\n\n Returns:\n Objective.\n " ]
Please provide a description of the function:def alignment(layer, decay_ratio=2): 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 += t...
[ "Encourage neighboring images to be similar.\n\n When visualizing the interpolation between two objectives, it's often\n desireable to encourage analagous boejcts to be drawn in the same position,\n to make them more comparable.\n\n This term penalizes L2 distance between neighboring images, as evaluated at\n ...
Please provide a description of the function:def diversity(layer): 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_normal...
[ "Encourage diversity between each batch element.\n\n A neural net feature often responds to multiple things, but naive feature\n visualization often only shows us one. If you optimize a batch of images,\n this objective will encourage them all to be different.\n\n In particular, it caculuates the correlation ma...
Please provide a description of the function:def input_diff(orig_img): def inner(T): diff = T("input") - orig_img return tf.sqrt(tf.reduce_mean(diff**2)) return inner
[ "Average L2 difference between optimized image and orig_img.\n\n This objective is usually mutliplied by a negative number and used as a\n penalty in making advarsarial counterexamples.\n " ]
Please provide a description of the function:def class_logit(layer, label): 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
[ "Like channel, but for softmax layers.\n\n Args:\n layer: A layer name string.\n label: Either a string (refering to a label in model.labels) or an int\n label position.\n\n Returns:\n Objective maximizing a logit.\n " ]
Please provide a description of the function:def as_objective(obj): 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)
[ "Convert obj into Objective class.\n\n Strings of the form \"layer:n\" become the Objective channel(layer, n).\n Objectives are returned unchanged.\n\n Args:\n obj: string or Objective.\n\n Returns:\n Objective\n " ]
Please provide a description of the function: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, grad) parallel_grad = unit_inp * grad_projection is_in_ball = tf.less_equal(inp_norm, 1) is_pointed_inward = tf.less(grad...
[ "Gradient for constrained optimization on an L2 unit ball.\n\n This function projects the gradient onto the ball if you are on the boundary\n (or outside!), but leaves it untouched if you are inside the ball.\n\n Args:\n op: the tensorflow op we're computing the gradient for.\n grad: gradient we need to ba...
Please provide a description of the function: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.\n\n EXPERIMENTAL: Do not use for adverserial examples if you need to be confident\n they are strong attacks. We are not yet confident in this code.\n " ]
Please provide a description of the function:def unit_ball_L_inf(shape, precondition=True): x = tf.Variable(tf.zeros(shape)) if precondition: return constrain_L_inf_precondition(x) else: return constrain_L_inf(x)
[ "A tensorflow variable tranfomed to be constrained in a L_inf unit ball.\n\n Note that this code also preconditions the gradient to go in the L_inf\n direction of steepest descent.\n\n EXPERIMENTAL: Do not use for adverserial examples if you need to be confident\n they are strong attacks. We are not yet confide...
Please provide a description of the function: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): with tf.Graph().as_default() as graph, tf.Session...
[ "Flexible optimization-base feature vis.\n\n There's a lot of ways one might wish to customize otpimization-based\n feature visualization. It's hard to create an abstraction that stands up\n to all the things one might wish to try.\n\n This function probably can't do *everything* you want, but it's much more\n ...
Please provide a description of the function: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_image(param_f) objective_f = objectives.as_objective(objective_f) transform_f = make...
[ "Even more flexible optimization-base feature vis.\n\n This function is the inner core of render_vis(), and can be used\n when render_vis() isn't flexible enough. Unfortunately, it's a bit more\n tedious to use:\n\n > with tf.Graph().as_default() as graph, tf.Session() as sess:\n >\n > T = make_vis_T(mode...
Please provide a description of the function:def grid(metadata, layout, params): x = layout["x"] y = layout["y"] x_min = np.min(x) x_max = np.max(x) y_min = np.min(y) y_max = np.max(y) # this creates the grid bins = np.linspace(x_min, x_max, params["n_layer"] - 1) xd = np.digitize(x, bins) bins ...
[ "\n layout: numpy arrays x, y\n metadata: user-defined numpy arrays with metadata\n n_layer: number of cells in the layer (squared)\n n_tile: number of cells in the tile (squared)\n " ]
Please provide a description of the function: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 = "{directory}/{name}/tile_{n_layer}_{n_tile}_{ti}_{tj}".format(ti=ti, tj=tj,...
[ "\n Write a file for each tile\n " ]
Please provide a description of the function:def enumerate_tiles(tiles): enumerated = [] for key in tiles.keys(): enumerated.append((key[0], key[1], tiles[key])) return enumerated
[ "\n Convenience\n " ]
Please provide a description of the function:def _load_img(handle, target_dtype=np.float32, size=None, **kwargs): 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] ...
[ "Load image file as numpy array." ]
Please provide a description of the function:def _load_text(handle, split=False, encoding="utf-8"): string = handle.read().decode(encoding) return string.splitlines() if split else string
[ "Load and decode a string." ]
Please provide a description of the function:def _load_graphdef_protobuf(handle, **kwargs): # as_graph_def graph_def = tf.GraphDef.FromString(handle.read()) # check if this is a lucid-saved model # metadata = modelzoo.util.extract_metadata(graph_def) # if metadata is not None: # url = ha...
[ "Load GraphDef from a binary proto file." ]
Please provide a description of the function:def load(url_or_handle, cache=None, **kwargs): 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) ...
[ "Load a file.\n\n File format is inferred from url. File retrieval strategy is inferred from\n URL. Returned object type is inferred from url extension.\n\n Args:\n url_or_handle: a (reachable) URL, or an already open file handle\n\n Raises:\n RuntimeError: If file extension or URL is not supp...
Please provide a description of the function: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.\n Meant to be used as a last transform for architectures insisting on a specific\n spatial shape of their inputs.\n " ]
Please provide a description of the function:def _normalize_array(array, domain=(0, 1)): # 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 ...
[ "Given an arbitrary rank-3 NumPy array, produce one representing an image.\n\n This ensures the resulting array has a dtype of uint8 and a domain of 0-255.\n\n Args:\n array: NumPy array representing the image\n domain: expected range of values in array,\n defaults to (0, 1), if explicitly set to None ...
Please provide a description of the function:def _serialize_normalized_array(array, fmt='png', quality=70): 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.fro...
[ "Given a normalized array, returns byte representation of image encoding.\n\n Args:\n array: NumPy array of dtype uint8 and range 0 to 255\n fmt: string describing desired file format, defaults to 'png'\n quality: specifies compression quality from 0 to 100 for lossy formats\n\n Returns:\n image data ...
Please provide a description of the function:def serialize_array(array, domain=(0, 1), fmt='png', quality=70): normalized = _normalize_array(array, domain=domain) return _serialize_normalized_array(normalized, fmt=fmt, quality=quality)
[ "Given an arbitrary rank-3 NumPy array,\n returns the byte representation of the encoded image.\n\n Args:\n array: NumPy array of dtype uint8 and range 0 to 255\n domain: expected range of values in array, see `_normalize_array()`\n fmt: string describing desired file format, defaults to 'png'\n quali...
Please provide a description of the function:def array_to_jsbuffer(array): if array.ndim != 1: raise TypeError('Only 1d arrays can be converted JS TypedArray.') if array.dtype.name not in JS_ARRAY_TYPES: raise TypeError('Array dtype not supported by JS TypedArray.') js_type_name = array.dtype.name.capi...
[ "Serialize 1d NumPy array to JS TypedArray.\n\n Data is serialized to base64-encoded string, which is much faster\n and memory-efficient than json list serialization.\n\n Args:\n array: 1d NumPy array, dtype must be one of JS_ARRAY_TYPES.\n\n Returns:\n JS code that evaluates to a TypedArray as string.\n\...
Please provide a description of the function:def _apply_flat(cls, f, acts): 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.resh...
[ "Utility for applying f to inner dimension of acts.\n\n Flattens acts into a 2D tensor, applies f, then unflattens so that all\n dimesnions except innermost are unchanged.\n " ]
Please provide a description of the function:def set_style(self, input_feeds): sess = tf.get_default_session() computed = sess.run(self.input_grams, input_feeds) for v, g in zip(self.target_vars, computed): v.load(g)
[ "Set target style variables.\n \n Expected usage: \n style_loss = StyleLoss(style_layers)\n ...\n init_op = tf.global_variables_initializer()\n init_op.run()\n \n feeds = {... session.run() 'feeds' argument that will make 'style_layers'\n tensors evaluate to activat...
Please provide a description of the function:def _image_url(array, fmt='png', mode="data", quality=90, domain=None): 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 = serial...
[ "Create a data URL representing an image from a PIL.Image.\n\n Args:\n image: a numpy\n mode: presently only supports \"data\" for data URL\n\n Returns:\n URL representing image\n " ]
Please provide a description of the function:def image(array, domain=None, width=None, format='png', **kwargs): image_data = serialize_array(array, fmt=format, domain=domain) image = IPython.display.Image(data=image_data, format=format, width=width) IPython.display.display(image)
[ "Display an image.\n\n Args:\n array: NumPy array representing the image\n fmt: Image format e.g. png, jpeg\n domain: Domain of pixel values, inferred from min & max values if None\n w: width of output image, scaled using nearest neighbor interpolation.\n size unchanged if None\n " ]
Please provide a description of the function:def images(arrays, labels=None, domain=None, w=None): s = '<div style="display: flex; flex-direction: row;">' for i, array in enumerate(arrays): url = _image_url(array) label = labels[i] if labels is not None else i s += .format(label=label, url=url) s ...
[ "Display a list of images with optional labels.\n\n Args:\n arrays: A list of NumPy arrays representing images\n labels: A list of strings to label each image.\n Defaults to show index if None\n domain: Domain of pixel values, inferred from min & max values if None\n w: width of output image, scal...
Please provide a description of the function:def show(thing, domain=(0, 1), **kwargs): 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): ...
[ "Display a nupmy array without having to specify what it represents.\n\n This module will attempt to infer how to display your tensor based on its\n rank, shape and dtype. rank 4 tensors will be displayed as image grids, rank\n 2 and 3 tensors as images.\n " ]
Please provide a description of the function:def _strip_consts(graph_def, max_const_size=32): 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.te...
[ "Strip large constant values from graph_def.\n\n This is mostly a utility function for graph(), and also originates here:\n https://github.com/tensorflow/tensorflow/blob/master/tensorflow/examples/tutorials/deepdream/deepdream.ipynb\n " ]
Please provide a description of the function:def graph(graph_def, max_const_size=32): if hasattr(graph_def, 'as_graph_def'): graph_def = graph_def.as_graph_def() strip_def = _strip_consts(graph_def, max_const_size=max_const_size) code = .format(data=repr(str(strip_def)), id='graph'+str(np.rando...
[ "Visualize a TensorFlow graph.\n\n This function was originally found in this notebook (also Apache licensed):\n https://github.com/tensorflow/tensorflow/blob/master/tensorflow/examples/tutorials/deepdream/deepdream.ipynb\n ", "\n <script>\n function load() {{\n document.getEle...
Please provide a description of the function:def resize(image, target_size, **kwargs): if isinstance(target_size, int): target_size = (target_size, target_size) if not isinstance(target_size, (list, tuple, np.ndarray)): message = ( "`target_size` should be a single number (wid...
[ "Resize an ndarray image of rank 3 or 4.\n target_size can be a tuple `(width, height)` or scalar `width`." ]
Please provide a description of the function:def composite( background_image, foreground_image, foreground_width_ratio=0.25, foreground_position=(0.0, 0.0), ): if foreground_width_ratio <= 0: return background_image composite = background_image.copy() width = int(foreground_wi...
[ "Takes two images and composites them." ]
Please provide a description of the function:def lowres_tensor(shape, underlying_shape, offset=None, sd=None): sd = sd or 0.01 init_val = sd * np.random.randn(*underlying_shape).astype("float32") underlying_t = tf.Variable(init_val) t = resize_bilinear_nd(underlying_t, shape) if offset is not N...
[ "Produces a tensor paramaterized by a interpolated lower resolution tensor.\n\n This is like what is done in a laplacian pyramid, but a bit more general. It\n can be a powerful way to describe images.\n\n Args:\n shape: desired shape of resulting tensor\n underlying_shape: shape of the tensor being resized...
Please provide a description of the function:def create_session(target='', timeout_sec=10): '''Create an intractive TensorFlow session. Helper function that creates TF session that uses growing GPU memory allocation and opration timeout. 'allow_growth' flag prevents TF from allocating the whole GPU memory an o...
[]
Please provide a description of the function:def read(url, encoding=None, cache=None, mode="rb"): with read_handle(url, cache, mode=mode) as handle: data = handle.read() if encoding: data = data.decode(encoding) return data
[ "Read from any URL.\n\n Internally differentiates between URLs supported by tf.gfile, such as URLs\n with the Google Cloud Storage scheme ('gs://...') or local paths, and HTTP\n URLs. This way users don't need to know about the underlying fetch mechanism.\n\n Args:\n url: a URL including scheme o...
Please provide a description of the function:def read_handle(url, cache=None, mode="rb"): scheme = urlparse(url).scheme if cache == 'purge': _purge_cached(url) cache = None if _is_remote(scheme) and cache is None: cache = True log.debug("Cache not specified, enabling b...
[ "Read from any URL with a file handle.\n\n Use this to get a handle to a file rather than eagerly load the data:\n\n ```\n with read_handle(url) as handle:\n result = something.load(handle)\n\n result.do_something()\n\n ```\n\n When program execution leaves this `with` block, the handle will be...
Please provide a description of the function:def local_cache_path(remote_url): local_name = RESERVED_PATH_CHARS.sub("_", remote_url) return os.path.join(gettempdir(), local_name)
[ "Returns the path that remote_url would be cached at locally." ]
Please provide a description of the function:def cppn( width, batch=1, num_output_channels=3, num_hidden_channels=24, num_layers=8, activation_func=_composite_activation, normalize=False, ): r = 3.0 ** 0.5 # std(coord_range) == 1.0 coord_range = tf.linspace(-r, r, width) y,...
[ "Compositional Pattern Producing Network\n\n Args:\n width: width of resulting image, equals height\n batch: batch dimension of output, note that all params share the same weights!\n num_output_channels:\n num_hidden_channels:\n num_layers:\n activation_func:\n normalize:\n\n ...
Please provide a description of the function:def get_model(name): if name not in models_map: candidates = filter(lambda key: name in key, models_map.keys()) candidates_string = ", ".join(candidates) raise ValueError( "No network named {}. Did you mean one of {}?".format( ...
[ "Returns a model instance such as `model = vision_models.InceptionV1()`.\n In the future may be expanded to filter by additional criteria, such as\n architecture, dataset, and task the model was trained on.\n Args:\n name: The name of the model, as given by the class name in vision_models.\n Return...
Please provide a description of the function:def activation_atlas( model, layer, grid_size=10, icon_size=96, number_activations=NUMBER_OF_AVAILABLE_SAMPLES, icon_batch_size=32, verbose=False, ): activations = layer.activations[:number_activations, ...] layout, = aligned_umap(ac...
[ "Renders an Activation Atlas of the given model's layer." ]
Please provide a description of the function:def aligned_activation_atlas( model1, layer1, model2, layer2, grid_size=10, icon_size=80, num_steps=1024, whiten_layers=True, number_activations=NUMBER_OF_AVAILABLE_SAMPLES, icon_batch_size=32, verbose=False, ): combined_a...
[ "Renders two aligned Activation Atlases of the given models' layers.\n\n Returns a generator of the two atlasses, and a nested generator for intermediate\n atlasses while they're being rendered.\n " ]
Please provide a description of the function:def _combine_activations( layer1, layer2, activations1=None, activations2=None, mode=ActivationTranslation.BIDIRECTIONAL, number_activations=NUMBER_OF_AVAILABLE_SAMPLES, ): activations1 = activations1 or layer1.activations[:number_activations...
[ "Given two layers, combines their activations according to mode.\n\n ActivationTranslation.ONE_TO_TWO:\n Translate activations of layer1 into the space of layer2, and return a tuple of\n the translated activations and the original layer2 activations.\n\n ActivationTranslation.BIDIRECTIONAL:\n T...
Please provide a description of the function:def bin_laid_out_activations(layout, activations, grid_size, threshold=5): assert layout.shape[0] == activations.shape[0] # calculate which grid cells each activation's layout position falls into # first bin stays empty because nothing should be < 0, so we...
[ "Given a layout and activations, overlays a grid on the layout and returns\n averaged activations for each grid cell. If a cell contains less than `threshold`\n activations it will be discarded, so the number of returned data is variable." ]