Save machine learning models to pickle files.
326069
def save_models(self, model_path):
        
        for group, condition_model_set in self.condition_models.items():
            for model_name, model_obj in condition_model_set.items():
                out_filename = model_path + \
                               "{0}_{1}_condition.pkl".format(group,
                                                              model_name.replace(" ", "-"))
                with open(out_filename, "wb") as pickle_file:
                    pickle.dump(model_obj,
                                pickle_file,
                                pickle.HIGHEST_PROTOCOL)
        for group, size_model_set in self.size_models.items():
            for model_name, model_obj in size_model_set.items():
                out_filename = model_path + \
                               "{0}_{1}_size.pkl".format(group,
                                                         model_name.replace(" ", "-"))
                with open(out_filename, "wb") as pickle_file:
                    pickle.dump(model_obj,
                                pickle_file,
                                pickle.HIGHEST_PROTOCOL)
        for group, dist_model_set in self.size_distribution_models.items():
            for model_type, model_objs in dist_model_set.items():
                for model_name, model_obj in model_objs.items():
                    out_filename = model_path + \
                                   "{0}_{1}_{2}_sizedist.pkl".format(group,
                                                                     model_name.replace(" ", "-"),
                                                                     model_type)
                    with open(out_filename, "wb") as pickle_file:
                        pickle.dump(model_obj,
                                    pickle_file,
                                    pickle.HIGHEST_PROTOCOL)
        for model_type, track_type_models in self.track_models.items():
            for group, track_model_set in track_type_models.items():
                for model_name, model_obj in track_model_set.items():
                    out_filename = model_path + \
                                   "{0}_{1}_{2}_track.pkl".format(group,
                                                                  model_name.replace(" ", "-"),
                                                                  model_type)
                    with open(out_filename, "wb") as pickle_file:
                        pickle.dump(model_obj,
                                    pickle_file,
                                    pickle.HIGHEST_PROTOCOL)

        return
72532
def score_file(filename):
  """"""
  # Prepare model.
  hparams = create_hparams()
  encoders = registry.problem(FLAGS.problem).feature_encoders(FLAGS.data_dir)
  has_inputs = "inputs" in encoders

  # Prepare features for feeding into the model.
  if has_inputs:
    inputs_ph = tf.placeholder(dtype=tf.int32)  # Just length dimension.
    batch_inputs = tf.reshape(inputs_ph, [1, -1, 1, 1])  # Make it 4D.
  targets_ph = tf.placeholder(dtype=tf.int32)  # Just length dimension.
  batch_targets = tf.reshape(targets_ph, [1, -1, 1, 1])  # Make it 4D.
  if has_inputs:
    features = {"inputs": batch_inputs, "targets": batch_targets}
  else:
    features = {"targets": batch_targets}

  # Prepare the model and the graph when model runs on features.
  model = registry.model(FLAGS.model)(hparams, tf.estimator.ModeKeys.EVAL)
  _, losses = model(features)
  saver = tf.train.Saver()

  with tf.Session() as sess:
    # Load weights from checkpoint.
    if FLAGS.checkpoint_path is None:
      ckpts = tf.train.get_checkpoint_state(FLAGS.output_dir)
      ckpt = ckpts.model_checkpoint_path
    else:
      ckpt = FLAGS.checkpoint_path
    saver.restore(sess, ckpt)
    # Run on each line.
    with tf.gfile.Open(filename) as f:
      lines = f.readlines()
    results = []
    for line in lines:
      tab_split = line.split("\t")
      if len(tab_split) > 2:
        raise ValueError("Each line must have at most one tab separator.")
      if len(tab_split) == 1:
        targets = tab_split[0].strip()
      else:
        targets = tab_split[1].strip()
        inputs = tab_split[0].strip()
      # Run encoders and append EOS symbol.
      targets_numpy = encoders["targets"].encode(
          targets) + [text_encoder.EOS_ID]
      if has_inputs:
        inputs_numpy = encoders["inputs"].encode(inputs) + [text_encoder.EOS_ID]
      # Prepare the feed.
      if has_inputs:
        feed = {inputs_ph: inputs_numpy, targets_ph: targets_numpy}
      else:
        feed = {targets_ph: targets_numpy}
      # Get the score.
      np_loss = sess.run(losses["training"], feed)
      results.append(np_loss)
  return results
499169
def to_pickle(self, filename):
        """"""
        with open(filename, 'wb') as f:
            pickle.dump(self, f)
771734
def get_zipped_dataset_from_predictions(predictions):
  """"""
  targets = stack_data_given_key(predictions, "targets")
  outputs = stack_data_given_key(predictions, "outputs")
  num_videos, num_steps = targets.shape[:2]

  # Truncate output time-steps to match target time-steps
  outputs = outputs[:, :num_steps]

  targets_placeholder = tf.placeholder(targets.dtype, targets.shape)
  outputs_placeholder = tf.placeholder(outputs.dtype, outputs.shape)
  dataset = tf.data.Dataset.from_tensor_slices(
      (targets_placeholder, outputs_placeholder))
  iterator = dataset.make_initializable_iterator()
  feed_dict = {targets_placeholder: targets,
               outputs_placeholder: outputs}
  return iterator, feed_dict, num_videos
353927
def save_cache(data, filename):
    """"""
    with open(filename, 'wb') as handle:
        pickle.dump(data, handle)
937056
def from_pickle(cls, filename):
        """"""
        with open(filename, 'rb') as f:
            mesh = pickle.load(f).copy()
        return mesh
731171
def _save_pickle(self, filename):
        """"""
        with open(filename, 'wb') as file_handle:
            pickle.dump(self._sensors, file_handle, pickle.HIGHEST_PROTOCOL)
            file_handle.flush()
            os.fsync(file_handle.fileno())
592977
def save(self, filename='classifier.dump'):
        
        ofile = open(filename,'w+')
        pickle.dump(self.classifier, ofile)
        ofile.close()
965325
def save_to_file(self,
                     file_path,
                     labels=None,
                     predict_proba=True,
                     show_predicted_value=True,
                     **kwargs):
        
        file_ = open(file_path, 'w', encoding='utf8')
        file_.write(self.as_html(labels=labels,
                                 predict_proba=predict_proba,
                                 show_predicted_value=show_predicted_value,
                                 **kwargs))
        file_.close()
487251
def predict_files(self, files):
        '''
        
        '''
        imgs = [0]*len(files)
        for i, file in enumerate(files):
            img = cv2.imread(file).astype('float64')
            img = cv2.resize(img, (224,224))
            img = preprocess_input(img)
            if img is None:
                print('failed to open: {}, continuing...'.format(file))
            imgs[i] = img
        return self.model.predict(np.array(imgs))
189940
def writeCache(self, filename):
        """"""
        with open(filename, 'wb') as f:
            pickle.dump(self.modules, f)
1114635
def rm_compressed(ctx, dataset, kwargs):
    ""

    kwargs = parse_kwargs(kwargs)
    data(dataset, **ctx.obj).rm_compressed(**kwargs)
93835
def save_results(self, path='.'):
        """"""
        with open(path, 'wb') as f:
            pickle.dump(self.results, f)
810470
def save_object(filename, obj):
    """"""
    logging.info('saving {}...'.format(filename))
    try:
        with gzip.GzipFile(filename, 'wb') as f:
            f.write(pickle.dumps(obj, 1))
    except Exception as e:
        logging.error('save failure: {}'.format(e))
        raise
842143
def save_model(model, filename):
    
    with open(filename, 'w') as f:
        f.write(serialize_model(model))
358760
def save(self, f):
        """"""
        return pickle.dump((self.perceptron.weights, self.tagdict, self.classes, self.clusters), f, protocol=pickle.HIGHEST_PROTOCOL)
545515
def save_files(self, selections) -> None:
        """"""
        try:
            currentpath = self.currentpath
            selections = selectiontools.Selections(selections)
            for selection in selections:
                if selection.name == 'complete':
                    continue
                path = os.path.join(currentpath, selection.name+'.py')
                selection.save_networkfile(filepath=path)
        except BaseException:
            objecttools.augment_excmessage(
                'While trying to save selections `%s` into network files'
                % selections)