Example with `morphological_chan_vese` with using the default
    initialization of the level-set.
321748
def example_camera():
    
    
    logging.info('Running: example_camera (MorphACWE)...')

    # Load the image.
    img = imread(PATH_IMG_CAMERA)/255.0

    # Callback for visual plotting
    callback = visual_callback_2d(img)

    # Morphological Chan-Vese (or ACWE)
    ms.morphological_chan_vese(img, 35,
                               smoothing=3, lambda1=1, lambda2=1,
                               iter_callback=callback)
726051
def _create_variables_no_pretrain(self, n_features):
        
        self.encoding_w_ = []
        self.encoding_b_ = []

        for l, layer in enumerate(self.layers):

            if l == 0:
                self.encoding_w_.append(tf.Variable(tf.truncated_normal(
                    shape=[n_features, self.layers[l]], stddev=0.1)))
                self.encoding_b_.append(tf.Variable(tf.truncated_normal(
                    [self.layers[l]], stddev=0.1)))
            else:
                self.encoding_w_.append(tf.Variable(tf.truncated_normal(
                    shape=[self.layers[l - 1], self.layers[l]], stddev=0.1)))
                self.encoding_b_.append(tf.Variable(tf.truncated_normal(
                    [self.layers[l]], stddev=0.1)))
8975
def RandomNormalInitializer(stddev=1e-2):
  """"""
  def init(shape, rng):
    return (stddev * backend.random.normal(rng, shape)).astype('float32')
  return init
1196103
def init_default(m:nn.Module, func:LayerFunc=nn.init.kaiming_normal_)->None:
    ""
    if func:
        if hasattr(m, 'weight'): func(m.weight)
        if hasattr(m, 'bias') and hasattr(m.bias, 'data'): m.bias.data.fill_(0.)
    return m
775106
def make_fc(dim_in, hidden_dim, use_gn=False):
    '''
        
    '''
    if use_gn:
        fc = nn.Linear(dim_in, hidden_dim, bias=False)
        nn.init.kaiming_uniform_(fc.weight, a=1)
        return nn.Sequential(fc, group_norm(hidden_dim))
    fc = nn.Linear(dim_in, hidden_dim)
    nn.init.kaiming_uniform_(fc.weight, a=1)
    nn.init.constant_(fc.bias, 0)
    return fc
105927
def initialize_vml_shape
      pos = Axlsx::name_to_indices(ref)
      @vml_shape = VmlShape.new(:row => pos[1], :column => pos[0], :visible => @visible) do |vml|
        vml.left_column = vml.column
        vml.right_column = vml.column + 2 
        vml.top_row = vml.row
         vml.bottom_row = vml.row + 4
      end
    end
863976
private static function _initialize() 
    {
        for ($i=self::SINGULAR; $i <= self::IRREGULAR; $i++) {
            if (!array_key_exists($i, self::$_inflections)) {
                self::$_inflections[$i] = array();
            }
        }
    }
1123446
def _init_norm(self, weights):
    """"""
    with tf.variable_scope("init_norm"):
      flat = tf.reshape(weights, [-1, self.layer_depth])
      return tf.reshape(tf.norm(flat, axis=0), (self.layer_depth,))
728476
def normalize_example(self, example, hparams):
    """"""

    length = self.max_length(hparams)
    def _to_constant_shape(tensor):
      tensor = tensor[:length]
      tensor = tf.pad(tensor, [(0, length - tf.shape(tensor)[0])])
      return tf.reshape(tensor, [length])

    if self.has_inputs:
      example['inputs'] = _to_constant_shape(example['inputs'])
      example['targets'] = _to_constant_shape(example['targets'])
    elif 'inputs' in example:
      if self.packed_length:
        raise ValueError('cannot concatenate packed examples on the fly.')
      inputs = example.pop('inputs')[:-1]  # Remove EOS token.
      targets = tf.concat([inputs, example['targets']], 0)
      example['targets'] = _to_constant_shape(targets)
    else:
      example['targets'] = _to_constant_shape(example['targets'])
    if self.packed_length:
      if self.has_inputs:
        if 'inputs_segmentation' in example:
          example['inputs_segmentation'] = _to_constant_shape(
              example['inputs_segmentation'])
          example['inputs_position'] = _to_constant_shape(
              example['inputs_position'])
        else:
          example['inputs_segmentation'] = tf.to_int64(
              tf.not_equal(example['inputs'], 0))
          example['inputs_position'] = (
              example['inputs_segmentation'] * tf.range(length, dtype=tf.int64))
      if 'targets_segmentation' in example:
        example['targets_segmentation'] = _to_constant_shape(
            example['targets_segmentation'])
        example['targets_position'] = _to_constant_shape(
            example['targets_position'])
      else:
        example['targets_segmentation'] = tf.to_int64(
            tf.not_equal(example['targets'], 0))
        example['targets_position'] = (
            example['targets_segmentation'] * tf.range(length, dtype=tf.int64))
    return example
1299321
def _create_gate_variables(self, input_shape, dtype):
    """"""
    if len(input_shape) != 2:
      raise ValueError(
          "Rank of shape must be {} not: {}".format(2, len(input_shape)))

    equiv_input_size = self._hidden_state_size + input_shape.dims[1].value
    initializer = basic.create_linear_initializer(equiv_input_size)

    self._w_xh = tf.get_variable(
        self.W_GATES,
        shape=[equiv_input_size, 4 * self._hidden_size],
        dtype=dtype,
        initializer=self._initializers.get(self.W_GATES, initializer),
        partitioner=self._partitioners.get(self.W_GATES),
        regularizer=self._regularizers.get(self.W_GATES))
    self._b = tf.get_variable(
        self.B_GATES,
        shape=[4 * self._hidden_size],
        dtype=dtype,
        initializer=self._initializers.get(self.B_GATES, initializer),
        partitioner=self._partitioners.get(self.B_GATES),
        regularizer=self._regularizers.get(self.B_GATES))
    if self._use_projection:
      w_h_initializer = basic.create_linear_initializer(self._hidden_size)
      self._w_h_projection = tf.get_variable(
          self.W_H_PROJECTION,
          shape=[self._hidden_size, self._hidden_state_size],
          dtype=dtype,
          initializer=self._initializers.get(self.W_H_PROJECTION,
                                             w_h_initializer),
          partitioner=self._partitioners.get(self.W_H_PROJECTION),
          regularizer=self._regularizers.get(self.W_H_PROJECTION))
222282
private static Properties _newInitedProp(String templateDir, String charset) {
		final Properties properties = new Properties();

		properties.setProperty(Velocity.FILE_RESOURCE_LOADER_PATH, templateDir);
		properties.setProperty(Velocity.ENCODING_DEFAULT, charset);
		properties.setProperty(Velocity.INPUT_ENCODING, charset);
		// properties.setProperty(Velocity.OUTPUT_ENCODING, charset);

		return properties;
	}
147213
def _create_initstate_and_embeddings(self):
        """"""
        self._init_state = self.cell.zero_state(self.batch_size, tf.float32)
        embedding = tf.get_variable(
            "embedding", [self.vocab_size, self.num_hidden])
        inputs = tf.nn.embedding_lookup(embedding, self.input_data)
        self.inputs = tf.nn.dropout(inputs, self.dropout)
595295
def morphemes(args):
  """"""
  morfessor = load_morfessor_model(lang=args.lang)
  for l in args.input:
    words = l.strip().split()
    morphemes = [(w, u"_".join(morfessor.viterbi_segment(w)[0])) for w in words]
    line_annotations = [u"{:<16}{:<5}".format(w,p) for w, p in morphemes]
    _print(u"\n".join(line_annotations))
    _print(u"")
747770
def initialize(self):
    
    if self._pooler is None:
      params = {
        "inputWidth": self.inputWidth,
        "lateralInputWidths": [self.cellCount] * self.numOtherCorticalColumns,
        "cellCount": self.cellCount,
        "sdrSize": self.sdrSize,
        "onlineLearning": self.onlineLearning,
        "maxSdrSize": self.maxSdrSize,
        "minSdrSize": self.minSdrSize,
        "synPermProximalInc": self.synPermProximalInc,
        "synPermProximalDec": self.synPermProximalDec,
        "initialProximalPermanence": self.initialProximalPermanence,
        "minThresholdProximal": self.minThresholdProximal,
        "sampleSizeProximal": self.sampleSizeProximal,
        "connectedPermanenceProximal": self.connectedPermanenceProximal,
        "predictedInhibitionThreshold": self.predictedInhibitionThreshold,
        "synPermDistalInc": self.synPermDistalInc,
        "synPermDistalDec": self.synPermDistalDec,
        "initialDistalPermanence": self.initialDistalPermanence,
        "activationThresholdDistal": self.activationThresholdDistal,
        "sampleSizeDistal": self.sampleSizeDistal,
        "connectedPermanenceDistal": self.connectedPermanenceDistal,
        "inertiaFactor": self.inertiaFactor,
        "seed": self.seed,
      }
      self._pooler = ColumnPooler(**params)
1077354
def initialize(
        self, config_file: str = "bmi_config.txt", initialize_indicators=True
    ):
        
        self.t = 0.0
        if not os.path.isfile(config_file):
            self.create_bmi_config_file(config_file)

        self.s0 = [
            pd.read_csv(
                config_file, index_col=0, header=None, error_bad_lines=False
            )[1]
            for _ in range(self.res)
        ]
        self.s0_original = self.s0[0].copy(deep=True)

        self.latent_state_vector = self.construct_default_initial_state()

        for n in self.nodes(data=True):
            rv = LatentVar(n[0])
            n[1]["rv"] = rv
            n[1]["update_function"] = self.default_update_function
            rv.dataset = [1.0 for _ in range(self.res)]
            rv.partial_t = self.s0[0][f"∂({n[0]})/∂t"]
            if initialize_indicators:
                for indicator in n[1]["indicators"].values():
                    indicator.samples = np.random.normal(
                        indicator.mean * np.array(n[1]["rv"].dataset),
                        scale=0.01,
                    )
317246
def _initialize(self):
        
        self._graph = tf.Graph()
        with self._graph.as_default():
            self._input_node = tf.placeholder(tf.float32, (self._batch_size, self._im_height, self._im_width, self._num_channels))
            weights = self.build_alexnet_weights()
            self._output_tensor = self.build_alexnet(weights)
            self._feature_tensor = self.build_alexnet(weights, output_layer=self._feature_layer)
            self._initialized = True
419406
def step(self):
        """"""
        # Assign attributes to local variables for convenience.
        u = self._u
        gI = self._data
        dgI = self._ddata
        theta = self._theta
        v = self._v
        
        if u is None:
            raise ValueError("the levelset is not set (use set_levelset)")
        
        res = np.copy(u)
        
        # Balloon.
        if v > 0:
            aux = binary_dilation(u, self.structure)
        elif v < 0:
            aux = binary_erosion(u, self.structure)
        if v!= 0:
            res[self._threshold_mask_v] = aux[self._threshold_mask_v]
        
        # Image attachment.
        aux = np.zeros_like(res)
        dres = np.gradient(res)
        for el1, el2 in zip(dgI, dres):
            aux += el1*el2
        res[aux > 0] = 1
        res[aux < 0] = 0
        
        # Smoothing.
        for i in range(self.smoothing):
            res = curvop(res)
        
        self._u = res