Creates the weights for the jackknife method. See func: teneto.derive.derive.
15097
def _weightfun_jackknife(T, report):
    

    weights = np.ones([T, T])
    np.fill_diagonal(weights, 0)
    report['method'] = 'jackknife'
    report['jackknife'] = ''
    return weights, report
247509
def create_method(self):
        
        n_indents = 0 if self.target_language in ['c', 'go'] else 1
        method_type = 'separated.{}.method'.format(self.prefix)
        method_temp = self.temp(method_type, n_indents=n_indents,
                                skipping=True)
        return method_temp.format(**self.__dict__)
279568
def _trees_feature_weights(clf, X, feature_names, num_targets):
    
    feature_weights = np.zeros([len(feature_names), num_targets])
    if hasattr(clf, 'tree_'):
        _update_tree_feature_weights(X, feature_names, clf, feature_weights)
    else:
        if isinstance(clf, (
                GradientBoostingClassifier, GradientBoostingRegressor)):
            weight = clf.learning_rate
        else:
            weight = 1. / len(clf.estimators_)
        for _clfs in clf.estimators_:
            _update = partial(_update_tree_feature_weights, X, feature_names)
            if isinstance(_clfs, np.ndarray):
                if len(_clfs) == 1:
                    _update(_clfs[0], feature_weights)
                else:
                    for idx, _clf in enumerate(_clfs):
                        _update(_clf, feature_weights[:, idx])
            else:
                _update(_clfs, feature_weights)
        feature_weights *= weight
        if hasattr(clf, 'init_'):
            feature_weights[feature_names.bias_idx] += clf.init_.predict(X)[0]
    return feature_weights
1066614
def create(input_length, hidden_layers, activation='tanh', normalization=None):
    
    def instantiate(**_):
        return MLP(
            input_length=input_length,
            hidden_layers=hidden_layers,
            activation=activation,
            normalization=normalization
        )

    return ModelFactory.generic(instantiate)
537294
def create_uni_method(op_name, klass, jacobians=None):
    
    # This function will become the actual method.
    op_modules = [operator, builtins]
    op_names = [op_name, op_name + '_']

    op_function_base = find_element(op_names, op_modules, error_on_fail=True)
    # many such functions do not take keyword arguments, so we need to wrap
    # them

    def op_function(self):
        return op_function_base(self)

    def new_method(self):
        # This code creates a Deterministic object.
        if not check_special_methods():
            raise NotImplementedError(
                'Special method %s called on %s, but special methods have been disabled. Set pymc.special_methods_available to True to enable them.' %
                (op_name, str(self)))

        jacobian_formats = {'self': 'transformation_operation'}
        return pm.Deterministic(op_function,
                                'A Deterministic returning the value of %s(%s)' % (
                                    op_name, self.__name__),
                                '(' + op_name + '_' + self.__name__ + ')',
                                parents={'self': self},
                                trace=False,
                                plot=False,
                                jacobians=jacobians,
                                jacobian_formats=jacobian_formats)
    # Make the function into a method for klass.

    new_method.__name__ = '__' + op_name + '__'
    setattr(
        klass,
        new_method.__name__,
        UnboundMethodType(
            new_method,
            None,
            klass))
15277
protected static <T> double initialWeights(WritableDoubleDataStore weights, Relation<? extends T> relation, DBIDs ids, T first, T second, DistanceQuery<? super T> distQ) {
    double weightsum = 0.;
    for(DBIDIter it = ids.iter(); it.valid(); it.advance()) {
      // distance will usually already be squared
      T v = relation.get(it);
      double weight = Math.min(distQ.distance(first, v), distQ.distance(second, v));
      weights.putDouble(it, weight);
      weightsum += weight;
    }
    return weightsum;
  }
496755
public static <S extends Solution<?>> void weightedProduct(List<S> solutionsList, double[] weights) {
    for (S solution : solutionsList) {
      double product = Math.pow(solution.getObjective(0), weights[0]);
      for (int i = 1; i < solution.getNumberOfObjectives(); i++) {
        product *= Math.pow(solution.getObjective(i), weights[i]);
      }
      setScalarizationValue(solution, product);
    }
  }
727677
def add(self, delta):
        
        if self.lw is None:
            return Weights(lw=delta)
        else:
            return Weights(lw=self.lw + delta)
1100938
def create_embedded_meth(self):
        
        # Generate related trees:
        fns = []
        for idx, estimator in enumerate(self.estimators):
            tree = self.create_single_method(idx, estimator)
            fns.append(tree)
        fns = '\n'.join(fns)

        # Generate method or function names:
        fn_names = ''
        if self.target_language in ['c', 'java']:
            fn_names = []
            temp_method_calls = self.temp('embedded.method_calls', n_indents=2,
                                          skipping=True)
            for idx, estimator in enumerate(self.estimators):
                cl_name = self.class_name
                fn_name = self.method_name + '_' + str(idx)
                fn_name = temp_method_calls.format(class_name=cl_name,
                                                   method_name=fn_name,
                                                   method_index=idx)
                fn_names.append(fn_name)
            fn_names = '\n'.join(fn_names)
            fn_names = self.indent(fn_names, n_indents=1, skipping=True)

        # Merge generated content:
        n_indents = 1 if self.target_language in ['java', 'js'] else 0
        temp_method = self.temp('embedded.method')
        method = temp_method.format(method_name=self.method_name,
                                    class_name=self.class_name,
                                    method_calls=fn_names, methods=fns,
                                    n_estimators=self.n_estimators,
                                    n_classes=self.n_classes)
        return self.indent(method, n_indents=n_indents, skipping=True)
347887
def set_weights_by_dict(self,weights):
    
    self._weights = []
    txnames = [x.name for x in self._transcriptome.transcripts]
    for txname in txnames:
      if txname in weights:
        self._weights.append(float(weights[txname]))
      else:
        self._weights.append(float(0))
    return
320117
def create_weight_initializer(fan_in_shape, dtype=tf.float32):
  """"""
  stddev = 1 / math.sqrt(np.prod(fan_in_shape))
  return tf.truncated_normal_initializer(stddev=stddev, dtype=dtype)
137230
function( weightFn ){
      weightFn = $$.is.fn(weightFn) ? weightFn : function(){ return 1; }; // if not specified, assume each edge has equal weight (1)

      function findSet(ele){
        for( var i = 0; i < forest.length; i++ ){
          var eles = forest[i];

          if( eles.anySame(ele) ){
            return {
              eles: eles,
              index: i
            };
          }
        }
      }

      var A = new $$.Collection(this._private.cy, []);
      var forest = [];
      var nodes = this.nodes();

      for( var i = 0; i < nodes.length; i++ ){
        forest.push( nodes[i].collection() );
      }

      var edges = this.edges();
      var S = edges.toArray().sort(function(a, b){
        var weightA = weightFn.call(a);
        var weightB = weightFn.call(b);

        return weightA - weightB;
      });

      for(var i = 0; i < S.length; i++){
        var edge = S[i];
        var u = edge.source()[0];
        var v = edge.target()[0];
        var setU = findSet(u);
        var setV = findSet(v);

        if( setU.index !== setV.index ){
          A = A.add( edge );

          // combine forests for u and v
          forest[ setU.index ] = setU.eles.add( setV.eles );
          forest.splice( setV.index, 1 );
        }
      }

      return nodes.add( A );

    }
403923
def create(entropy_coefficient, value_coefficient, max_grad_norm, discount_factor, gae_lambda=1.0):
    
    return A2CPolicyGradient(
        entropy_coefficient,
        value_coefficient,
        max_grad_norm,
        discount_factor,
        gae_lambda
    )
1025432
def create(model: ModelFactory, discount_factor: float, target_update_frequency: int,
           max_grad_norm: float, double_dqn: bool = False):
    
    return DistributionalDeepQLearning(
        model_factory=model,
        discount_factor=discount_factor,
        double_dqn=double_dqn,
        target_update_frequency=target_update_frequency,
        max_grad_norm=max_grad_norm
    )
627523
public static double[][] initializeUniformlyInTwoDimensions(double epsilon, int numberOfWeights) {
		double[][] weights = new double[numberOfWeights][2];
		
		int indexOfWeight;
		double w, jump;
		
		jump = (1 - (2 * epsilon)) / (numberOfWeights - 1);
		indexOfWeight = 0;
		
		w = epsilon;
		
		//while(w <= (1-epsilon))
		while (indexOfWeight < numberOfWeights) {
			weights[indexOfWeight][0] = w;
			weights[indexOfWeight][1] = 1 - w;
			
			w = w + jump;
			
			indexOfWeight = indexOfWeight + 1;
		}
		
		return weights;
	}
1045784
def create(lr, alpha, momentum=0, weight_decay=0, epsilon=1e-8):
    
    return RMSpropTFFactory(lr=lr, alpha=alpha, momentum=momentum, weight_decay=weight_decay, eps=float(epsilon))
1186429
def make_weights_for_balanced_classes(self):
    """"""

    nclasses = len(self.classes)
    count = np.ones(nclasses)
    for item in self.data:
      count[item[1]] += 1

    N = float(sum(count))
    weight_per_class = N / count
    weight = np.zeros(len(self.data))
    for idx, item in enumerate(self.data):
      weight[idx] = weight_per_class[item[1]]
    return weight