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 isdir(self, dirname):
"""Returns whether the path is a directory or not.""" |
client = boto3.client("s3")
bucket, path = self.bucket_and_path(dirname)
if not path.endswith("/"):
path += "/" # This will now only retrieve subdir content
r = client.list_objects(Bucket=bucket, Prefix=path, Delimiter="/")
if r.get("Contents") or r.get("CommonPrefi... |
<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_context():
"""Determine the most specific context that we're in. Returns: _CONTEXT_COLAB: If in Colab with an IPython notebook context. _CONTEXT_IPYTHON... |
# In Colab, the `google.colab` module is available, but the shell
# returned by `IPython.get_ipython` does not have a `get_trait`
# method.
try:
import google.colab
import IPython
except ImportError:
pass
else:
if IPython.get_ipython() is not None:
# We'll assume that we're in a Colab... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def start(args_string):
"""Launch and display a TensorBoard instance as if at the command line. Args: args_string: Command-line arguments to TensorBoard, to be i... |
context = _get_context()
try:
import IPython
import IPython.display
except ImportError:
IPython = None
if context == _CONTEXT_NONE:
handle = None
print("Launching TensorBoard...")
else:
handle = IPython.display.display(
IPython.display.Pretty("Launching TensorBoard..."),
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _time_delta_from_info(info):
"""Format the elapsed time for the given TensorBoardInfo. Args: info: A TensorBoardInfo value. Returns: A human-readable string ... |
delta_seconds = int(time.time()) - info.start_time
return str(datetime.timedelta(seconds=delta_seconds)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def display(port=None, height=None):
"""Display a TensorBoard instance already running on this machine. Args: port: The port on which the TensorBoard server is l... |
_display(port=port, height=height, print_message=True, display_handle=None) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _display(port=None, height=None, print_message=False, display_handle=None):
"""Internal version of `display`. Args: port: As with `display`. height: As with ... |
if height is None:
height = 800
if port is None:
infos = manager.get_all()
if not infos:
raise ValueError("Can't display TensorBoard: no known instances running.")
else:
info = max(manager.get_all(), key=lambda x: x.start_time)
port = info.port
else:
infos = [i for i in man... |
<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():
"""Print a listing of known running TensorBoard instances. TensorBoard instances that were killed uncleanly (e.g., with SIGKILL or SIGQUIT) may appea... |
infos = manager.get_all()
if not infos:
print("No known TensorBoard instances running.")
return
print("Known TensorBoard instances:")
for info in infos:
template = " - port {port}: {data_source} (started {delta} ago; pid {pid})"
print(template.format(
port=info.port,
data_sour... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def IsTensorFlowEventsFile(path):
"""Check the path name to see if it is probably a TF Events file. Args: path: A file path to check if it is an event file. Rais... |
if not path:
raise ValueError('Path must be a nonempty string')
return 'tfevents' in tf.compat.as_str_any(os.path.basename(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 ListDirectoryAbsolute(directory):
"""Yields all files in the given directory. The paths are absolute.""" |
return (os.path.join(directory, path)
for path in tf.io.gfile.listdir(directory)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _EscapeGlobCharacters(path):
"""Escapes the glob characters in a path. Python 3 has a glob.escape method, but python 2 lacks it, so we manually implement thi... |
drive, path = os.path.splitdrive(path)
return '%s%s' % (drive, _ESCAPE_GLOB_CHARACTERS_REGEX.sub(r'[\1]', 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 ListRecursivelyViaGlobbing(top):
"""Recursively lists all files within the directory. This method does not list subdirectories (in addition to regular files)... |
current_glob_string = os.path.join(_EscapeGlobCharacters(top), '*')
level = 0
while True:
logger.info('GlobAndListFiles: Starting to glob level %d', level)
glob = tf.io.gfile.glob(current_glob_string)
logger.info(
'GlobAndListFiles: %d files glob-ed at level %d', len(glob), level)
if no... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def GetLogdirSubdirectories(path):
"""Obtains all subdirectories with events files. The order of the subdirectories returned is unspecified. The internal logic t... |
if not tf.io.gfile.exists(path):
# No directory to traverse.
return ()
if not tf.io.gfile.isdir(path):
raise ValueError('GetLogdirSubdirectories: path exists and is not a '
'directory, %s' % path)
if IsCloudPath(path):
# Glob-ing for files can be significantly faster than 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 audio(name, data, sample_rate, step=None, max_outputs=3, encoding=None, description=None):
"""Write an audio summary. Arguments: name: A name for this summar... |
audio_ops = getattr(tf, 'audio', None)
if audio_ops is None:
# Fallback for older versions of TF without tf.audio.
from tensorflow.python.ops import gen_audio_ops as audio_ops
if encoding is None:
encoding = 'wav'
if encoding != 'wav':
raise ValueError('Unknown encoding: %r' % encoding)
summ... |
<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_numerics_alert(event):
"""Determines whether a health pill event contains bad values. A bad value is one of NaN, -Inf, or +Inf. Args: event: (`Event`... |
value = event.summary.value[0]
debugger_plugin_metadata_content = None
if value.HasField("metadata"):
plugin_data = value.metadata.plugin_data
if plugin_data.plugin_name == constants.DEBUGGER_PLUGIN_NAME:
debugger_plugin_metadata_content = plugin_data.content
if not debugger_plugin_metadata_cont... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def first_timestamp(self, event_key=None):
"""Obtain the first timestamp. Args: event_key: the type key of the sought events (e.g., constants.NAN_KEY). If None, ... |
if event_key is None:
timestamps = [self._trackers[key].first_timestamp
for key in self._trackers]
return min(timestamp for timestamp in timestamps if timestamp >= 0)
else:
return self._trackers[event_key].first_timestamp |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def last_timestamp(self, event_key=None):
"""Obtain the last timestamp. Args: event_key: the type key of the sought events (e.g., constants.NAN_KEY). If None, in... |
if event_key is None:
timestamps = [self._trackers[key].first_timestamp
for key in self._trackers]
return max(timestamp for timestamp in timestamps if timestamp >= 0)
else:
return self._trackers[event_key].last_timestamp |
<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(self, numerics_alert):
"""Register an alerting numeric event. Args: numerics_alert: An instance of `NumericsAlert`. """ |
key = (numerics_alert.device_name, numerics_alert.tensor_name)
if key in self._data:
self._data[key].add(numerics_alert)
else:
if len(self._data) < self._capacity:
history = NumericsAlertHistory()
history.add(numerics_alert)
self._data[key] = history |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def run(logdir, run_name, wave_name, wave_constructor):
"""Generate wave data of the given form. The provided function `wave_constructor` should accept a scalar ... |
tf.compat.v1.reset_default_graph()
tf.compat.v1.set_random_seed(0)
# On each step `i`, we'll set this placeholder to `i`. This allows us
# to know "what time it is" at each step.
step_placeholder = tf.compat.v1.placeholder(tf.float32, shape=[])
# We want to linearly interpolate a frequency between A4 (44... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def sine_wave(frequency):
"""Emit a sine wave at the given frequency.""" |
xs = tf.reshape(tf.range(_samples(), dtype=tf.float32), [1, _samples(), 1])
ts = xs / FLAGS.sample_rate
return tf.sin(2 * math.pi * frequency * ts) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def triangle_wave(frequency):
"""Emit a triangle wave at the given frequency.""" |
xs = tf.reshape(tf.range(_samples(), dtype=tf.float32), [1, _samples(), 1])
ts = xs / FLAGS.sample_rate
#
# A triangle wave looks like this:
#
# /\ /\
# / \ / \
# \ / \ /
# \/ \/
#
# If we look at just half a period (the first four slashes in the
# ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def bisine_wave(frequency):
"""Emit two sine waves, in stereo at different octaves.""" |
#
# We can first our existing sine generator to generate two different
# waves.
f_hi = frequency
f_lo = frequency / 2.0
with tf.name_scope('hi'):
sine_hi = sine_wave(f_hi)
with tf.name_scope('lo'):
sine_lo = sine_wave(f_lo)
#
# Now, we have two tensors of shape [1, _samples(), 1]. By concaten... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def bisine_wahwah_wave(frequency):
"""Emit two sine waves with balance oscillating left and right.""" |
#
# This is clearly intended to build on the bisine wave defined above,
# so we can start by generating that.
waves_a = bisine_wave(frequency)
#
# Then, by reversing axis 2, we swap the stereo channels. By mixing
# this with `waves_a`, we'll be able to create the desired effect.
waves_b = tf.reverse(wa... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def run_all(logdir, verbose=False):
"""Generate waves of the shapes defined above. Arguments: logdir: the directory into which to store all the runs' data verbos... |
waves = [sine_wave, square_wave, triangle_wave,
bisine_wave, bisine_wahwah_wave]
for (i, wave_constructor) in enumerate(waves):
wave_name = wave_constructor.__name__
run_name = 'wave:%02d,%s' % (i + 1, wave_name)
if verbose:
print('--- Running: %s' % run_name)
run(logdir, run_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 info_impl(self):
"""Returns a dict of all runs and tags and their data availabilities.""" |
result = {}
def add_row_item(run, tag=None):
run_item = result.setdefault(run, {
'run': run,
'tags': {},
# A run-wide GraphDef of ops.
'run_graph': False})
tag_item = None
if tag:
tag_item = run_item.get('tags').setdefault(tag, {
'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 graph_route(self, request):
"""Given a single run, return the graph definition in protobuf format.""" |
run = request.args.get('run')
tag = request.args.get('tag', '')
conceptual_arg = request.args.get('conceptual', False)
is_conceptual = True if conceptual_arg == 'true' else False
if run is None:
return http_util.Respond(
request, 'query parameter "run" is required', 'text/plain', 4... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def model_fn(hparams, seed):
"""Create a Keras model with the given hyperparameters. Args: hparams: A dict mapping hyperparameters in `HPARAMS` to values. seed: ... |
rng = random.Random(seed)
model = tf.keras.models.Sequential()
model.add(tf.keras.layers.Input(INPUT_SHAPE))
model.add(tf.keras.layers.Reshape(INPUT_SHAPE + (1,))) # grayscale channel
# Add convolutional layers.
conv_filters = 8
for _ in xrange(hparams[HP_CONV_LAYERS]):
model.add(tf.keras.layers.C... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def prepare_data():
"""Load and normalize data.""" |
((x_train, y_train), (x_test, y_test)) = DATASET.load_data()
x_train = x_train.astype("float32")
x_test = x_test.astype("float32")
x_train /= 255.0
x_test /= 255.0
return ((x_train, y_train), (x_test, y_test)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def run_all(logdir, verbose=False):
"""Perform random search over the hyperparameter space. Arguments: logdir: The top-level directory into which to write data. ... |
data = prepare_data()
rng = random.Random(0)
base_writer = tf.summary.create_file_writer(logdir)
with base_writer.as_default():
experiment = hp.Experiment(hparams=HPARAMS, metrics=METRICS)
experiment_string = experiment.summary_pb().SerializeToString()
tf.summary.experimental.write_raw_pb(experime... |
<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_uniform(domain, rng):
"""Sample a value uniformly from a domain. Args: domain: An `IntInterval`, `RealInterval`, or `Discrete` domain. rng: A `random.... |
if isinstance(domain, hp.IntInterval):
return rng.randint(domain.min_value, domain.max_value)
elif isinstance(domain, hp.RealInterval):
return rng.uniform(domain.min_value, domain.max_value)
elif isinstance(domain, hp.Discrete):
return rng.choice(domain.values)
else:
raise TypeError("unknown do... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def pr_curves_route(self, request):
"""A route that returns a JSON mapping between runs and PR curve data. Returns: Given a tag and a comma-separated list of run... |
runs = request.args.getlist('run')
if not runs:
return http_util.Respond(
request, 'No runs provided when fetching PR curve data', 400)
tag = request.args.get('tag')
if not tag:
return http_util.Respond(
request, 'No tag provided when fetching PR curve data', 400)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _process_tensor_event(self, event, thresholds):
"""Converts a TensorEvent into a dict that encapsulates information on it. Args: event: The TensorEvent to co... |
return self._make_pr_entry(
event.step,
event.wall_time,
tensor_util.make_ndarray(event.tensor_proto),
thresholds) |
<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_pr_entry(self, step, wall_time, data_array, thresholds):
"""Creates an entry for PR curve data. Each entry corresponds to 1 step. Args: step: The step.... |
# Trim entries for which TP + FP = 0 (precision is undefined) at the tail of
# the data.
true_positives = [int(v) for v in data_array[metadata.TRUE_POSITIVES_INDEX]]
false_positives = [
int(v) for v in data_array[metadata.FALSE_POSITIVES_INDEX]]
tp_index = metadata.TRUE_POSITIVES_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 summary_pb(self):
"""Create a top-level experiment summary describing this experiment. The resulting summary should be written to a log directory that enclos... |
hparam_infos = []
for hparam in self._hparams:
info = api_pb2.HParamInfo(
name=hparam.name,
description=hparam.description,
display_name=hparam.display_name,
)
domain = hparam.domain
if domain is not None:
domain.update_hparam_info(info)
hpara... |
<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_column(self, column_name, column_values):
"""Adds a named column of metadata values. Args: column_name: Name of the column. column_values: 1D array/list/... |
# Sanity checks.
if isinstance(column_values, list) and isinstance(column_values[0], list):
raise ValueError('"column_values" must be a flat list, but we detected '
'that its first entry is a list')
if isinstance(column_values, np.ndarray) and column_values.ndim != 1:
ra... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def configs(self):
"""Returns a map of run paths to `ProjectorConfig` protos.""" |
run_path_pairs = list(self.run_paths.items())
self._append_plugin_asset_directories(run_path_pairs)
# If there are no summary event files, the projector should still work,
# treating the `logdir` as the model checkpoint directory.
if not run_path_pairs:
run_path_pairs.append(('.', self.logdir... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def Histograms(self, run, tag):
"""Retrieve the histogram events associated with a run and tag. Args: run: A string name of the run for which values are retrieve... |
accumulator = self.GetAccumulator(run)
return accumulator.Histograms(tag) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def CompressedHistograms(self, run, tag):
"""Retrieve the compressed histogram events associated with a run and tag. Args: run: A string name of the run for whic... |
accumulator = self.GetAccumulator(run)
return accumulator.CompressedHistograms(tag) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def Images(self, run, tag):
"""Retrieve the image events associated with a run and tag. Args: run: A string name of the run for which values are retrieved. tag: ... |
accumulator = self.GetAccumulator(run)
return accumulator.Images(tag) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def histogram(name, data, step=None, buckets=None, description=None):
"""Write a histogram summary. Arguments: name: A name for this summary. The summary tag use... |
summary_metadata = metadata.create_summary_metadata(
display_name=None, description=description)
# TODO(https://github.com/tensorflow/tensorboard/issues/2109): remove fallback
summary_scope = (
getattr(tf.summary.experimental, 'summary_scope', None) or
tf.summary.summary_scope)
with summary_s... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def histogram_pb(tag, data, buckets=None, description=None):
"""Create a histogram summary protobuf. Arguments: tag: String tag for the summary. data: A `np.arra... |
bucket_count = DEFAULT_BUCKET_COUNT if buckets is None else buckets
data = np.array(data).flatten().astype(float)
if data.size == 0:
buckets = np.array([]).reshape((0, 3))
else:
min_ = np.min(data)
max_ = np.max(data)
range_ = max_ - min_
if range_ == 0:
center = min_
buckets = ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def setup_environment():
"""Makes recommended modifications to the environment. This functions changes global state in the Python process. Calling this function ... |
absl.logging.set_verbosity(absl.logging.WARNING)
# The default is HTTP/1.0 for some strange reason. If we don't use
# HTTP/1.1 then a new TCP socket and Python thread is created for
# each HTTP request. The tradeoff is we must always specify the
# Content-Length header, or do chunked encoding for streaming.... |
<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_default_assets_zip_provider():
"""Opens stock TensorBoard web assets collection. Returns: Returns function that returns a newly opened file handle to zip... |
path = os.path.join(os.path.dirname(inspect.getfile(sys._getframe(1))),
'webfiles.zip')
if not os.path.exists(path):
logger.warning('webfiles.zip static assets not found: %s', path)
return None
return lambda: open(path, 'rb') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def with_port_scanning(cls):
"""Create a server factory that performs port scanning. This function returns a callable whose signature matches the specification o... |
def init(wsgi_app, flags):
# base_port: what's the first port to which we should try to bind?
# should_scan: if that fails, shall we try additional ports?
# max_attempts: how many ports shall we try?
should_scan = flags.port is None
base_port = core_plugin.DEFAULT_PORT if flags.port is None 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 configure(self, argv=('',), **kwargs):
"""Configures TensorBoard behavior via flags. This method will populate the "flags" property with an argparse.Namespac... |
parser = argparse_flags.ArgumentParser(
prog='tensorboard',
description=('TensorBoard is a suite of web applications for '
'inspecting and understanding your TensorFlow runs '
'and graphs. https://github.com/tensorflow/tensorboard '))
for loader in self... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def main(self, ignored_argv=('',)):
"""Blocking main function for TensorBoard. This method is called by `tensorboard.main.run_main`, which is the standard entryp... |
self._install_signal_handler(signal.SIGTERM, "SIGTERM")
if self.flags.inspect:
logger.info('Not bringing up TensorBoard, but inspecting event files.')
event_file = os.path.expanduser(self.flags.event_file)
efi.inspect(self.flags.logdir, event_file, self.flags.tag)
return 0
if self.f... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def launch(self):
"""Python API for launching TensorBoard. This method is the same as main() except it launches TensorBoard in a separate permanent thread. The c... |
# Make it easy to run TensorBoard inside other programs, e.g. Colab.
server = self._make_server()
thread = threading.Thread(target=server.serve_forever, name='TensorBoard')
thread.daemon = True
thread.start()
return server.get_url() |
<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_info(self, server):
"""Write a TensorBoardInfo file and arrange for its cleanup. Args: server: The result of `self._make_server()`. """ |
server_url = urllib.parse.urlparse(server.get_url())
info = manager.TensorBoardInfo(
version=version.VERSION,
start_time=int(time.time()),
port=server_url.port,
pid=os.getpid(),
path_prefix=self.flags.path_prefix,
logdir=self.flags.logdir,
db=self.flags.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 _install_signal_handler(self, signal_number, signal_name):
"""Set a signal handler to gracefully exit on the given signal. When this process receives the giv... |
old_signal_handler = None # set below
def handler(handled_signal_number, frame):
# In case we catch this signal again while running atexit
# handlers, take the hint and actually die.
signal.signal(signal_number, signal.SIG_DFL)
sys.stderr.write("TensorBoard caught %s; exiting...\n" % s... |
<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_server(self):
"""Constructs the TensorBoard WSGI app and instantiates the server.""" |
app = application.standard_tensorboard_wsgi(self.flags,
self.plugin_loaders,
self.assets_zip_provider)
return self.server_class(app, self.flags) |
<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_wildcard_address(self, port):
"""Returns a wildcard address for the port in question. This will attempt to follow the best practice of calling getaddrin... |
fallback_address = '::' if socket.has_ipv6 else '0.0.0.0'
if hasattr(socket, 'AI_PASSIVE'):
try:
addrinfos = socket.getaddrinfo(None, port, socket.AF_UNSPEC,
socket.SOCK_STREAM, socket.IPPROTO_TCP,
socket.AI_PASSIVE)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def server_bind(self):
"""Override to enable IPV4 mapping for IPV6 sockets when desired. The main use case for this is so that when no host is specified, TensorB... |
socket_is_v6 = (
hasattr(socket, 'AF_INET6') and self.socket.family == socket.AF_INET6)
has_v6only_option = (
hasattr(socket, 'IPPROTO_IPV6') and hasattr(socket, 'IPV6_V6ONLY'))
if self._auto_wildcard and socket_is_v6 and has_v6only_option:
try:
self.socket.setsockopt(socket.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 handle_error(self, request, client_address):
"""Override to get rid of noisy EPIPE errors.""" |
del request # unused
# Kludge to override a SocketServer.py method so we can get rid of noisy
# EPIPE errors. They're kind of a red herring as far as errors go. For
# example, `curl -N http://localhost:6006/ | head` will cause an EPIPE.
exc_info = sys.exc_info()
e = exc_info[1]
if isinstan... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _events(self):
"""Iterator over all catapult trace events, as python values.""" |
for did, device in sorted(six.iteritems(self._proto.devices)):
if device.name:
yield dict(
ph=_TYPE_METADATA,
pid=did,
name='process_name',
args=dict(name=device.name))
yield dict(
ph=_TYPE_METADATA,
pid=did,
name='pr... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _event(self, event):
"""Converts a TraceEvent proto into a catapult trace event python value.""" |
result = dict(
pid=event.device_id,
tid=event.resource_id,
name=event.name,
ts=event.timestamp_ps / 1000000.0)
if event.duration_ps:
result['ph'] = _TYPE_COMPLETE
result['dur'] = event.duration_ps / 1000000.0
else:
result['ph'] = _TYPE_INSTANT
result[... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def op(name, data, display_name=None, description=None, collections=None):
"""Create a legacy scalar summary op. Arguments: name: A unique name for the generated... |
# TODO(nickfelt): remove on-demand imports once dep situation is fixed.
import tensorflow.compat.v1 as tf
if display_name is None:
display_name = name
summary_metadata = metadata.create_summary_metadata(
display_name=display_name, description=description)
with tf.name_scope(name):
with tf.cont... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def pb(name, data, display_name=None, description=None):
"""Create a legacy scalar summary protobuf. Arguments: name: A unique name for the generated summary, in... |
# TODO(nickfelt): remove on-demand imports once dep situation is fixed.
import tensorflow.compat.v1 as tf
data = np.array(data)
if data.shape != ():
raise ValueError('Expected scalar shape for data, saw shape: %s.'
% data.shape)
if data.dtype.kind not in ('b', 'i', 'u', 'f'): # boo... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def run(inputs, program, outputs):
"""Creates temp symlink tree, runs program, and copies back outputs. Args: inputs: List of fake paths to real paths, which are... |
root = tempfile.mkdtemp()
try:
cwd = os.getcwd()
for fake, real in inputs:
parent = os.path.join(root, os.path.dirname(fake))
if not os.path.exists(parent):
os.makedirs(parent)
# Use symlink if possible and not on Windows, since on Windows 10
# symlinks exist but they requir... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def main(args):
"""Invokes run function using a JSON file config. Args: args: CLI args, which can be a JSON file containing an object whose attributes are the pa... |
if not args:
raise Exception('Please specify at least one JSON config path')
inputs = []
program = []
outputs = []
for arg in args:
with open(arg) as fd:
config = json.load(fd)
inputs.extend(config.get('inputs', []))
program.extend(config.get('program', []))
outputs.extend(config.ge... |
<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_schema(connection):
"""Initializes the TensorBoard sqlite schema using the given connection. Args: connection: A sqlite DB connection. """ |
cursor = connection.cursor()
cursor.execute("PRAGMA application_id={}".format(_TENSORBOARD_APPLICATION_ID))
cursor.execute("PRAGMA user_version={}".format(_TENSORBOARD_USER_VERSION))
with connection:
for statement in _SCHEMA_STATEMENTS:
lines = statement.strip('\n').split('\n')
message = lines[... |
<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_id(self):
"""Returns a freshly created DB-wide unique ID.""" |
cursor = self._db.cursor()
cursor.execute('INSERT INTO Ids DEFAULT VALUES')
return cursor.lastrowid |
<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_data(verbose=False):
"""Get the raw encoded image data, downloading it if necessary.""" |
# This is a principled use of the `global` statement; don't lint me.
global _IMAGE_DATA # pylint: disable=global-statement
if _IMAGE_DATA is None:
if verbose:
logger.info("--- Downloading image.")
with contextlib.closing(urllib.request.urlopen(IMAGE_URL)) as infile:
_IMAGE_DATA = infile.read... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def convolve(image, pixel_filter, channels=3, name=None):
"""Perform a 2D pixel convolution on the given image. Arguments: image: A 3D `float32` `Tensor` of shap... |
with tf.name_scope(name, 'convolve'):
tf.compat.v1.assert_type(image, tf.float32)
channel_filter = tf.eye(channels)
filter_ = (tf.expand_dims(tf.expand_dims(pixel_filter, -1), -1) *
tf.expand_dims(tf.expand_dims(channel_filter, 0), 0))
result_batch = tf.nn.conv2d(tf.stack([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 get_image(verbose=False):
"""Get the image as a TensorFlow variable. Returns: A `tf.Variable`, which must be initialized prior to use: invoke `sess.run(resul... |
base_data = tf.constant(image_data(verbose=verbose))
base_image = tf.image.decode_image(base_data, channels=3)
base_image.set_shape((IMAGE_HEIGHT, IMAGE_WIDTH, 3))
parsed_image = tf.Variable(base_image, name='image', dtype=tf.uint8)
return parsed_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 proto_value_for_feature(example, feature_name):
"""Get the value of a feature from Example regardless of feature type.""" |
feature = get_example_features(example)[feature_name]
if feature is None:
raise ValueError('Feature {} is not on example proto.'.format(feature_name))
feature_type = feature.WhichOneof('kind')
if feature_type is None:
raise ValueError('Feature {} on example proto has no declared type.'.format(
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def parse_original_feature_from_example(example, feature_name):
"""Returns an `OriginalFeatureList` for the specified feature_name. Args: example: An example. fe... |
feature = get_example_features(example)[feature_name]
feature_type = feature.WhichOneof('kind')
original_value = proto_value_for_feature(example, feature_name)
return OriginalFeatureList(feature_name, original_value, feature_type) |
<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_inference_results(inference_result_proto):
"""Returns packaged inference results from the provided proto. Args: inference_result_proto: The classificati... |
inference_proto = inference_pb2.InferenceResult()
if isinstance(inference_result_proto,
classification_pb2.ClassificationResponse):
inference_proto.classification_result.CopyFrom(
inference_result_proto.result)
elif isinstance(inference_result_proto, regression_pb2.RegressionResponse)... |
<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_numeric_feature_names(example):
"""Returns a list of feature names for float and int64 type features. Args: example: An example. Returns: A list of strin... |
numeric_features = ('float_list', 'int64_list')
features = get_example_features(example)
return sorted([
feature_name for feature_name in features
if features[feature_name].WhichOneof('kind') in numeric_features
]) |
<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_categorical_feature_names(example):
"""Returns a list of feature names for byte type features. Args: example: An example. Returns: A list of categorical ... |
features = get_example_features(example)
return sorted([
feature_name for feature_name in features
if features[feature_name].WhichOneof('kind') == 'bytes_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 get_numeric_features_to_observed_range(examples):
"""Returns numerical features and their observed ranges. Args: examples: Examples to read to get ranges. Re... |
observed_features = collections.defaultdict(list) # name -> [value, ]
for example in examples:
for feature_name in get_numeric_feature_names(example):
original_feature = parse_original_feature_from_example(
example, feature_name)
observed_features[feature_name].extend(original_feature.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 get_categorical_features_to_sampling(examples, top_k):
"""Returns categorical features and a sampling of their most-common values. The results of this slow f... |
observed_features = collections.defaultdict(list) # name -> [value, ]
for example in examples:
for feature_name in get_categorical_feature_names(example):
original_feature = parse_original_feature_from_example(
example, feature_name)
observed_features[feature_name].extend(original_featur... |
<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_mutant_features(original_feature, index_to_mutate, viz_params):
"""Return a list of `MutantFeatureValue`s that are variants of original.""" |
lower = viz_params.x_min
upper = viz_params.x_max
examples = viz_params.examples
num_mutants = viz_params.num_mutants
if original_feature.feature_type == 'float_list':
return [
MutantFeatureValue(original_feature, index_to_mutate, value)
for value in np.linspace(lower, upper, num_mutants... |
<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_mutant_tuples(example_protos, original_feature, index_to_mutate, viz_params):
"""Return a list of `MutantFeatureValue`s and a list of mutant Examples. A... |
mutant_features = make_mutant_features(original_feature, index_to_mutate,
viz_params)
mutant_examples = []
for example_proto in example_protos:
for mutant_feature in mutant_features:
copied_example = copy.deepcopy(example_proto)
feature_name = mutant_featu... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def mutant_charts_for_feature(example_protos, feature_name, serving_bundles, viz_params):
"""Returns JSON formatted for rendering all charts for a feature. Args:... |
def chart_for_index(index_to_mutate):
mutant_features, mutant_examples = make_mutant_tuples(
example_protos, original_feature, index_to_mutate, viz_params)
charts = []
for serving_bundle in serving_bundles:
inference_result_proto = run_inference(mutant_examples, serving_bundle)
char... |
<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_json_formatted_for_single_chart(mutant_features, inference_result_proto, index_to_mutate):
"""Returns JSON formatted for a single mutant chart. Args: mu... |
x_label = 'step'
y_label = 'scalar'
if isinstance(inference_result_proto,
classification_pb2.ClassificationResponse):
# classification_label -> [{x_label: y_label:}]
series = {}
# ClassificationResponse has a separate probability for each label
for idx, classification in enumera... |
<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_example_features(example):
"""Returns the non-sequence features from the provided example.""" |
return (example.features.feature if isinstance(example, tf.train.Example)
else example.context.feature) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def run_inference_for_inference_results(examples, serving_bundle):
"""Calls servo and wraps the inference results.""" |
inference_result_proto = run_inference(examples, serving_bundle)
inferences = wrap_inference_results(inference_result_proto)
infer_json = json_format.MessageToJson(
inferences, including_default_value_fields=True)
return json.loads(infer_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 get_eligible_features(examples, num_mutants):
"""Returns a list of JSON objects for each feature in the examples. This list is used to drive partial dependen... |
features_dict = (
get_numeric_features_to_observed_range(
examples))
features_dict.update(
get_categorical_features_to_sampling(
examples, num_mutants))
# Massage the features_dict into a sorted list before returning because
# Polymer dom-repeat needs a list.
features_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 get_label_vocab(vocab_path):
"""Returns a list of label strings loaded from the provided path.""" |
if vocab_path:
try:
with tf.io.gfile.GFile(vocab_path, 'r') as f:
return [line.rstrip('\n') for line in f]
except tf.errors.NotFoundError as err:
tf.logging.error('error reading vocab file: %s', err)
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 create_sprite_image(examples):
"""Returns an encoded sprite image for use in Facets Dive. Args: examples: A list of serialized example protos to get images f... |
def generate_image_from_thubnails(thumbnails, thumbnail_dims):
"""Generates a sprite atlas image from a set of thumbnails."""
num_thumbnails = tf.shape(thumbnails)[0].eval()
images_per_row = int(math.ceil(math.sqrt(num_thumbnails)))
thumb_height = thumbnail_dims[0]
thumb_width = thum... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def run_inference(examples, serving_bundle):
"""Run inference on examples given model information Args: examples: A list of examples that matches the model spec.... |
batch_size = 64
if serving_bundle.estimator and serving_bundle.feature_spec:
# If provided an estimator and feature spec then run inference locally.
preds = serving_bundle.estimator.predict(
lambda: tf.data.Dataset.from_tensor_slices(
tf.parse_example([ex.SerializeToString() for ex in example... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def Items(self, key):
"""Return items associated with given key. Args: key: The key for which we are finding associated items. Raises: KeyError: If the key is no... |
with self._mutex:
if key not in self._buckets:
raise KeyError('Key %s was not found in Reservoir' % key)
bucket = self._buckets[key]
return bucket.Items() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def AddItem(self, key, item, f=lambda x: x):
"""Add a new item to the Reservoir with the given tag. If the reservoir has not yet reached full size, the new item ... |
with self._mutex:
bucket = self._buckets[key]
bucket.AddItem(item, f) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def FilterItems(self, filterFn, key=None):
"""Filter items within a Reservoir, using a filtering function. Args: filterFn: A function that returns True for the i... |
with self._mutex:
if key:
if key in self._buckets:
return self._buckets[key].FilterItems(filterFn)
else:
return 0
else:
return sum(bucket.FilterItems(filterFn)
for bucket in self._buckets.values()) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def AddItem(self, item, f=lambda x: x):
"""Add an item to the ReservoirBucket, replacing an old item if necessary. The new item is guaranteed to be added to the ... |
with self._mutex:
if len(self.items) < self._max_size or self._max_size == 0:
self.items.append(f(item))
else:
r = self._random.randint(0, self._num_items_seen)
if r < self._max_size:
self.items.pop(r)
self.items.append(f(item))
elif self.always_keep_... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def FilterItems(self, filterFn):
"""Filter items in a ReservoirBucket, using a filtering function. Filtering items from the reservoir bucket must update the inte... |
with self._mutex:
size_before = len(self.items)
self.items = list(filter(filterFn, self.items))
size_diff = size_before - len(self.items)
# Estimate a correction the number of items seen
prop_remaining = len(self.items) / float(
size_before) if size_before > 0 else 0
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _GetDenseDimensions(list_of_lists):
"""Returns the inferred dense dimensions of a list of lists.""" |
if not isinstance(list_of_lists, (list, tuple)):
return []
elif not list_of_lists:
return [0]
else:
return [len(list_of_lists)] + _GetDenseDimensions(list_of_lists[0]) |
<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_convertible_with(self, other):
"""Returns true if `other` is convertible with this Dimension. Two known Dimensions are convertible if they have the same v... |
other = as_dimension(other)
return self._value is None or other.value is None or self._value == other.value |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def merge_with(self, other):
"""Returns a Dimension that combines the information in `self` and `other`. Dimensions are combined as follows: ```python tf.Dimensi... |
other = as_dimension(other)
self.assert_is_convertible_with(other)
if self._value is None:
return Dimension(other.value)
else:
return Dimension(self._value) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def ndims(self):
"""Returns the rank of this shape, or None if it is unspecified.""" |
if self._dims is None:
return None
else:
if self._ndims is None:
self._ndims = len(self._dims)
return self._ndims |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def num_elements(self):
"""Returns the total number of elements, or none for incomplete shapes.""" |
if self.is_fully_defined():
size = 1
for dim in self._dims:
size *= dim.value
return size
else:
return None |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def merge_with(self, other):
"""Returns a `TensorShape` combining the information in `self` and `other`. The dimensions in `self` and `other` are merged elementw... |
other = as_shape(other)
if self._dims is None:
return other
else:
try:
self.assert_same_rank(other)
new_dims = []
for i, dim in enumerate(self._dims):
new_dims.append(dim.merge_with(other[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 concatenate(self, other):
"""Returns the concatenation of the dimension in `self` and `other`. *N.B.* If either `self` or `other` is completely unknown, conc... |
# TODO(mrry): Handle the case where we concatenate a known shape with a
# completely unknown shape, so that we can use the partial information.
other = as_shape(other)
if self._dims is None or other.dims is None:
return unknown_shape()
else:
return Tensor... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def assert_same_rank(self, other):
"""Raises an exception if `self` and `other` do not have convertible ranks. Args: other: Another `TensorShape`. Raises: ValueE... |
other = as_shape(other)
if self.ndims is not None and other.ndims is not None:
if self.ndims != other.ndims:
raise ValueError(
"Shapes %s and %s must have the same rank" % (self, other)
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def with_rank(self, rank):
"""Returns a shape based on `self` with the given rank. This method promotes a completely unknown shape to one with a known rank. Args... |
try:
return self.merge_with(unknown_shape(ndims=rank))
except ValueError:
raise ValueError("Shape %s must have rank %d" % (self, rank)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def with_rank_at_least(self, rank):
"""Returns a shape based on `self` with at least the given rank. Args: rank: An integer. Returns: A shape that is at least as... |
if self.ndims is not None and self.ndims < rank:
raise ValueError("Shape %s must have rank at least %d" % (self, rank))
else:
return self |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def with_rank_at_most(self, rank):
"""Returns a shape based on `self` with at most the given rank. Args: rank: An integer. Returns: A shape that is at least as s... |
if self.ndims is not None and self.ndims > rank:
raise ValueError("Shape %s must have rank at most %d" % (self, rank))
else:
return self |
<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_convertible_with(self, other):
"""Returns True iff `self` is convertible with `other`. Two possibly-partially-defined shapes are convertible if there exis... |
other = as_shape(other)
if self._dims is not None and other.dims is not None:
if self.ndims != other.ndims:
return False
for x_dim, y_dim in zip(self._dims, other.dims):
if not x_dim.is_convertible_with(y_dim):
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 most_specific_convertible_shape(self, other):
"""Returns the most specific TensorShape convertible with `self` and `other`. * TensorShape([None, 1]) is the m... |
other = as_shape(other)
if self._dims is None or other.dims is None or self.ndims != other.ndims:
return unknown_shape()
dims = [(Dimension(None))] * self.ndims
for i, (d1, d2) in enumerate(zip(self._dims, other.dims)):
if d1 is not None and d2 is not None and ... |
<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_fully_defined(self):
"""Returns True iff `self` is fully defined in every dimension.""" |
return self._dims is not None and all(
dim.value is not None for dim in self._dims
) |
<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_list(self):
"""Returns a list of integers or `None` for each dimension. Returns: A list of integers or `None` for each dimension. Raises: ValueError: If `... |
if self._dims is None:
raise ValueError("as_list() is not defined on an unknown TensorShape.")
return [dim.value for dim in self._dims] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.