当前位置: 首页>>代码示例>>Python>>正文


Python serializers.load_npz方法代码示例

本文整理汇总了Python中chainer.serializers.load_npz方法的典型用法代码示例。如果您正苦于以下问题:Python serializers.load_npz方法的具体用法?Python serializers.load_npz怎么用?Python serializers.load_npz使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在chainer.serializers的用法示例。


在下文中一共展示了serializers.load_npz方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: test

# 需要导入模块: from chainer import serializers [as 别名]
# 或者: from chainer.serializers import load_npz [as 别名]
def test(self, cgp, model_file, comp_graph='comp_graph.dot', batchsize=256):
        chainer.cuda.get_device(0).use()  # Make a specified GPU current
        model = CGP2CNN(cgp, self.n_class)
        print('\tLoad model from', model_file)
        serializers.load_npz(model_file, model)
        model.to_gpu(0)
        test_accuracy, test_loss = self.__test(model, batchsize)
        print('\tparamNum={}'.format(model.param_num))
        print('\ttest mean loss={}, test accuracy={}'.format(test_loss / self.test_data_num, test_accuracy / self.test_data_num))

        if comp_graph is not None:
            with open(comp_graph, 'w') as o:
                g = computational_graph.build_computational_graph((model.loss,))
                o.write(g.dump())
                del g
                print('\tCNN graph generated ({}).'.format(comp_graph))

        return test_accuracy, test_loss 
开发者ID:sg-nm,项目名称:cgp-cnn,代码行数:20,代码来源:cnn_train.py

示例2: predict

# 需要导入模块: from chainer import serializers [as 别名]
# 或者: from chainer.serializers import load_npz [as 别名]
def predict(limit):
    _limit = limit if limit > 0 else 5

    td = TrainingData(LABEL_FILE, img_root=IMAGES_ROOT, mean_image_file=MEAN_IMAGE_FILE, image_property=IMAGE_PROP)
    label_def = LabelingMachine.read_label_def(LABEL_DEF_FILE)
    model = alex.Alex(len(label_def))
    serializers.load_npz(MODEL_FILE, model)

    i = 0
    for arr, im in td.generate():
        x = np.ndarray((1,) + arr.shape, arr.dtype)
        x[0] = arr
        x = chainer.Variable(np.asarray(x), volatile="on")
        y = model.predict(x)
        p = np.argmax(y.data)
        print("predict {0}, actual {1}".format(label_def[p], label_def[im.label]))
        im.image.show()
        i += 1
        if i >= _limit:
            break 
开发者ID:icoxfog417,项目名称:mlimages,代码行数:22,代码来源:chainer_alex.py

示例3: load_model_flexible

# 需要导入模块: from chainer import serializers [as 别名]
# 或者: from chainer.serializers import load_npz [as 别名]
def load_model_flexible(filename_list, encdec):
    mode = "normal"
    if isinstance(filename_list, tuple) or isinstance(filename_list, list):
        if len(filename_list) == 1:
            filename_list = filename_list[0]
        else:
            mode = "average"
            
    if mode == "normal":
        log.info("loading model parameters from %s", filename_list)
        try:
            serializers.load_npz(filename_list, encdec)
        except KeyError:
            log.info("not model format, trying snapshot format")
            with np.load(filename_list) as fseri:
                dicseri = serializers.NpzDeserializer(fseri, path="updater/model:main/")
                dicseri.load(encdec)        
    else:
        assert mode == "average"
        log.info("loading averaged model parameters from %r", filename_list)
        dseri = NpzDeserializerAverage([np.load(filename) for filename in filename_list])
        dseri.load(encdec) 
开发者ID:fabiencro,项目名称:knmt,代码行数:24,代码来源:train.py

示例4: test_resumed_trigger

# 需要导入模块: from chainer import serializers [as 别名]
# 或者: from chainer.serializers import load_npz [as 别名]
def test_resumed_trigger(self):
        trainer = testing.get_trainer_with_mock_updater(
            stop_trigger=None, iter_per_epoch=self.iter_per_epoch)
        with tempfile.NamedTemporaryFile(delete=False) as f:
            trigger = training.triggers.ManualScheduleTrigger(*self.schedule)
            for expected, finished in zip(self.expected[:self.resume],
                                          self.finished[:self.resume]):
                trainer.updater.update()
                self.assertEqual(trigger(trainer), expected)
                self.assertEqual(trigger.finished, finished)
            serializers.save_npz(f.name, trigger)

            trigger = training.triggers.ManualScheduleTrigger(*self.schedule)
            serializers.load_npz(f.name, trigger)
            for expected, finished in zip(self.expected[self.resume:],
                                          self.finished[self.resume:]):
                trainer.updater.update()
                self.assertEqual(trigger(trainer), expected)
                self.assertEqual(trigger.finished, finished) 
开发者ID:chainer,项目名称:chainer,代码行数:21,代码来源:test_manual_schedule_trigger.py

示例5: test_resumed_trigger_backward_compat

# 需要导入模块: from chainer import serializers [as 别名]
# 或者: from chainer.serializers import load_npz [as 别名]
def test_resumed_trigger_backward_compat(self):
        trainer = testing.get_trainer_with_mock_updater(
            stop_trigger=None, iter_per_epoch=self.iter_per_epoch)
        with tempfile.NamedTemporaryFile(delete=False) as f:
            trigger = training.triggers.ManualScheduleTrigger(*self.schedule)
            for expected, finished in zip(self.expected[:self.resume],
                                          self.finished[:self.resume]):
                trainer.updater.update()
                self.assertEqual(trigger(trainer), expected)
                self.assertEqual(trigger.finished, finished)
            # old version does not save anything
            np.savez(f, dummy=0)

            trigger = training.triggers.ManualScheduleTrigger(*self.schedule)
            with testing.assert_warns(UserWarning):
                serializers.load_npz(f.name, trigger)
            for expected, finished in zip(self.expected[self.resume:],
                                          self.finished[self.resume:]):
                trainer.updater.update()
                self.assertEqual(trigger(trainer), expected)
                self.assertEqual(trigger.finished, finished) 
开发者ID:chainer,项目名称:chainer,代码行数:23,代码来源:test_manual_schedule_trigger.py

示例6: test_resumed_trigger_sparse_call

# 需要导入模块: from chainer import serializers [as 别名]
# 或者: from chainer.serializers import load_npz [as 别名]
def test_resumed_trigger_sparse_call(self):
        trainer = testing.get_trainer_with_mock_updater(
            stop_trigger=None, iter_per_epoch=self.iter_per_epoch)
        accumulated = False
        with tempfile.NamedTemporaryFile(delete=False) as f:
            trigger = training.triggers.IntervalTrigger(*self.interval)
            for expected in self.expected[:self.resume]:
                trainer.updater.update()
                accumulated = accumulated or expected
                if random.randrange(2):
                    self.assertEqual(trigger(trainer), accumulated)
                    accumulated = False
            serializers.save_npz(f.name, trigger)

            trigger = training.triggers.IntervalTrigger(*self.interval)
            serializers.load_npz(f.name, trigger)
            for expected in self.expected[self.resume:]:
                trainer.updater.update()
                accumulated = accumulated or expected
                if random.randrange(2):
                    self.assertEqual(trigger(trainer), accumulated)
                    accumulated = False 
开发者ID:chainer,项目名称:chainer,代码行数:24,代码来源:test_interval_trigger.py

示例7: test_resumed_trigger

# 需要导入模块: from chainer import serializers [as 别名]
# 或者: from chainer.serializers import load_npz [as 别名]
def test_resumed_trigger(self):
        trainer = testing.get_trainer_with_mock_updater(
            stop_trigger=None, iter_per_epoch=self.iter_per_epoch)
        with tempfile.NamedTemporaryFile(delete=False) as f:
            trigger = training.triggers.OnceTrigger(self.call_on_resume)
            for expected, finished in zip(self.resumed_expected[:self.resume],
                                          self.resumed_finished[:self.resume]):
                trainer.updater.update()
                self.assertEqual(trigger.finished, finished)
                self.assertEqual(trigger(trainer), expected)
            serializers.save_npz(f.name, trigger)

            trigger = training.triggers.OnceTrigger(self.call_on_resume)
            serializers.load_npz(f.name, trigger)
            for expected, finished in zip(self.resumed_expected[self.resume:],
                                          self.resumed_finished[self.resume:]):
                trainer.updater.update()
                self.assertEqual(trigger.finished, finished)
                self.assertEqual(trigger(trainer), expected) 
开发者ID:chainer,项目名称:chainer,代码行数:21,代码来源:test_once_trigger.py

示例8: test_resumed_trigger_backward_compat

# 需要导入模块: from chainer import serializers [as 别名]
# 或者: from chainer.serializers import load_npz [as 别名]
def test_resumed_trigger_backward_compat(self):
        trainer = testing.get_trainer_with_mock_updater(
            stop_trigger=None, iter_per_epoch=self.iter_per_epoch)
        with tempfile.NamedTemporaryFile(delete=False) as f:
            trigger = training.triggers.OnceTrigger(self.call_on_resume)
            for expected, finished in zip(self.resumed_expected[:self.resume],
                                          self.resumed_finished[:self.resume]):
                trainer.updater.update()
                self.assertEqual(trigger.finished, finished)
                self.assertEqual(trigger(trainer), expected)
            # old version does not save anything
            np.savez(f, dummy=0)

            trigger = training.triggers.OnceTrigger(self.call_on_resume)
            with testing.assert_warns(UserWarning):
                serializers.load_npz(f.name, trigger)
            for expected, finished in zip(self.resumed_expected[self.resume:],
                                          self.resumed_finished[self.resume:]):
                trainer.updater.update()
                self.assertEqual(trigger.finished, finished)
                self.assertEqual(trigger(trainer), expected) 
开发者ID:chainer,项目名称:chainer,代码行数:23,代码来源:test_once_trigger.py

示例9: get_model

# 需要导入模块: from chainer import serializers [as 别名]
# 或者: from chainer.serializers import load_npz [as 别名]
def get_model(model_path, n_joints, result_dir, resume_model):
    model_fn = os.path.basename(model_path)
    model_name = model_fn.split('.')[0]
    model = imp.load_source(model_name, model_path)
    model = getattr(model, model_name)

    # Initialize
    model = model(n_joints)

    # Copy files
    dst = '{}/{}'.format(result_dir, model_fn)
    if not os.path.exists(dst):
        shutil.copy(model_path, dst)

    # load model
    if resume_model is not None:
        serializers.load_npz(resume_model, model)

    return model 
开发者ID:mitmul,项目名称:deeppose,代码行数:21,代码来源:train.py

示例10: __init__

# 需要导入模块: from chainer import serializers [as 别名]
# 或者: from chainer.serializers import load_npz [as 别名]
def __init__(self,modelpath='misc/VGG16_faster_rcnn_final.model',
					mean=[102.9801, 115.9465, 122.7717],
					in_size=224):
		super(FasterRCNN,self).__init__('FasterRCNN',in_size)
		self.func = FRCNN(Deel.gpu)
		self.func.train=False
		serializers.load_npz('misc/VGG16_faster_rcnn_final.model', self.func)

		ImageNet.mean_image = np.ndarray((3, 256, 256), dtype=np.float32)
		ImageNet.mean_image[0] = mean[0]
		ImageNet.mean_image[1] = mean[1]
		ImageNet.mean_image[2] = mean[2]
		ImageNet.in_size = in_size

		self.labels = CLASSES

		self.batchsize = 1
		xp = Deel.xp
		self.x_batch = xp.ndarray((self.batchsize, 3, self.in_size, self.in_size), dtype=np.float32)

		if Deel.gpu >=0:
			self.func = self.func.to_gpu(Deel.gpu)
		self.optimizer = optimizers.Adam()
		self.optimizer.setup(self.func) 
开发者ID:uei,项目名称:deel,代码行数:26,代码来源:fasterRCNN.py

示例11: load_npz_no_strict

# 需要导入模块: from chainer import serializers [as 别名]
# 或者: from chainer.serializers import load_npz [as 别名]
def load_npz_no_strict(filename, obj):
    try:
        serializers.load_npz(filename, obj)
    except KeyError as e:
        warnings.warn(repr(e))
        with numpy.load(filename) as f:
            d = serializers.NpzDeserializer(f, strict=False)
            d.load(obj) 
开发者ID:chainer,项目名称:chainerrl,代码行数:10,代码来源:agent.py

示例12: create_and_load_encdec_from_files

# 需要导入模块: from chainer import serializers [as 别名]
# 或者: from chainer.serializers import load_npz [as 别名]
def create_and_load_encdec_from_files(config_training_fn, trained_model):
    log.info("loading model config from %s" % config_training_fn)

    config_training = train_config.load_config_train(config_training_fn)
    encdec, eos_idx, src_indexer, tgt_indexer = train.create_encdec_and_indexers_from_config_dict(config_training)

    log.info("loading model from %s" % trained_model)
    serializers.load_npz(trained_model, encdec)

    return encdec, eos_idx, src_indexer, tgt_indexer 
开发者ID:fabiencro,项目名称:knmt,代码行数:12,代码来源:eval.py

示例13: load_encdec_from_config

# 需要导入模块: from chainer import serializers [as 别名]
# 或者: from chainer.serializers import load_npz [as 别名]
def load_encdec_from_config(config_fn, model_fn):
    config=json.load(open(config_fn))
    ced = create_model(config)
    charlist = json.load(open(config["indexer"], "r"))
    chardict = dict((c,i) for i,c in enumerate(charlist))
    serializers.load_npz(model_fn, ced)
    return ced, charlist, chardict 
开发者ID:fabiencro,项目名称:knmt,代码行数:9,代码来源:char_encdec.py

示例14: generate

# 需要导入模块: from chainer import serializers [as 别名]
# 或者: from chainer.serializers import load_npz [as 别名]
def generate():
    parser = argparse.ArgumentParser()
    parser.add_argument('--gpu', '-g', type=int, default=-1)
    parser.add_argument('--gen', type=str, default=None)
    parser.add_argument('--depth', '-d', type=int, default=0)
    parser.add_argument('--out', '-o', type=str, default='img/')
    parser.add_argument('--num', '-n', type=int, default=10)
    args = parser.parse_args()
    
    gen = network.Generator(depth=args.depth)
    print('loading generator model from ' + args.gen)
    serializers.load_npz(args.gen, gen)

    if args.gpu >= 0:
        cuda.get_device_from_id(0).use()
        gen.to_gpu()

    xp = gen.xp
        
    z1 = gen.z(1)
    z2 = gen.z(1)

    for i in range(args.num):
        print(i)
        p = i / (args.num-1)
        z = z1 * p + z2 * (1 - p)
        x = gen(z, alpha=1.0)
        x = chainer.cuda.to_cpu(x.data)
        
        img = x[0].copy()
        filename = os.path.join(args.out, 'gen_%04d.png'%i)
        utils.save_image(img, filename) 
开发者ID:joisino,项目名称:chainer-PGGAN,代码行数:34,代码来源:analogy.py

示例15: model_fn

# 需要导入模块: from chainer import serializers [as 别名]
# 或者: from chainer.serializers import load_npz [as 别名]
def model_fn(model_dir):
    model = L.Classifier(MLP(1000, 10))
    serializers.load_npz(os.path.join(model_dir, "model.npz"), model)
    return model.predictor 
开发者ID:aws,项目名称:sagemaker-python-sdk,代码行数:6,代码来源:distributed_mnist.py


注:本文中的chainer.serializers.load_npz方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。