Create a compiled Keras model.

    Parameters
    ----------
    input_shape : tuple, len=3
        Shape of each image sample.

    Returns
    -------
    model : keras.Model
        Constructed model.
514482
def build_model(input_shape):
    
    model = Sequential()

    model.add(Conv2D(32, kernel_size=(3, 3),
                     activation='relu',
                     input_shape=input_shape))
    model.add(Conv2D(64, kernel_size=(3, 3),
                     activation='relu'))
    model.add(MaxPooling2D(pool_size=(2, 2)))
    model.add(Dropout(0.25))

    model.add(Flatten())
    model.add(Dense(128, activation='relu'))
    model.add(Dropout(0.5))
    model.add(Dense(num_classes, activation='softmax'))

    model.compile(loss=keras.losses.categorical_crossentropy,
                  optimizer=keras.optimizers.Adadelta(),
                  metrics=['accuracy'])
    return model
544325
def fill_model(self, model=None):
        
        normalized_dct = self.normalize()
        if model:
            if not isinstance(model, self._model_class):
                raise ModelFormSecurityError('%s should be %s instance' % (model, self._model_class.__name__))
            model.populate(**normalized_dct)
            return model
        return self._model_class(**normalized_dct)
823299
def _build_model(self):
        

        if "input_dim" not in self.settings:
            raise ValueError("Model parameter input_dim cannot be None.")

        self.sparse_linear = SparseLinear(
            self.settings["input_dim"], self.cardinality, self.settings["bias"]
        )
876378
def model_creator(self, model_type, exact_feval, space):
        
        model_type = model_type
        exact_feval = exact_feval
        space = space

        kernel = self.kwargs.get('kernel',None)
        ARD = self.kwargs.get('ARD',False)
        verbosity_model = self.kwargs.get('verbosity_model',False)
        noise_var = self.kwargs.get('noise_var',None)
        model_optimizer_type = self.kwargs.get('model_optimizer_type','lbfgs')
        max_iters = self.kwargs.get('max_iters',1000)
        optimize_restarts = self.kwargs.get('optimize_restarts',5)

        # --------
        # --- Initialize GP model with MLE on the parameters
        # --------
        if model_type == 'GP' or model_type == 'sparseGP':
            if model_type == 'GP':
                sparse = False
            if model_type == 'sparseGP':
                sparse = True
            optimize_restarts = self.kwargs.get('optimize_restarts',5)
            num_inducing = self.kwargs.get('num_inducing',10)
            return GPModel(kernel, noise_var, exact_feval, model_optimizer_type, max_iters, optimize_restarts, sparse, num_inducing, verbosity_model, ARD)

        # --------
        # --- Initialize GP model with MCMC on the parameters
        # --------
        elif model_type == 'GP_MCMC':
            n_samples = self.kwargs.get('n_samples',10)
            n_burnin = self.kwargs.get('n_burnin',100)
            subsample_interval = self.kwargs.get('subsample_interval',10)
            step_size = self.kwargs.get('step_size',1e-1)
            leapfrog_steps = self.kwargs.get('leapfrog_steps',20)
            return GPModel_MCMC(kernel, noise_var, exact_feval, n_samples, n_burnin, subsample_interval, step_size, leapfrog_steps, verbosity_model)

        # --------
        # --- Initialize RF: values taken from default in scikit-learn
        # --------
        elif model_type =='RF':
            return RFModel(verbose=verbosity_model)

        # --------
        # --- Initialize WapedGP in the outputs
        # --------
        elif model_type =='warpedGP':
            return WarpedGPModel()

        # --------
        # --- Initialize WapedGP in the inputs
        # --------
        elif model_type == 'input_warped_GP':
            if 'input_warping_function_type' in self.kwargs:
                if self.kwargs['input_warping_function_type'] != "kumar_warping":
                    print("Only support kumar_warping for input!")

            # Only support Kumar warping now, setting it to None will use default Kumar warping
            input_warping_function = None
            optimize_restarts = self.kwargs.get('optimize_restarts',5)
            return InputWarpedGPModel(space, input_warping_function, kernel, noise_var,
                                      exact_feval, model_optimizer_type, max_iters,
                                      optimize_restarts, verbosity_model, ARD)
366659
def create(cls, h:int, w:int, bboxes:Collection[Collection[int]], labels:Collection=None, classes:dict=None,
               pad_idx:int=0, scale:bool=True)->'ImageBBox':
        ""
        if isinstance(bboxes, np.ndarray) and bboxes.dtype == np.object: bboxes = np.array([bb for bb in bboxes])
        bboxes = tensor(bboxes).float()
        tr_corners = torch.cat([bboxes[:,0][:,None], bboxes[:,3][:,None]], 1)
        bl_corners = bboxes[:,1:3].flip(1)
        bboxes = torch.cat([bboxes[:,:2], tr_corners, bl_corners, bboxes[:,2:]], 1)
        flow = FlowField((h,w), bboxes.view(-1,2))
        return cls(flow, labels=labels, classes=classes, pad_idx=pad_idx, y_first=True, scale=scale)
1069007
def _build_model(self):
        

        # Set up LSTM modules
        self.lstms = nn.ModuleList(
            [
                RNN(
                    num_classes=0,
                    num_tokens=self.word_dict.s,
                    emb_size=self.settings["emb_dim"],
                    lstm_hidden=self.settings["hidden_dim"],
                    attention=self.settings["attention"],
                    dropout=self.settings["dropout"],
                    bidirectional=self.settings["bidirectional"],
                    use_cuda=self.settings["host_device"] in self._gpu,
                )
            ]
            * self.settings["relation_arity"]
        )

        if "input_dim" not in self.settings:
            raise ValueError("Model parameter input_dim cannot be None.")

        # Set up final linear layer
        self.sparse_linear = SparseLinear(
            self.settings["input_dim"], self.cardinality, self.settings["bias"]
        )
771376
def create_cnn_model(base_arch:Callable, nc:int, cut:Union[int,Callable]=None, pretrained:bool=True,
        lin_ftrs:Optional[Collection[int]]=None, ps:Floats=0.5, custom_head:Optional[nn.Module]=None,
        split_on:Optional[SplitFuncOrIdxList]=None, bn_final:bool=False, concat_pool:bool=True):
    ""
    body = create_body(base_arch, pretrained, cut)
    if custom_head is None:
        nf = num_features_model(nn.Sequential(*body.children())) * (2 if concat_pool else 1)
        head = create_head(nf, nc, lin_ftrs, ps=ps, concat_pool=concat_pool, bn_final=bn_final)
    else: head = custom_head
    return nn.Sequential(body, head)
1135019
def instantiate(self, **extra_args):
        
        input_block = self.input_block.instantiate()
        backbone = self.backbone.instantiate(**extra_args)

        return NoisyQModel(
            input_block, backbone, extra_args['action_space'], initial_std_dev=self.initial_std_dev,
            factorized_noise=self.factorized_noise
        )
679684
def joint_shape(*args) -> tuple:
    
    if len(args) == 0:
        return ()
    shape = []
    shapes = [a.shape for a in args]
    ndim = args[0].ndim
    for i in range(ndim):
        shape.append(max([s[i] for s in shapes]))
    return tuple(shape)
308497
def _build(self, input_shape, dtype=tf.float32):
    
    with tf.variable_scope(self.name, reuse=tf.AUTO_REUSE):
      nonZeros = int(round(input_shape[-1].value * self.sparsity))

      # Create random mask with k elements set to 1, all other elements set to 0
      values = tf.random_uniform(input_shape)
      topk, _ = tf.math.top_k(input=values, k=nonZeros, sorted=False)
      kth = tf.reduce_min(topk, axis=1, keepdims=True)
      mask = tf.cast(tf.greater_equal(values, kth), dtype=dtype)
      self.mask = tf.get_variable(self.name, initializer=mask, trainable=False,
                                  synchronization=tf.VariableSynchronization.NONE)
      keras.backend.track_variable(self.mask)
      self._built = True
1353148
def create(backbone: ModelFactory, input_block: typing.Optional[ModelFactory]=None):
    
    if input_block is None:
        input_block = IdentityFactory()

    return QDuelingModelFactory(input_block=input_block, backbone=backbone)
156209
def _init_model(self):
        
        model = Sequential()
        model.add(ConvLSTM2D(filters=self.filters, kernel_size=self.kernel_size, activation=self.activation,
                             input_shape=[self.time_delay] + list(self.image_size) + [self.channels],
                             data_format='channels_last', return_sequences=True))
        model.add(BatchNormalization())
        model.add(ConvLSTM2D(filters=self.filters, kernel_size=self.kernel_size, activation=self.activation,
                             input_shape=(self.time_delay, self.channels) + self.image_size,
                             data_format='channels_last', return_sequences=True))
        model.add(BatchNormalization())
        model.add(ConvLSTM2D(filters=self.filters, kernel_size=self.kernel_size, activation=self.activation))
        model.add(BatchNormalization())
        model.add(Conv2D(filters=1, kernel_size=self.kernel_size, activation="sigmoid", data_format="channels_last"))
        model.add(Flatten())
        model.add(Dense(units=len(self.emotion_map.keys()), activation="sigmoid"))
        if self.verbose:
            model.summary()
        self.model = model
591925
def build_model(self, n_features, regtype='none'):
        
        self._create_placeholders(n_features)
        self._create_variables(n_features)
        self.encode = self.sample_hidden_from_visible(self.input_data)[0]
        self.reconstruction = self.sample_visible_from_hidden(
            self.encode, n_features)

        hprob0, hstate0, vprob, hprob1, hstate1 = self.gibbs_sampling_step(
            self.input_data, n_features)
        positive = self.compute_positive_association(self.input_data,
                                                     hprob0, hstate0)

        nn_input = vprob

        for step in range(self.gibbs_sampling_steps - 1):
            hprob, hstate, vprob, hprob1, hstate1 = self.gibbs_sampling_step(
                nn_input, n_features)
            nn_input = vprob

        negative = tf.matmul(tf.transpose(vprob), hprob1)

        self.w_upd8 = self.W.assign_add(
            self.learning_rate * (positive - negative) / self.batch_size)

        self.bh_upd8 = self.bh_.assign_add(tf.multiply(self.learning_rate, tf.reduce_mean(
            tf.subtract(hprob0, hprob1), 0)))

        self.bv_upd8 = self.bv_.assign_add(tf.multiply(self.learning_rate, tf.reduce_mean(
            tf.subtract(self.input_data, vprob), 0)))

        variables = [self.W, self.bh_, self.bv_]
        regterm = Layers.regularization(variables, self.regtype, self.regcoef)

        self.cost = self.loss.compile(vprob, self.input_data, regterm=regterm)
1166825
def from_shapefile(output, input_shp_files, validate):
    
    input_parser = shapefileparser.ShapefileParser()
    source_model = input_parser.read(input_shp_files[0], validate)
    for f in input_shp_files[1:]:
        source_model.sources.extend(input_parser.read(f, validate).sources)
    if not output:
        output = os.path.splitext(input_shp_files[0])[0]
    shapefileparser.SourceModelParser().write(output + '.xml', source_model)
119926
def _chunked_selector_output_shape(  # pylint: disable=invalid-name
    input_shapes, selector=None, **unused_kwargs):
  """"""
  # Read the main function below first, the shape logic just follows the ops.
  selector = selector or (lambda x: [] if x < 1 else [x-1])
  triples, _ = zip(*input_shapes)
  (query_shapes, key_shapes, value_shapes) = zip(*triples)
  result = []
  for i in range(len(input_shapes)):
    selected = selector(i)
    cur_key_shape, cur_value_shape = key_shapes[i], value_shapes[i]
    # Since keys and values are [batch, length, depth] we concatenate on axis=1.
    new_key_len = sum([key_shapes[j][1] for j in selected]) + cur_key_shape[1]
    new_key_shape = (cur_key_shape[0], new_key_len, cur_key_shape[2])
    new_value_len = sum(
        [value_shapes[j][1] for j in selected]) + cur_value_shape[1]
    new_value_shape = (cur_value_shape[0], new_value_len, cur_value_shape[2])
    # Masks are (1, query-len, key-len).
    new_mask_shape = (1, query_shapes[i][1], new_key_len)
    new_shape = ((query_shapes[i], new_key_shape, new_value_shape),
                 new_mask_shape)
    result.append(new_shape)
  return tuple(result)
344833
def create_model(model_name: Optional[str], params: ModelParams) -> 'Sequential':
    
    if model_name and isfile(model_name):
        print('Loading from ' + model_name + '...')
        model = load_precise_model(model_name)
    else:
        from keras.layers.core import Dense
        from keras.layers.recurrent import GRU
        from keras.models import Sequential

        model = Sequential()
        model.add(GRU(
            params.recurrent_units, activation='linear',
            input_shape=(pr.n_features, pr.feature_size), dropout=params.dropout, name='net'
        ))
        model.add(Dense(1, activation='sigmoid'))

    load_keras()
    metrics = ['accuracy'] + params.extra_metrics * [false_pos, false_neg]
    set_loss_bias(params.loss_bias)
    for i in model.layers[:params.freeze_till]:
        i.trainable = False
    model.compile('rmsprop', weighted_log_loss, metrics=(not params.skip_acc) * metrics)
    return model
560578
def nested_shape(array_or_tuple):
    
    if hasattr(array_or_tuple, 'size'):
        # pytorch tensors use V.size() to get size of tensor
        return list(array_or_tuple.size())
    elif hasattr(array_or_tuple, 'get_shape'):
        # tensorflow uses V.get_shape() to get size of tensor
        return array_or_tuple.get_shape().as_list()
    elif hasattr(array_or_tuple, 'shape'):
        return array_or_tuple.shape

    try:
        # treat object as iterable
        return [nested_shape(item) for item in list(array_or_tuple)]
    except TypeError:
        # object is not actually iterable
        # LB: Maybe we should throw an error?
        return []