本文整理匯總了Python中utils.load_config方法的典型用法代碼示例。如果您正苦於以下問題:Python utils.load_config方法的具體用法?Python utils.load_config怎麽用?Python utils.load_config使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類utils
的用法示例。
在下文中一共展示了utils.load_config方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: main
# 需要導入模塊: import utils [as 別名]
# 或者: from utils import load_config [as 別名]
def main():
args = make_args()
config = configparser.ConfigParser()
utils.load_config(config, args.config)
for cmd in args.modify:
utils.modify_config(config, cmd)
with open(os.path.expanduser(os.path.expandvars(args.logging)), 'r') as f:
logging.config.dictConfig(yaml.load(f))
model_dir = utils.get_model_dir(config)
path, step, epoch = utils.train.load_model(model_dir)
state_dict = torch.load(path, map_location=lambda storage, loc: storage)
mapper = [(inflection.underscore(name), member()) for name, member in inspect.getmembers(importlib.machinery.SourceFileLoader('', __file__).load_module()) if inspect.isclass(member)]
path = os.path.join(model_dir, os.path.basename(os.path.splitext(__file__)[0])) + '.xlsx'
with xlsxwriter.Workbook(path, {'strings_to_urls': False, 'nan_inf_to_errors': True}) as workbook:
worksheet = workbook.add_worksheet(args.worksheet)
for j, (key, m) in enumerate(mapper):
worksheet.write(0, j, key)
for i, (name, variable) in enumerate(state_dict.items()):
value = m(name, variable)
worksheet.write(1 + i, j, value)
if hasattr(m, 'format'):
m.format(workbook, worksheet, i, j)
worksheet.autofilter(0, 0, i, len(mapper) - 1)
worksheet.freeze_panes(1, 0)
logging.info(path)
示例2: test
# 需要導入模塊: import utils [as 別名]
# 或者: from utils import load_config [as 別名]
def test(exp_name, device, image_id):
config, _, _, _ = load_config(exp_name)
net, loss_fn = build_model(config, device, train=False)
net.load_state_dict(torch.load(get_model_name(config), map_location=device))
net.set_decode(True)
train_loader, val_loader = get_data_loader(1, config['use_npy'], geometry=config['geometry'],
frame_range=config['frame_range'])
net.eval()
with torch.no_grad():
num_gt, num_pred, scores, pred_image, pred_match, loss, t_forward, t_nms = \
eval_one(net, loss_fn, config, train_loader, image_id, device, plot=True)
TP = (pred_match != -1).sum()
print("Loss: {:.4f}".format(loss))
print("Precision: {:.2f}".format(TP/num_pred))
print("Recall: {:.2f}".format(TP/num_gt))
print("forward pass time {:.3f}s".format(t_forward))
print("nms time {:.3f}s".format(t_nms))
示例3: main
# 需要導入模塊: import utils [as 別名]
# 或者: from utils import load_config [as 別名]
def main( _ ):
args = parser.parse_args()
# TODO(apply proposed change)
# shim to reboot if the transport end point is disconnected
# We will remove this in the next experiment and add it as a background process launched from user data
# subprocess.call(
# "watch -n 300 'bash /home/ubuntu/task-taxonomy-331b/tools/script/reboot_if_disconnected.sh' &>/dev/null &",
# shell=True
# )
print(args)
# Get available GPUs
local_device_protos = utils.get_available_devices()
print( 'Found devices:', [ x.name for x in local_device_protos ] )
# set gpu
if args.gpu_id is not None:
print( 'using gpu %d' % args.gpu_id )
os.environ[ 'CUDA_VISIBLE_DEVICES' ] = str( args.gpu_id )
else:
print( 'no gpu specified' )
# load config and run training
cfg = utils.load_config( args.cfg_dir, nopause=args.nopause )
# cfg['num_read_threads'] = 1
run_training( cfg, args.cfg_dir )
示例4: main
# 需要導入模塊: import utils [as 別名]
# 或者: from utils import load_config [as 別名]
def main( _ ):
args = parser.parse_args()
print(args)
# Get available GPUs
local_device_protos = utils.get_available_devices()
print( 'Found devices:', [ x.name for x in local_device_protos ] )
# set gpu
if args.gpu_id is not None:
print( 'using gpu %d' % args.gpu_id )
os.environ[ 'CUDA_VISIBLE_DEVICES' ] = str( args.gpu_id )
else:
print( 'no gpu specified' )
# load config and run training
cfg = utils.load_config( args.cfg_dir, nopause=args.nopause )
cfg['task_name'] = args.cfg_dir.split('/')[-1]
cfg['task_name'] = 'class_selected'
cfg['num_epochs'] = 1
run_val_test( cfg )
示例5: main
# 需要導入模塊: import utils [as 別名]
# 或者: from utils import load_config [as 別名]
def main( _ ):
args = parser.parse_args()
#task_list = ["autoencoder", "colorization","curvature", "denoise", "edge2d", "edge3d", "ego_motion", "fix_pose", "impainting", "jigsaw", "keypoint2d", "keypoint3d", "non_fixated_pose", "point_match", "reshade", "rgb2depth", "rgb2mist", "rgb2sfnorm", "room_layout", "segment25d", "segment2d", "vanishing_point"]
#single channel for colorization !!!!!!!!!!!!!!!!!!!!!!!!! COME BACK TO THIS !!!!!!!!!!!!!!!!!!!!!!!!!!!
#task_list = [ "point_match"]
task_list = [ "vanishing_point"]
# Get available GPUs
local_device_protos = utils.get_available_devices()
print( 'Found devices:', [ x.name for x in local_device_protos ] )
# set GPU id
if args.gpu_id:
print( 'using gpu %d' % args.gpu_id )
os.environ[ 'CUDA_VISIBLE_DEVICES' ] = str( args.gpu_id )
else:
print( 'no gpu specified' )
for task in task_list:
task_dir = os.path.join(args.cfg_dir, task)
cfg = utils.load_config( task_dir, nopause=args.nopause )
root_dir = cfg['root_dir']
cfg['randomize'] = False
cfg['num_epochs'] = 1
run_rand_baseline( args, cfg, task )
示例6: main
# 需要導入模塊: import utils [as 別名]
# 或者: from utils import load_config [as 別名]
def main( _ ):
args = parser.parse_args()
print(args)
# Get available GPUs
local_device_protos = utils.get_available_devices()
print( 'Found devices:', [ x.name for x in local_device_protos ] )
# set gpu
if args.gpu_id is not None:
print( 'using gpu %d' % args.gpu_id )
os.environ[ 'CUDA_VISIBLE_DEVICES' ] = str( args.gpu_id )
else:
print( 'no gpu specified' )
# load config and run training
cfg = utils.load_config( args.cfg_dir, nopause=args.nopause )
cfg['train_filenames'] = cfg['train_filenames'].replace('task-taxonomy-331b/assets/aws_data', 's3/meta')
cfg['num_epochs'] = 6
cfg['learning_rate_schedule_kwargs' ] = {
'boundaries': [np.int64(0), np.int64(1800000)], # need to be int64 since global step is...
'values': [cfg['initial_learning_rate'], cfg['initial_learning_rate']/10]
}
cfg['randomize'] = True
run_training( cfg, args.cfg_dir )
示例7: main
# 需要導入模塊: import utils [as 別名]
# 或者: from utils import load_config [as 別名]
def main( _ ):
args = parser.parse_args()
print(args)
# Get available GPUs
local_device_protos = utils.get_available_devices()
print( 'Found devices:', [ x.name for x in local_device_protos ] )
# set gpu
if args.gpu_id is not None:
print( 'using gpu %d' % args.gpu_id )
os.environ[ 'CUDA_VISIBLE_DEVICES' ] = str( args.gpu_id )
else:
print( 'no gpu specified' )
# load config and run training
cfg = utils.load_config( args.cfg_dir, nopause=args.nopause )
# cfg['num_read_threads'] = 1
run_training( cfg, args.cfg_dir )
示例8: main
# 需要導入模塊: import utils [as 別名]
# 或者: from utils import load_config [as 別名]
def main( _ ):
args = parser.parse_args()
print(args)
# Get available GPUs
local_device_protos = utils.get_available_devices()
print( 'Found devices:', [ x.name for x in local_device_protos ] )
# set gpu
if args.gpu_id is not None:
print( 'using gpu %d' % args.gpu_id )
os.environ[ 'CUDA_VISIBLE_DEVICES' ] = str( args.gpu_id )
else:
print( 'no gpu specified' )
# load config and run training
cfg = utils.load_config( args.cfg_dir, nopause=args.nopause )
run_training( cfg, args.cfg_dir )
示例9: evaluate_line
# 需要導入模塊: import utils [as 別名]
# 或者: from utils import load_config [as 別名]
def evaluate_line():
config = load_config(FLAGS.config_file)
logger = get_logger(FLAGS.log_file)
# limit GPU memory
tf_config = tf.ConfigProto()
tf_config.gpu_options.allow_growth = True
with open(FLAGS.map_file, "rb") as f:
char_to_id, id_to_char, tag_to_id, id_to_tag = pickle.load(f)
with tf.Session(config=tf_config) as sess:
model = create_model(sess, Model, FLAGS.ckpt_path, load_word2vec, config, id_to_char, logger, False)
while True:
# try:
# line = input("請輸入測試句子:")
# result = ckpt.evaluate_line(sess, input_from_line(line, char_to_id), id_to_tag)
# print(result)
# except Exception as e:
# logger.info(e)
line = input("請輸入測試句子:")
result = model.evaluate_line(sess, input_from_line(line, char_to_id), id_to_tag)
print(result)
示例10: _test_predictors
# 需要導入模塊: import utils [as 別名]
# 或者: from utils import load_config [as 別名]
def _test_predictors(
self, predictors, overwrite_cfgs, overwrite_in_channels,
hwsize,
):
''' Make sure predictors run '''
self.assertGreater(len(predictors), 0)
in_channels_default = 64
for name, builder in predictors.items():
print('Testing {}...'.format(name))
if name in overwrite_cfgs:
cfg = load_config(overwrite_cfgs[name])
else:
# Use default config if config file is not specified
cfg = copy.deepcopy(g_cfg)
in_channels = overwrite_in_channels.get(
name, in_channels_default)
fe = builder(cfg, in_channels)
N, C_in, H, W = 2, in_channels, hwsize, hwsize
input = torch.rand([N, C_in, H, W], dtype=torch.float32)
out = fe(input)
yield input, out, cfg
示例11: test_build_backbones
# 需要導入模塊: import utils [as 別名]
# 或者: from utils import load_config [as 別名]
def test_build_backbones(self):
''' Make sure backbones run '''
self.assertGreater(len(registry.BACKBONES), 0)
for name, backbone_builder in registry.BACKBONES.items():
print('Testing {}...'.format(name))
if name in BACKBONE_CFGS:
cfg = load_config(BACKBONE_CFGS[name])
else:
# Use default config if config file is not specified
cfg = copy.deepcopy(g_cfg)
backbone = backbone_builder(cfg)
# make sures the backbone has `out_channels`
self.assertIsNotNone(
getattr(backbone, 'out_channels', None),
'Need to provide out_channels for backbone {}'.format(name)
)
N, C_in, H, W = 2, 3, 224, 256
input = torch.rand([N, C_in, H, W], dtype=torch.float32)
out = backbone(input)
for cur_out in out:
self.assertEqual(
cur_out.shape[:2],
torch.Size([N, backbone.out_channels])
)
示例12: _test_feature_extractors
# 需要導入模塊: import utils [as 別名]
# 或者: from utils import load_config [as 別名]
def _test_feature_extractors(
self, extractors, overwrite_cfgs, overwrite_in_channels
):
''' Make sure roi box feature extractors run '''
self.assertGreater(len(extractors), 0)
in_channels_default = 64
for name, builder in extractors.items():
print('Testing {}...'.format(name))
if name in overwrite_cfgs:
cfg = load_config(overwrite_cfgs[name])
else:
# Use default config if config file is not specified
cfg = copy.deepcopy(g_cfg)
in_channels = overwrite_in_channels.get(
name, in_channels_default)
fe = builder(cfg, in_channels)
self.assertIsNotNone(
getattr(fe, 'out_channels', None),
'Need to provide out_channels for feature extractor {}'.format(name)
)
N, C_in, H, W = 2, in_channels, 24, 32
input = torch.rand([N, C_in, H, W], dtype=torch.float32)
bboxes = [[1, 1, 10, 10], [5, 5, 8, 8], [2, 2, 3, 4]]
img_size = [384, 512]
box_list = BoxList(bboxes, img_size, "xyxy")
out = fe([input], [box_list] * N)
self.assertEqual(
out.shape[:2],
torch.Size([N * len(bboxes), fe.out_channels])
)
示例13: test_build_rpn_heads
# 需要導入模塊: import utils [as 別名]
# 或者: from utils import load_config [as 別名]
def test_build_rpn_heads(self):
''' Make sure rpn heads run '''
self.assertGreater(len(registry.RPN_HEADS), 0)
in_channels = 64
num_anchors = 10
for name, builder in registry.RPN_HEADS.items():
print('Testing {}...'.format(name))
if name in RPN_CFGS:
cfg = load_config(RPN_CFGS[name])
else:
# Use default config if config file is not specified
cfg = copy.deepcopy(g_cfg)
rpn = builder(cfg, in_channels, num_anchors)
N, C_in, H, W = 2, in_channels, 24, 32
input = torch.rand([N, C_in, H, W], dtype=torch.float32)
LAYERS = 3
out = rpn([input] * LAYERS)
self.assertEqual(len(out), 2)
logits, bbox_reg = out
for idx in range(LAYERS):
self.assertEqual(
logits[idx].shape,
torch.Size([
input.shape[0], num_anchors,
input.shape[2], input.shape[3],
])
)
self.assertEqual(
bbox_reg[idx].shape,
torch.Size([
logits[idx].shape[0], num_anchors * 4,
logits[idx].shape[2], logits[idx].shape[3],
]),
)
示例14: main
# 需要導入模塊: import utils [as 別名]
# 或者: from utils import load_config [as 別名]
def main():
args = make_args()
config = configparser.ConfigParser()
utils.load_config(config, args.config)
for cmd in args.modify:
utils.modify_config(config, cmd)
with open(os.path.expanduser(os.path.expandvars(args.logging)), 'r') as f:
logging.config.dictConfig(yaml.load(f))
model_dir = utils.get_model_dir(config)
model = onnx.load(model_dir + '.onnx')
onnx.checker.check_model(model)
init_net, predict_net = onnx_caffe2.backend.Caffe2Backend.onnx_graph_to_caffe2_net(model.graph, device='CPU')
onnx_caffe2.helper.save_caffe2_net(init_net, os.path.join(model_dir, 'init_net.pb'))
onnx_caffe2.helper.save_caffe2_net(predict_net, os.path.join(model_dir, 'predict_net.pb'), output_txt=True)
logging.info(model_dir)
示例15: main
# 需要導入模塊: import utils [as 別名]
# 或者: from utils import load_config [as 別名]
def main():
args = make_args()
config = configparser.ConfigParser()
utils.load_config(config, args.config)
for cmd in args.modify:
utils.modify_config(config, cmd)
with open(os.path.expanduser(os.path.expandvars(args.logging)), 'r') as f:
logging.config.dictConfig(yaml.load(f))
torch.manual_seed(args.seed)
model_dir = utils.get_model_dir(config)
init_net = caffe2_pb2.NetDef()
with open(os.path.join(model_dir, 'init_net.pb'), 'rb') as f:
init_net.ParseFromString(f.read())
predict_net = caffe2_pb2.NetDef()
with open(os.path.join(model_dir, 'predict_net.pb'), 'rb') as f:
predict_net.ParseFromString(f.read())
p = workspace.Predictor(init_net, predict_net)
height, width = tuple(map(int, config.get('image', 'size').split()))
tensor = torch.randn(1, 3, height, width)
# Checksum
output = p.run([tensor.numpy()])
for key, a in [
('tensor', tensor.cpu().numpy()),
('output', output[0]),
]:
print('\t'.join(map(str, [key, a.shape, utils.abs_mean(a), hashlib.md5(a.tostring()).hexdigest()])))