本文整理汇总了Python中json.dump方法的典型用法代码示例。如果您正苦于以下问题:Python json.dump方法的具体用法?Python json.dump怎么用?Python json.dump使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类json
的用法示例。
在下文中一共展示了json.dump方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _write_coco_results_file
# 需要导入模块: import json [as 别名]
# 或者: from json import dump [as 别名]
def _write_coco_results_file(self, all_boxes, res_file):
# [{"image_id": 42,
# "category_id": 18,
# "bbox": [258.15,41.29,348.26,243.78],
# "score": 0.236}, ...]
results = []
for cls_ind, cls in enumerate(self.classes):
if cls == '__background__':
continue
print('Collecting {} results ({:d}/{:d})'.format(cls, cls_ind,
self.num_classes - 1))
coco_cat_id = self._class_to_coco_cat_id[cls]
results.extend(self._coco_results_one_category(all_boxes[cls_ind],
coco_cat_id))
print('Writing results json to {}'.format(res_file))
with open(res_file, 'w') as fid:
json.dump(results, fid)
开发者ID:Sunarker,项目名称:Collaborative-Learning-for-Weakly-Supervised-Object-Detection,代码行数:19,代码来源:coco.py
示例2: save_eval_file
# 需要导入模块: import json [as 别名]
# 或者: from json import dump [as 别名]
def save_eval_file(opt, stats, eval_type="losses", split="dev", ext="pickle"):
if cfg.test_save:
name = "{}/{}.{}".format(utils.make_name(
opt, prefix="garbage/{}/".format(eval_type),
is_dir=True, eval_=True), split, ext)
else:
name = "{}/{}.{}".format(utils.make_name(
opt, prefix="results/{}/".format(eval_type),
is_dir=True, eval_=True), split, ext)
print("Saving {} {} to {}".format(split, eval_type, name))
if ext == "pickle":
with open(name, "wb") as f:
pickle.dump(stats, f)
elif ext == "txt":
with open(name, "w") as f:
f.write(stats)
elif ext == "json":
with open(name, "w") as f:
json.dump(stats, f)
else:
raise
示例3: register
# 需要导入模块: import json [as 别名]
# 或者: from json import dump [as 别名]
def register(self, name, serializer):
"""Register ``serializer`` object under ``name``.
Raises :class:`AttributeError` if ``serializer`` in invalid.
.. note::
``name`` will be used as the file extension of the saved files.
:param name: Name to register ``serializer`` under
:type name: ``unicode`` or ``str``
:param serializer: object with ``load()`` and ``dump()``
methods
"""
# Basic validation
getattr(serializer, 'load')
getattr(serializer, 'dump')
self._serializers[name] = serializer
示例4: cache_data
# 需要导入模块: import json [as 别名]
# 或者: from json import dump [as 别名]
def cache_data(self, name, data):
"""Save ``data`` to cache under ``name``.
If ``data`` is ``None``, the corresponding cache file will be
deleted.
:param name: name of datastore
:param data: data to store. This may be any object supported by
the cache serializer
"""
serializer = manager.serializer(self.cache_serializer)
cache_path = self.cachefile('%s.%s' % (name, self.cache_serializer))
if data is None:
if os.path.exists(cache_path):
os.unlink(cache_path)
self.logger.debug('deleted cache file: %s', cache_path)
return
with atomic_writer(cache_path, 'wb') as file_obj:
serializer.dump(data, file_obj)
self.logger.debug('cached data: %s', cache_path)
示例5: gt_roidb
# 需要导入模块: import json [as 别名]
# 或者: from json import dump [as 别名]
def gt_roidb(self):
"""
Return the database of ground-truth regions of interest.
This function loads/saves from/to a cache file to speed up future calls.
"""
cache_file = osp.join(self.cache_path, self.name + '_gt_roidb.pkl')
if osp.exists(cache_file):
with open(cache_file, 'rb') as fid:
roidb = pickle.load(fid)
print('{} gt roidb loaded from {}'.format(self.name, cache_file))
return roidb
gt_roidb = [self._load_coco_annotation(index)
for index in self._image_index]
with open(cache_file, 'wb') as fid:
pickle.dump(gt_roidb, fid, pickle.HIGHEST_PROTOCOL)
print('wrote gt roidb to {}'.format(cache_file))
return gt_roidb
开发者ID:Sunarker,项目名称:Collaborative-Learning-for-Weakly-Supervised-Object-Detection,代码行数:21,代码来源:coco.py
示例6: savepb
# 需要导入模块: import json [as 别名]
# 或者: from json import dump [as 别名]
def savepb(self):
"""
Create a standalone const graph def that
C++ can load and run.
"""
darknet_pb = self.to_darknet()
flags_pb = self.FLAGS
flags_pb.verbalise = False
flags_pb.train = False
# rebuild another tfnet. all const.
tfnet_pb = TFNet(flags_pb, darknet_pb)
tfnet_pb.sess = tf.Session(graph = tfnet_pb.graph)
# tfnet_pb.predict() # uncomment for unit testing
name = 'built_graph/{}.pb'.format(self.meta['name'])
os.makedirs(os.path.dirname(name), exist_ok=True)
#Save dump of everything in meta
with open('built_graph/{}.meta'.format(self.meta['name']), 'w') as fp:
json.dump(self.meta, fp)
self.say('Saving const graph def to {}'.format(name))
graph_def = tfnet_pb.sess.graph_def
tf.train.write_graph(graph_def,'./', name, False)
示例7: make_model_yaml
# 需要导入模块: import json [as 别名]
# 或者: from json import dump [as 别名]
def make_model_yaml(template_yaml, model_json, output_yaml_path):
#
with open(template_yaml, 'r') as f:
model_yaml = yaml.load(f)
#
# get the model config:
json_file = open(model_json, 'r')
loaded_model_json = json_file.read()
json_file.close()
loaded_model = keras.models.model_from_json(loaded_model_json)
#
model_yaml["schema"]["targets"] = []
for oname, oshape in zip(loaded_model.output_names, loaded_model.output_shape):
append_el ={"name":oname , "shape":str(oshape)#replace("None,", "")
, "doc":"Methylation probability for %s"%oname}
model_yaml["schema"]["targets"].append(append_el)
#
with open(output_yaml_path, 'w') as f:
yaml.dump(model_yaml, f, default_flow_style=False)
示例8: make_secondary_dl_yaml
# 需要导入模块: import json [as 别名]
# 或者: from json import dump [as 别名]
def make_secondary_dl_yaml(template_yaml, model_json, output_yaml_path):
with open(template_yaml, 'r') as f:
model_yaml = yaml.load(f)
#
# get the model config:
json_file = open(model_json, 'r')
loaded_model_json = json_file.read()
json_file.close()
loaded_model = keras.models.model_from_json(loaded_model_json)
#
model_yaml["output_schema"]["targets"] = []
for oname, oshape in zip(loaded_model.output_names, loaded_model.output_shape):
append_el ={"name":oname , "shape":str(oshape)#replace("None,", "")
, "doc":"Methylation probability for %s"%oname}
model_yaml["output_schema"]["targets"].append(append_el)
#
with open(output_yaml_path, 'w') as f:
yaml.dump(model_yaml, f, default_flow_style=False)
示例9: saverc
# 需要导入模块: import json [as 别名]
# 或者: from json import dump [as 别名]
def saverc(filename, dat, overwrite=False):
'''
saverc(filename, d) saves the given configuration dictionary d to the given filename in JSON
format. If d is not a dictionary or if filename already exists or cannot be created, an error
is raised. This funciton does not create directories.
The optional argument overwrite (default: False) may be passed as True to overwrite files that
already exist.
'''
filename = os.path.expanduser(os.path.expandvars(filename))
if not overwrite and os.path.isfile(filename):
raise ValueError('Given filename %s already exists' % filename)
if not pimms.is_map(dat):
try: dat = dict(dat)
except Exception: raise ValueError('Given config data must be a dictionary')
with open(filename, 'w') as fl:
json.dump(dat, fl, sort_keys=True)
return filename
# the private class that handles all the details...
示例10: save_json
# 需要导入模块: import json [as 别名]
# 或者: from json import dump [as 别名]
def save_json(filename, obj, normalize=True):
'''
save_json(filename, obj) writes the given object to the given filename (or stream) in a
normalized JSON format.
The optional argument normalize (default True) may be set to False to prevent the object from
being run through neuropythy's normalize system.
'''
from neuropythy.util import normalize as norm
dat = norm(obj) if normalize else obj
if pimms.is_str(filename):
jsonstr = json.dumps(dat)
if any(filename.endswith(s) for s in ('.gz', '.bz2', '.lzma')):
with gzip.open(filename, 'wt') as fl: fl.write(jsonstr)
else:
with open(filename, 'wt') as fl: fl.write(jsonstr)
else: json.dump(dat, filename)
return filename
示例11: _write_coco_results
# 需要导入模块: import json [as 别名]
# 或者: from json import dump [as 别名]
def _write_coco_results(self, _coco, detections):
""" example results
[{"image_id": 42,
"category_id": 18,
"bbox": [258.15,41.29,348.26,243.78],
"score": 0.236}, ...]
"""
cats = [cat['name'] for cat in _coco.loadCats(_coco.getCatIds())]
class_to_coco_ind = dict(zip(cats, _coco.getCatIds()))
results = []
for cls_ind, cls in enumerate(self.classes):
if cls == '__background__':
continue
logger.info('collecting %s results (%d/%d)' % (cls, cls_ind, self.num_classes - 1))
coco_cat_id = class_to_coco_ind[cls]
results.extend(self._coco_results_one_category(detections[cls_ind], coco_cat_id))
logger.info('writing results json to %s' % self._result_file)
with open(self._result_file, 'w') as f:
json.dump(results, f, sort_keys=True, indent=4)
示例12: loadProxies
# 需要导入模块: import json [as 别名]
# 或者: from json import dump [as 别名]
def loadProxies():
proxiesList = []
cprint("Loading proxies...","green")
site2(proxiesList) # load proxies
# proxiesList = ["13.85.80.251:443"]
# proxiesList = ["13.85.80.251:443"]
# proxiesList = ["144.217.16.78:3128"]
proxiesList = proxiesList[::-1]
proxiesList = proxiesList[:10]
proxiesList = filterConnections(proxiesList) # filter for working connections
# Write to file
with open("proxies.txt", 'w') as outfile:
json.dump(proxiesList, outfile)
cprint("Proxies saved to proxies.txt!","magenta","on_grey", attrs=['bold'])
示例13: write_output
# 需要导入模块: import json [as 别名]
# 或者: from json import dump [as 别名]
def write_output(bucket_name, key_name, output_key_name, outstanding_requesters):
logging.getLogger().debug('[write_output] Start')
try:
current_data = '/tmp/' + key_name.split('/')[-1] + '_LOCAL.json'
with open(current_data, 'w') as outfile:
json.dump(outstanding_requesters, outfile)
s3 = boto3.client('s3')
s3.upload_file(current_data, bucket_name, output_key_name, ExtraArgs={'ContentType': "application/json"})
remove(current_data)
except Exception as e:
logging.getLogger().error("[write_output] \tError to write output file")
logging.getLogger().error(e)
logging.getLogger().debug('[write_output] End')
示例14: train
# 需要导入模块: import json [as 别名]
# 或者: from json import dump [as 别名]
def train(session, model, curr_dir, data_train, data_val):
curr_dir = os.path.join(curr_dir, model.algorithm)
bestmodel_dir = os.path.join(curr_dir, 'best_checkpoint')
if not os.path.exists(curr_dir):
os.makedirs(curr_dir)
file_handler = logging.FileHandler(os.path.join(curr_dir, 'log.txt'))
logging.getLogger().addHandler(file_handler)
with open(os.path.join(curr_dir, FLAGS['save_name'] + '.json'), 'w') as f:
json.dump(FLAGS, f)
if not os.path.exists(bestmodel_dir):
os.makedirs(bestmodel_dir)
initialize_model(session, model, curr_dir, expect_exists=False)
model.train(session, curr_dir, bestmodel_dir, data_train, data_val)
示例15: record_results
# 需要导入模块: import json [as 别名]
# 或者: from json import dump [as 别名]
def record_results(self, file_nm):
json.dump(self, open(file_nm, 'w'), indent=4,
default=self.jsondump)