• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python serial.save函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中pylearn2.utils.serial.save函数的典型用法代码示例。如果您正苦于以下问题:Python save函数的具体用法?Python save怎么用?Python save使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



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

示例1: on_monitor

    def on_monitor(self, model, dataset, algorithm):
        """
        Make sure Polyak-averaged model gets monitored.
        Save the model if necessary.

        Parameters
        ----------
        model : a Model instance
        dataset : Dataset
        algorithm : WRITEME
        """
        if self._count == self.start:
            self._worker = _PolyakWorker(model)
            algorithm.update_callbacks.append(self._worker)
            #HACK
            try:
                model.add_polyak_channels(self._worker.param_to_mean,
                                          algorithm.monitoring_dataset)
            except AttributeError:
                pass
        elif self.save_path is not None and self._count > self.start and \
                self._count % self.save_freq == 0:
            saved_params = OrderedDict()
            for param in model.get_params():
                saved_params[param] = param.get_value()
                param.set_value(self._worker.param_to_mean[param].get_value())
            serial.save(self.save_path, model)
            for param in model.get_params():
                param.set_value(saved_params[param])
        self._count += 1
开发者ID:AdityoSanjaya,项目名称:adversarial,代码行数:30,代码来源:sgd_alt.py


示例2: main

def main(train_path,
        out_path,
        dataset,
        standardize,
        C,
        **kwargs):

    stl10 = dataset == 'stl10'
    cifar10 = dataset == 'cifar10'
    cifar100 = dataset == 'cifar100'
    assert stl10 + cifar10 + cifar100 == 1

    print('getting labels and oflds')
    train_y, fold_indices = get_labels_and_fold_indices(cifar10, cifar100, stl10)
    gc.collect()
    assert train_y is not None

    print('loading training features')
    train_X = get_features(train_path, split = False, standardize = standardize)

    assert str(train_X.dtype) == 'float32'
    if stl10:
        assert train_X.shape[0] == 5000
    if cifar10 or cifar100:
        assert train_X.shape[0] == 50000
        assert train_y.shape == (50000,)

    print('training model')
    model =  train(train_X, train_y, C)

    print('saving model')
    serial.save(out_path, model)
开发者ID:123fengye741,项目名称:pylearn2,代码行数:32,代码来源:fit_final_model.py


示例3: cnn_ensemble_leave_one_out

def cnn_ensemble_leave_one_out():
    import os
    from datetime import datetime
    print str(datetime.now())
    t0 = time.time()
    which_fold = 0
    while 1:
        print which_fold
        try:
            kwargs = get_default_configure_leave_one_out(which_fold=which_fold)
        except:
            break
        kwargs['num_rows']=40
        kwargs['num_cols']=40
        pp=pprint.PrettyPrinter(indent=4)
        pp.pprint(kwargs)
        kwargs['save_path'] =  str(which_fold)+'.pkl'
        t1 = time.time()
        ann = cnn_train(**kwargs)
        serial.save(kwargs['predict_path']+'f'+kwargs['save_path'],ann,on_overwrite='backup')
        print 'saved to: '+kwargs['save_path']
        print 'Traing done. Take {}h'.format((time.time()-t1)/3600)
        which_fold += 1
    utils.sms_notice('Training finished. Taking {}h in total.'.format((time.time()-t0)/3600))
    print 'Traing done. Take {}h'.format((time.time()-t0)/3600)
    # sum of all predictions
    #predict_batch()
    evaluate_sets(kwargs['predict_path'])
开发者ID:leinxx,项目名称:pylearn2_cnn,代码行数:28,代码来源:cnn_pl_sar.py


示例4: cnn_transform_ensemble

def cnn_transform_ensemble():
    import os
    from datetime import datetime
    print str(datetime.now())
    t0 = time.time()
    kwargs = get_default_configure()
    kwargs['num_rows']=41
    kwargs['num_cols']=41
    import pprint
    pp=pprint.PrettyPrinter(indent=4)
    pp.pprint(kwargs)

    i = -1
    while under_sample_water.which_fold != i:
        if i == -1:
            i = under_sample_water.which_fold
        kwargs['save_path'] =  str(under_sample_water.which_fold)+'.pkl'
        t1 = time.time()
        ann = cnn_train_tranformer(**kwargs)
        serial.save(kwargs['predict_path']+'f'+kwargs['save_path'],ann,on_overwrite='backup')
        print 'saved to: '+kwargs['save_path']
        print 'Traing done. Take {}h'.format((time.time()-t1)/3600)
        break
    utils.sms_notice('Training finished. Taking {}h in total.'.format((time.time()-t0)/3600))
    print 'Traing done. Take {}h'.format((time.time()-t0)/3600)
    # sum of all predictions
    predict_batch(predict_path)
开发者ID:leinxx,项目名称:pylearn2_cnn,代码行数:27,代码来源:cnn_pl_sar.py


示例5: save_weights

    def save_weights(self):
        """
        Saves all weights in a .txt, .npy or .mat file depending on the ending of the 'weight_path'.
        If the path ends in .pkl, the entire model is stored. 
        """
    
        model = serial.load(self.model_path)
    
        weight_dict = {}
    
        for layer in model.layers:
            try:
                weight_dict[layer.layer_name] = layer.get_weights()
            except:
                layer_weights = layer.get_weights_topo()
                weight_dict[layer.layer_name] = layer_weights# without reshaping since it the input/output vector would need to reshaped in the same way which might lead to problems

        if self.weight_path[-4:] == '.pkl':
            print 'saving model ', self.weight_path
            serial.save(self.weight_path, model)
        elif self.weight_path[-4:] == '.mat':
            scipy.io.savemat(self.weight_path[:-4]+'.mat', weight_dict)
        elif self.weight_path[-4:] == '.npy':
            np.save(self.weight_path[:-4], weight_dict)
        else:
            raise Exception('Only ".mat", ".pkl" and ".npy" files are supported as data formats.')
开发者ID:pombredanne,项目名称:telluride-decoding-toolbox,代码行数:26,代码来源:DNNRegression.py


示例6: get_processed_dataset

def get_processed_dataset():

    train_path = 'pp_cifar10_train.pkl'
    test_path = 'pp_cifar10_test.pkl'

    if os.path.exists(train_path) and os.path.exists(test_path):
        print 'loading preprocessed data'
        trainset = serial.load(train_path)
        testset = serial.load(test_path)

    else:
        print 'loading raw data...'
        trainset = cifar10.CIFAR10(which_set="train")
        testset =  cifar10.CIFAR10(which_set="test")
	
        pipeline = preprocessing.Pipeline()
        pipeline.items.append(preprocessing.ExtractPatchesWithPosition(patch_shape=patch_shape, patches_per_image=patches_per_image))
        pipeline.items.append(preprocessing.GlobalContrastNormalization(sqrt_bias=10., use_std=True))
        pipeline.items.append(preprocessing.PCA(num_components = num_components, keep_var_fraction = keep_var_fraction))
        pipeline.items.append(preprocessing.ExtractPatchPairs(patches_per_image = patches_per_image, num_images = train_size, input_width = input_width))

        trainset.apply_preprocessor(preprocessor=pipeline, can_fit=True)

        # the pkl-ing is having issues, the dataset is maybe too big.
        serial.save('pp_cifar10_train.pkl', trainset)
        serial.save('pp_cifar10_test.pkl', testset)

        # this path will be used for visualizing weights after training is done
        trainset.yaml_src = '!pkl: "%s"' % train_path
        testset.yaml_src = '!pkl: "%s"' % test_path

    return trainset, testset
开发者ID:capybaralet,项目名称:current,代码行数:32,代码来源:testrun.py


示例7: on_monitor

 def on_monitor(self, model, dataset, algorithm):
     
     epoch = algorithm.monitor._epochs_seen;
     model_file = self.save_path + self.save_prefix + str(epoch) + '.pkl'; 
     
     with log_timing(log, 'saving model to {}'.format(model_file)):
         serial.save(model_file, model, on_overwrite = 'backup')
开发者ID:Qi0116,项目名称:deepthought,代码行数:7,代码来源:util.py


示例8: on_monitor

    def on_monitor(self, model, dataset, algorithm):
        """
        Looks whether the model performs better than earlier. If it's the
        case, saves the model.

        Parameters
        ----------
        model : pylearn2.models.model.Model
                model.monitor must contain a channel with name given by self.channel_name
        dataset : pylearn2.datasets.dataset.Dataset
            not used
        algorithm : TrainingAlgorithm
            not used
        """

        monitor = model.monitor
        channels = monitor.channels
        channel = channels[self.channel_name]
        val_record = channel.val_record
        new_cost = self.coeff * val_record[-1]

        if new_cost < self.best_cost:
            self.best_cost = new_cost
            serial.save(self.save_path, model, on_overwrite = 'backup')
            
            # XXX: [Kien] Save best filters.
            pv = get_weights_report.get_weights_report(model = model, 
                                                       dataset = dataset)
            pv.save('best_filters.png')                                           
开发者ID:KienTran89,项目名称:pylearn2,代码行数:29,代码来源:best_params.py


示例9: on_monitor

    def on_monitor(self, model, dataset, algorithm):
        """
        Looks whether the model performs better than earlier
        - or equally good (modification).
        If it's the case, saves the model.

        Parameters
        ----------
        model : pylearn2.models.model.Model
            model.monitor must contain a channel with name given by
            self.channel_name
        dataset : pylearn2.datasets.dataset.Dataset
            Not used
        algorithm : TrainingAlgorithm
            Not used
        """
        monitor = model.monitor
        channels = monitor.channels
        channel = channels[self.channel_name]
        val_record = channel.val_record
        new_cost = val_record[-1]

        if self.coeff * new_cost <= self.coeff * self.best_cost and \
           monitor._epochs_seen >= self.start_epoch:
            self.best_cost = new_cost
            # Update the tag of the model object before saving it.
            self._update_tag(model)
            if self.store_best_model:
                self.best_model = deepcopy(model)
            if self.save_path is not None:
                with log_timing(log, 'Saving to ' + self.save_path):
                    serial.save(self.save_path, model, on_overwrite='backup')
开发者ID:Qi0116,项目名称:deepthought,代码行数:32,代码来源:best_params.py


示例10: train_batch

    def train_batch(self, dataset, batch_size):

        x = dataset.get_batch_design(batch_size, include_labels=False)
        self.batch_train_func(x)

        # accounting...
        self.examples_seen += self.batch_size
        self.batches_seen += 1

        # modify learning rate multipliers
        for (k, iter) in self.lr_mults_it.iteritems():
            if iter.next():
                print 'self.batches_seen = ', self.batches_seen
                self.lr_mults_shrd[k].set_value(iter.value)
                print 'lr_mults_shrd[%s] = %f' % (k,iter.value)

        self.enforce_constraints()

        # save to different path each epoch
        if self.my_save_path and \
           (self.batches_seen in self.save_at or
            self.batches_seen % self.save_every == 0):
            fname = self.my_save_path + '_e%i.pkl' % self.batches_seen
            print 'Saving to %s ...' % fname,
            serial.save(fname, self)
            print 'done'

        return self.batches_seen < self.max_updates
开发者ID:codeaudit,项目名称:ssrbm,代码行数:28,代码来源:bin_pooled_ss_rbm.py


示例11: save

    def save(self):
        """
        Call on_save for Train and TrainCV extensions and serialize trained
        models if save_path is set.
        """
        # Train extensions
        for trainer in self.trainers:
            for extension in trainer.extensions:
                extension.on_save(trainer.model, trainer.dataset,
                                  trainer.algorithm)

        # TrainCV extensions
        for extension in self.cv_extensions:
            extension.on_save(self.trainers)

        # serialize trained models
        if self.save_path is not None:
            models = [trainer.model for trainer in self.trainers]
            try:
                for trainer in self.trainers:
                    trainer.dataset._serialization_guard = SerializationGuard()
                if not self.allow_overwrite and os.path.exists(self.save_path):
                    raise IOError("Trying to overwrite file when not allowed.")
                serial.save(self.save_path, models, on_overwrite='backup')
            finally:
                for trainer in self.trainers:
                    trainer.dataset._serialization_guard = None
开发者ID:tsoontornwutikul,项目名称:pylearn2,代码行数:27,代码来源:__init__.py


示例12: on_monitor

    def on_monitor(self, model, dataset, algorithm):
        """
        Save the model if we are on a save epoch.
        
        Parameters
        ----------
        model : pylearn2.models.model.Model
                model.monitor must contain a channel with name given by self.channel_name
        dataset : pylearn2.datasets.dataset.Dataset
            not used
        algorithm : TrainingAlgorithm
            not used
        """

        #monitor = model.monitor
        #channels = monitor.channels
        #channel = channels[self.channel_name]
        #val_record = channel.val_record
        #epoch = len(val_record)
        epoch = model.monitor.get_epochs_seen()

        save_file = '%s_%d.pkl' % (self.save_prefix, epoch)

        if np.mod(epoch, self.interval) == 0:
            print('Saving model to %s' % save_file)
            serial.save(save_file, model, on_overwrite = 'backup')
开发者ID:sdmassey27,项目名称:pylearn2,代码行数:26,代码来源:dropout_analysis.py


示例13: train_batch

    def train_batch(self, dataset, batch_size):

        x = dataset.get_batch_design(batch_size, include_labels=False)
        if self.flags['truncate_v']:
            x = numpy.clip(x, -self.truncation_bound['v'], self.truncation_bound['v'])
        try:
            self.batch_train_func(x)
            self.enforce_constraints()
        except:
            import pdb; pdb.set_trace()

        # accounting...
        self.examples_seen += self.batch_size
        self.batches_seen += 1

        # save to different path each epoch
        if self.my_save_path and \
           (self.batches_seen in self.save_at or
            self.batches_seen % self.save_every == 0):
            fname = self.my_save_path + '_e%i.pkl' % self.batches_seen
            print 'Saving to %s ...' % fname,
            serial.save(fname, self)
            print 'done'

        return self.batches_seen < self.max_updates
开发者ID:gdesjardins,项目名称:hossrbm,代码行数:25,代码来源:implicit_hossrbm_v03.py


示例14: on_monitor

    def on_monitor(self, model, dataset, algorithm):
        # this shall never happen but better safe than sorry
        if self.predictor is None:
            self.setup(model, dataset, algorithm)

        # obtaining validating set # TODO: finally we want to have train-validation-test set. Or sth.
        valid_x = algorithm.monitoring_dataset['valid'].X
        valid_y = algorithm.monitoring_dataset['valid'].y
        predictions = self.predictor.get_predictions(valid_x)
        threshold, score = self.compute_optimal_threshold_and_score(valid_y, predictions)

        self.threshold_list.append(threshold)
        self.score_list.append(score)

        if self.saving_path is not None and self.save:
            if max(self.score_list) == score:
                try:
                    # Make sure that saving does not serialize the dataset
                    dataset._serialization_guard = SerializationGuard()
                    save_path = self.saving_path
                    serial.save(save_path, model,
                                on_overwrite='backup')
                finally:
                    dataset._serialization_guard = None

        print "F1Score1Threshold score", score, "\ncorresponding threshold:", threshold
开发者ID:marekPedziwiatr,项目名称:DCN,代码行数:26,代码来源:symmetric_threshold.py


示例15: on_monitor

    def on_monitor(self, model, dataset, algorithm):
        import numpy as np
        # this shall never happen but better safe than sorry
        if self.predictor is None:
            self.setup(model, dataset, algorithm)

        # obtaining validating set #
        valid_x = algorithm.monitoring_dataset['valid'].X
        valid_y = algorithm.monitoring_dataset['valid'].y
        y_pred = self.predictor.get_predictions(valid_x)
        y_classes = [np.argmax(pred) for pred in y_pred]
        score = f1_score(y_true=valid_y, y_pred=y_classes)
        self.score_list.append(score)

        if self.saving_path is not None and self.save:
            if max(self.score_list) == score:
                try:
                    # Make sure that saving does not serialize the dataset
                    dataset._serialization_guard = SerializationGuard()
                    save_path = self.saving_path
                    serial.save(save_path, model,
                                on_overwrite='backup')
                finally:
                    dataset._serialization_guard = None

        print "F1 score:", score
开发者ID:marekPedziwiatr,项目名称:DCN,代码行数:26,代码来源:no_threshold.py


示例16: main

def main(train_path,
        out_path,
        split,
        **kwargs):



    print 'loading training features'

    train_X = get_features(train_path, split)
    #assert train_X.flags.c_contiguous
    gc.collect()


    assert str(train_X.dtype) == 'float32'
    assert train_X.shape[0] == 120

    report = Report(train_path, split)

    train_X_omnivore, train_y, fold_indices = get_training_subset(train_X, 'omnivore')

    model = train(fold_indices, train_X_omnivore, train_y, report, **kwargs)

    serial.save(out_path+'.omnivore.model.pkl', model)
    report.write(out_path+'.omnivore.validation_report.txt')


    report = Report(train_path, split)

    train_X_fruit, train_y, fold_indices = get_training_subset(train_X, 'fruit')

    model = train(fold_indices, train_X_fruit, train_y, report, **kwargs)

    serial.save(out_path+'.fruit.model.pkl', model)
    report.write(out_path+'.fruit.validation_report.txt')
开发者ID:cc13ny,项目名称:galatea,代码行数:35,代码来源:tlcloo_sub.py


示例17: on_monitor

    def on_monitor(self, model, dataset, algorithm):
        """
        Looks whether the model performs better than earlier. If it's the
        case, saves the model.

        Parameters
        ----------
        model : pylearn2.models.model.Model
            model.monitor must contain a channel with name given by
            self.channel_name
        dataset : pylearn2.datasets.dataset.Dataset
            Not used
        algorithm : TrainingAlgorithm
            Not used
        """

        monitor = model.monitor
        channels = monitor.channels
        channel = channels[self.channel_name]
        val_record = channel.val_record
        new_cost = self.coeff * val_record[-1]


        if new_cost < self.best_cost:
            self.best_cost = new_cost
            # Update the tag of the model object before saving it.
            self._update_tag(model)
            serial.save(self.save_path, model, on_overwrite = 'backup')
开发者ID:dzeno,项目名称:pylearn2,代码行数:28,代码来源:best_params.py


示例18: on_save

    def on_save(self, trainers):
        """
        Save best model from each cross-validation fold.

        Parameters
        ----------
        trainers : list
            List of Train objects belonging to the parent TrainCV object.
        """
        if self.save_path is None:
            return
        models = []
        for trainer in trainers:
            for extension in trainer.extensions:
                if isinstance(extension, MonitorBasedSaveBest):
                    models.append(extension.best_model)
                    break
        assert len(models) == len(trainers)
        try:
            for trainer in trainers:
                trainer.dataset._serialization_guard = SerializationGuard()
                serial.save(self.save_path, models, on_overwrite='backup')
        finally:
            for trainer in trainers:
                trainer.dataset._serialization_guard = None
开发者ID:ASAPPinc,项目名称:pylearn2,代码行数:25,代码来源:train_cv_extensions.py


示例19: compute_ZCA_fast

def compute_ZCA_fast(X, normalize, ZCA_filename="zca"):
    zca_preprocessor = preprocessing.ZCA()
    zca_preprocessor.set_matrices_save_path(ZCA_filename+".npz")
    X = X.astype(np.float32)
    if normalize:
        X /= 255.0
    zca_preprocessor.fit(X.T)
    serial.save(ZCA_filename+".pkl", zca_preprocessor)
开发者ID:ttblue,项目名称:human_demos,代码行数:8,代码来源:create_leveldb_utils.py


示例20: save

 def save(self, filename):
     # Delete data sets
     if (hasattr(self.experiment.binary_csp, 'cnt')):
         del self.experiment.binary_csp.cnt
     if hasattr(self.experiment, 'test_cnt'):
         del self.experiment.test_cnt
     del self.experiment.cnt
     serial.save(filename, self.experiment)
开发者ID:robintibor,项目名称:braindecode,代码行数:8,代码来源:results.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python serial.to_string函数代码示例发布时间:2022-05-25
下一篇:
Python serial.preprocess函数代码示例发布时间:2022-05-25
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap