Run the pruned and frozen inference graph.
7528
def apply_compact(graph_path):
    
    with tf.Session(config=tf.ConfigProto(allow_soft_placement=True)) as sess:
        # Note, we just load the graph and do *not* need to initialize anything.
        with tf.gfile.GFile(graph_path, "rb") as f:
            graph_def = tf.GraphDef()
            graph_def.ParseFromString(f.read())
            tf.import_graph_def(graph_def)

        input_img = sess.graph.get_tensor_by_name('import/input_img:0')
        prediction_img = sess.graph.get_tensor_by_name('import/prediction_img:0')

        prediction = sess.run(prediction_img, {input_img: cv2.imread('lena.png')[None, ...]})
        cv2.imwrite('applied_compact.png', prediction[0])
611598
def run(self, graph):
        
        if not self:
            log.debug('no seeding, returning graph: %s', graph)
            return graph

        subgraphs = []

        for seed in self:
            seed_method, seed_data = seed[SEED_METHOD], seed[SEED_DATA]

            log.debug('seeding with %s: %s', seed_method, seed_data)
            subgraph = get_subgraph(graph, seed_method=seed_method, seed_data=seed_data)

            if subgraph is None:
                log.debug('seed returned empty graph: %s', seed)
                continue

            subgraphs.append(subgraph)

        if not subgraphs:
            log.debug('no subgraphs returned')
            return

        return union(subgraphs)
1364832
def run_steps(node: Node, pipeline: RenderingPipeline, **args):
    """"""
    for step in pipeline.steps:
        result = step(node, pipeline=pipeline, **args)
        if isinstance(result, dict):
            args = {**args, **result}
34434
def run(X_train, X_test, y_train, y_test, PARAMS):
    ''''''
    model.fit(X_train, y_train)
    predict_y = model.predict(X_test)
    score = r2_score(y_test, predict_y)
    LOG.debug('r2 score: %s' % score)
    nni.report_final_result(score)
1351685
def _run_helper(self, graph, protocol: Iterable[Dict]):
        
        result = graph

        for entry in protocol:
            meta_entry = entry.get('meta')

            if meta_entry is None:
                name, args, kwargs = _get_protocol_tuple(entry)
                func = self._get_function(name)
                result = func(result, *args, **kwargs)
            else:
                networks = (
                    self._run_helper(graph, subprotocol)
                    for subprotocol in entry['pipelines']
                )

                if meta_entry == META_UNION:
                    result = union(networks)

                elif meta_entry == META_INTERSECTION:
                    result = node_intersection(networks)

                else:
                    raise MetaValueError('invalid meta-command: {}'.format(meta_entry))

        return result
1287918
def use_educated_guess(self):
        """"""

        preprocess_fallback_config()

        global LIBIGRAPH_FALLBACK_LIBRARIES
        global LIBIGRAPH_FALLBACK_INCLUDE_DIRS
        global LIBIGRAPH_FALLBACK_LIBRARY_DIRS

        print("WARNING: we were not able to detect where igraph is installed on")
        print("your machine (if it is installed at all). We will use the fallback")
        print("library and include paths hardcoded in setup.py and hope that the")
        print("C core of igraph is installed there.")
        print("")
        print("If the compilation fails and you are sure that igraph is installed")
        print("on your machine, adjust the following two variables in setup.py")
        print("accordingly and try again:")
        print("")
        print("- LIBIGRAPH_FALLBACK_INCLUDE_DIRS",
            LIBIGRAPH_FALLBACK_INCLUDE_DIRS)
        print("- LIBIGRAPH_FALLBACK_LIBRARY_DIRS",
            LIBIGRAPH_FALLBACK_LIBRARY_DIRS)
        print("")

        seconds_remaining = 10 if self.wait else 0
        while seconds_remaining > 0:
            if seconds_remaining > 1:
                plural = "s"
            else:
                plural = ""

            sys.stdout.write("\rContinuing in %2d second%s; press Enter to continue "
                    "immediately. " % (seconds_remaining, plural))
            sys.stdout.flush()

            if os.name == 'nt':
              if msvcrt.kbhit():
                  if msvcrt.getch() == b'\r': # not '\n'
                      break
              time.sleep(1)
            else:
              rlist, _, _ = select([sys.stdin], [], [], 1)
              if rlist:
                  sys.stdin.readline()
                  break

            seconds_remaining -= 1
        sys.stdout.write("\r" + " "*65 + "\r")

        self.libraries = LIBIGRAPH_FALLBACK_LIBRARIES[:]
        if self.static_extension:
            self.libraries.extend(["xml2", "z", "m", "stdc++"])
        self.include_dirs = LIBIGRAPH_FALLBACK_INCLUDE_DIRS[:]
        self.library_dirs = LIBIGRAPH_FALLBACK_LIBRARY_DIRS[:]
746491
def dump(args):
    """"""
    if len(args) != 1:
        log.error('One target required.')
        app.quit(1)

    try:
        bb = Butcher()
        bb.load_graph(args[0])
    except error.BrokenGraph as lolno:
        log.fatal(lolno)
        app.quit(1)
    print "Nodes:"
    pprint.pprint(bb.graph.node)
    print "Edges:"
    pprint.pprint(bb.graph.edge)
818036
def run_inference_on_image(image):
  
  if not tf.gfile.Exists(image):
    tf.logging.fatal('File does not exist %s', image)
  image_data = tf.gfile.FastGFile(image, 'rb').read()

  # Creates graph from saved GraphDef.
  create_graph()

  with tf.Session() as sess:
    # Some useful tensors:
    # 'softmax:0': A tensor containing the normalized prediction across
    #   1000 labels.
    # 'pool_3:0': A tensor containing the next-to-last layer containing 2048
    #   float description of the image.
    # 'DecodeJpeg/contents:0': A tensor containing a string providing JPEG
    #   encoding of the image.
    # Runs the softmax tensor by feeding the image_data as input to the graph.
    softmax_tensor = sess.graph.get_tensor_by_name('softmax:0')
    predictions = sess.run(softmax_tensor,
                           {'DecodeJpeg/contents:0': image_data})
    predictions = np.squeeze(predictions)

    # Creates node ID --> English string lookup.
    node_lookup = NodeLookup()

    top_k = predictions.argsort()[-FLAGS.num_top_predictions:][::-1]
    for node_id in top_k:
      human_string = node_lookup.id_to_string(node_id)
      score = predictions[node_id]
      print('%s (score = %.5f)' % (human_string, score))
1181167
def run(self, run_fit_model=True):
        

        if run_fit_model:
            self.fit_model(self.img, self.voxelsize, self.seeds)

        self._start_time = time.time()
        if self.segparams["method"].lower() in ("graphcut", "gc"):
            self.__single_scale_gc_run()
        elif self.segparams["method"].lower() in (
            "multiscale_graphcut",
            "multiscale_gc",
            "msgc",
            "msgc_lo2hi",
            "lo2hi",
            "multiscale_graphcut_lo2hi",
        ):
            logger.debug("performing multiscale Graph-Cut lo2hi")
            self.__multiscale_gc_lo2hi_run()
        elif self.segparams["method"].lower() in (
            "msgc_hi2lo",
            "hi2lo",
            "multiscale_graphcut_hi2lo",
        ):
            logger.debug("performing multiscale Graph-Cut hi2lo")
            self.__multiscale_gc_hi2lo_run()
        else:
            logger.error("Unknown segmentation method: " + self.segparams["method"])
822718
def Main():
  
  argument_parser = argparse.ArgumentParser(description=(
      'Plots memory usage from profiling data.'))

  argument_parser.add_argument(
      '--output', dest='output_file', type=str, help=(
          'path of the output file to write the graph to instead of using '
          'interactive mode. The output format deduced from the extension '
          'of the filename.'))

  argument_parser.add_argument(
      'profile_path', type=str, help=(
          'path to the directory containing the profiling data.'))

  options = argument_parser.parse_args()

  if not os.path.isdir(options.profile_path):
    print('No such directory: {0:s}'.format(options.profile_path))
    return False

  names = ['time', 'queued', 'processing', 'to_merge', 'abandoned', 'total']

  glob_expression = os.path.join(options.profile_path, 'task_queue-*.csv.gz')
  for csv_file_name in glob.glob(glob_expression):
    data = numpy.genfromtxt(
        csv_file_name, delimiter='\t', dtype=None, encoding='utf-8',
        names=names, skip_header=1)

    pyplot.plot(data['time'], data['queued'], label='queued')
    pyplot.plot(data['time'], data['processing'], label='processing')
    pyplot.plot(data['time'], data['to_merge'], label='to merge')
    pyplot.plot(data['time'], data['abandoned'], label='abandoned')

  pyplot.title('Number of tasks over time')

  pyplot.xlabel('Time')
  pyplot.xscale('linear')

  pyplot.ylabel('Number of tasks')
  pyplot.yscale('linear')

  pyplot.legend()

  if options.output_file:
    pyplot.savefig(options.output_file)
  else:
    pyplot.show()

  return True
73755
def _setup_converter_graph(self, converter_list, prune_converters):
        '''
        
        '''
        for converter in converter_list:
            if prune_converters:
                try:
                    converter.configure()
                except ConverterUnavailable as e:
                    log.warning('%s unavailable: %s' %
                                (converter.__class__.__name__, str(e)))
                    continue

            for in_ in converter.inputs:
                for out in converter.outputs:
                    self.dgraph.add_edge(in_, out, converter.cost)
                    self.converters[(in_, out)] = converter

            if hasattr(converter, 'direct_outputs'):
                self._setup_direct_converter(converter)
1048079
def make_batch(size, graph):
        
        i = iter(graph)
        chunk = list(islice(i, size))
        while chunk:
            yield chunk
            chunk = list(islice(i, size))
413394
private boolean pruneData(ThroughputDistribution priorStats, double forecast) {
        boolean prune = false;

        // if forecast tput is much greater or much smaller than priorStats, we suspect
        // priorStats is no longer relevant, so prune it
        double tputRatio = forecast / priorStats.getMovingAverage();
        if (tputRatio > tputRatioPruneLevel || tputRatio < (1 / tputRatioPruneLevel)) {
            prune = true;
        } else {
            // age & reliability (represented by standard deviation) check
            int age = controllerCycle - priorStats.getLastUpdate();
            double variability = (priorStats.getStddev() / priorStats.getMovingAverage());
            if (age * variability > dataAgePruneLevel)
                prune = true;
        }

        return prune;
    }
607388
def run(self, format=None, reduce=False, *args, **kwargs):
        
        plan = self._generate_plan()
        if reduce:
            # This will performa a transitive reduction on the underlying
            # graph, producing less edges. Mostly useful for the "dot" format,
            # when converting to PNG, so it creates a prettier/cleaner
            # dependency graph.
            plan.graph.transitive_reduction()

        fn = FORMATTERS[format]
        fn(sys.stdout, plan.graph)
        sys.stdout.flush()
1186655
def preprocess_tree(self, tree):
        """"""
        visitor = RinohTreePreprocessor(tree, self)
        tree.walkabout(visitor)
1118970
def _flush_graph_val(self):
        """"""
        if not self._graphvals2set:
            return
        delafter = {}
        for graph, key, branch, turn, tick, value in self._graphvals2set:
            if (graph, key, branch) in delafter:
                delafter[graph, key, branch] = min((
                    (turn, tick),
                    delafter[graph, key, branch]
                ))
            else:
                delafter[graph, key, branch] = (turn, tick)
        self.sqlmany(
            'del_graph_val_after',
            *((graph, key, branch, turn, turn, tick)
              for ((graph, key, branch), (turn, tick)) in delafter.items())
        )
        self.sqlmany('graph_val_insert', *self._graphvals2set)
        self._graphvals2set = []
493279
def maybe_with_graph(graph=None, create_if_none=True):
  """"""
  if tf.executing_eagerly():
    yield None
  else:
    if graph is None and create_if_none:
      graph = tf.Graph()

    if graph is None:
      yield None
    else:
      with graph.as_default():
        yield graph