Get model for pre-training.
190929
def get_model_loss(ctx, model, pretrained, dataset_name, dtype, ckpt_dir=None, start_step=None):
    """"""
    # model
    model, vocabulary = nlp.model.get_model(model,
                                            dataset_name=dataset_name,
                                            pretrained=pretrained, ctx=ctx)

    if not pretrained:
        model.initialize(init=mx.init.Normal(0.02), ctx=ctx)
    model.cast(dtype)

    if ckpt_dir and start_step:
        param_path = os.path.join(ckpt_dir, '%07d.params'%start_step)
        model.load_parameters(param_path, ctx=ctx)
        logging.info('Loading step %d checkpoints from %s.', start_step, param_path)

    model.hybridize(static_alloc=True)

    # losses
    nsp_loss = mx.gluon.loss.SoftmaxCELoss()
    mlm_loss = mx.gluon.loss.SoftmaxCELoss()
    nsp_loss.hybridize(static_alloc=True)
    mlm_loss.hybridize(static_alloc=True)

    return model, nsp_loss, mlm_loss, vocabulary
1111737
def _get_sampleset(model):
    """"""
    if isinstance(model, Model):
        if hasattr(model, 'sampleset'):
            w = model.sampleset()
        else:
            w = None
    else:
        w = model  # Already a sampleset
    return w
380620
def model(self):
        """"""
        try:
            return self.data.get('identity').get('model_name')
        except (KeyError, AttributeError):
            return self.device_status_simple('')
1064019
def _get_model_instance(model_cls, data):
        
        if not isinstance(data, (model_cls, dict)):
            raise TypeError('{0} is not valid type, instance of '
                            '{1} or dict required'.format(data, model_cls))
        return model_cls(**data) if isinstance(data, dict) else data
1273604
def pre_save(self, model_instance, add):
        """"""
        value = socket.gethostname()
        setattr(model_instance, self.attname, value)
        return value
1325467
def _find_model(self, constructor, table_name, constraints=None, *, columns=None, order_by=None):
    """"""
    data = self.find(table_name, constraints, columns=columns, order_by=order_by)
    return constructor(data) if data else None
831081
def get_model(PARAMS):
    ''''''
    model_dict = {
        'LinearRegression': LinearRegression(),
        'SVR': SVR(),
        'KNeighborsRegressor': KNeighborsRegressor(),
        'DecisionTreeRegressor': DecisionTreeRegressor()
    }
    if not model_dict.get(PARAMS['model_name']):
        LOG.exception('Not supported model!')
        exit(1)
    
    model = model_dict[PARAMS['model_name']]
    
    try:
        if PARAMS['model_name'] == 'SVR':
            model.kernel = PARAMS['svr_kernel']
        elif PARAMS['model_name'] == 'KNeighborsRegressor':
            model.weights = PARAMS['knr_weights']
    except Exception as exception:
        LOG.exception(exception)
        raise
    return model
1115657
def vgg11(num_classes=1000, pretrained='imagenet'):
    
    model = models.vgg11(pretrained=False)
    if pretrained is not None:
        settings = pretrained_settings['vgg11'][pretrained]
        model = load_pretrained(model, num_classes, settings)
    model = modify_vggs(model)
    return model
1150054
def get_for_model(self, model):
        
        return self.get_or_create(
            content_type    = ContentType.objects.get_for_model(model),
            object_id       = model.pk
        )
62258
def _load_model(self):
        """"""
        super()._load_model()
        self.mujoco_robot = Baxter()
        if self.has_gripper_right:
            self.gripper_right = gripper_factory(self.gripper_right_name)
            if not self.gripper_visualization:
                self.gripper_right.hide_visualization()
            self.mujoco_robot.add_gripper("right_hand", self.gripper_right)

        if self.has_gripper_left:
            self.gripper_left = gripper_factory(self.gripper_left_name)
            if not self.gripper_visualization:
                self.gripper_left.hide_visualization()
            self.mujoco_robot.add_gripper("left_hand", self.gripper_left)
712308
def get(self, *args, **kwargs):
        """"""
        assert not args
        assert list(kwargs.keys()) == ['pk']
        pk = kwargs['pk']
        model_name = self.model.__name__
        object_spec = (model_name, pk, None)
        instances = self.cache.get_instances((object_spec,))
        try:
            model_data = instances[(model_name, pk)][0]
        except KeyError:
            raise self.model.DoesNotExist(
                "No match for %r with args %r, kwargs %r" %
                (self.model, args, kwargs))
        else:
            return CachedModel(self.model, model_data)
1243678
def attached_to_model(self):
        """"""
        try:
            if not bool(self._model):
                return False
        except AttributeError:
            return False
        else:
            try:
                return not bool(self._instance)
            except AttributeError:
                return True
1207658
def language_model_learner(data:DataBunch, arch, config:dict=None, drop_mult:float=1., pretrained:bool=True,
                           pretrained_fnames:OptStrTuple=None, **learn_kwargs) -> 'LanguageLearner':
    ""
    model = get_language_model(arch, len(data.vocab.itos), config=config, drop_mult=drop_mult)
    meta = _model_meta[arch]
    learn = LanguageLearner(data, model, split_func=meta['split_lm'], **learn_kwargs)
    if pretrained:
        if 'url' not in meta: 
            warn("There are no pretrained weights for that architecture yet!")
            return learn
        model_path = untar_data(meta['url'], data=False)
        fnames = [list(model_path.glob(f'*.{ext}'))[0] for ext in ['pth', 'pkl']]
        learn.load_pretrained(*fnames)
        learn.freeze()
    if pretrained_fnames is not None:
        fnames = [learn.path/learn.model_dir/f'{fn}.{ext}' for fn,ext in zip(pretrained_fnames, ['pth', 'pkl'])]
        learn.load_pretrained(*fnames)
        learn.freeze()
    return learn
416673
def load_precise_model(model_name: str) -> Any:
    """"""
    if not model_name.endswith('.net'):
        print('Warning: Unknown model type, ', model_name)

    inject_params(model_name)
    return load_keras().models.load_model(model_name)
915673
def _build_model(self):
        """"""

        with tf.variable_scope("init"):
            x = self._conv("init_conv", self._images, 3, 3, 16,
                           self._stride_arr(1))

        strides = [1, 2, 2]
        activate_before_residual = [True, False, False]
        if self.hps.use_bottleneck:
            res_func = self._bottleneck_residual
            filters = [16, 64, 128, 256]
        else:
            res_func = self._residual
            filters = [16, 16, 32, 64]

        with tf.variable_scope("unit_1_0"):
            x = res_func(x, filters[0], filters[1], self._stride_arr(
                strides[0]), activate_before_residual[0])
        for i in range(1, self.hps.num_residual_units):
            with tf.variable_scope("unit_1_%d" % i):
                x = res_func(x, filters[1], filters[1], self._stride_arr(1),
                             False)

        with tf.variable_scope("unit_2_0"):
            x = res_func(x, filters[1], filters[2], self._stride_arr(
                strides[1]), activate_before_residual[1])
        for i in range(1, self.hps.num_residual_units):
            with tf.variable_scope("unit_2_%d" % i):
                x = res_func(x, filters[2], filters[2], self._stride_arr(1),
                             False)

        with tf.variable_scope("unit_3_0"):
            x = res_func(x, filters[2], filters[3], self._stride_arr(
                strides[2]), activate_before_residual[2])
        for i in range(1, self.hps.num_residual_units):
            with tf.variable_scope("unit_3_%d" % i):
                x = res_func(x, filters[3], filters[3], self._stride_arr(1),
                             False)
        with tf.variable_scope("unit_last"):
            x = self._batch_norm("final_bn", x)
            x = self._relu(x, self.hps.relu_leakiness)
            x = self._global_avg_pool(x)

        with tf.variable_scope("logit"):
            logits = self._fully_connected(x, self.hps.num_classes)
            self.predictions = tf.nn.softmax(logits)

        with tf.variable_scope("costs"):
            xent = tf.nn.softmax_cross_entropy_with_logits(
                logits=logits, labels=self.labels)
            self.cost = tf.reduce_mean(xent, name="xent")
            self.cost += self._decay()

            if self.mode == "eval":
                tf.summary.scalar("cost", self.cost)
971464
def get_model(self, entity_cls):
        """"""
        entity_record = self._get_entity_by_class(entity_cls)

        model_cls = None
        if entity_record.model_cls:
            model_cls = entity_record.model_cls
        else:
            # We should ask the Provider to give a fully baked model the first time
            #   that has been initialized properly for this entity
            provider = self.get_provider(entity_record.provider_name)
            baked_model_cls = provider.get_model(entity_record.entity_cls)

            # Record for future reference
            new_entity_record = entity_record._replace(model_cls=baked_model_cls)
            self._registry[entity_record.qualname] = new_entity_record

            model_cls = baked_model_cls

        return model_cls
1007254
def _get_model(vehicle):
    """"""
    model = vehicle['model']
    model = model.replace(vehicle['year'], '')
    model = model.replace(vehicle['make'], '')
    return model.strip().split(' ')[0]