Computes the weights for the scaled unscented Kalman filter.
961481
def _compute_weights(self):
        

        n = self.n
        lambda_ = self.alpha**2 * (n +self.kappa) - n

        c = .5 / (n + lambda_)
        self.Wc = np.full(2*n + 1, c)
        self.Wm = np.full(2*n + 1, c)
        self.Wc[0] = lambda_ / (n + lambda_) + (1 - self.alpha**2 + self.beta)
        self.Wm[0] = lambda_ / (n + lambda_)
29523
def returnMatches(kw, kv, n, theta, inputScaling=1.0):
  
  # How many weight vectors and input vectors to generate at a time
  m1 = 4
  m2 = 1000

  weights = getSparseTensor(kw, n, m1, fixedRange=1.0 / kw)

  # Initialize random input vectors using given scaling and see how many match
  inputVectors = getSparseTensor(kv, n, m2,
                                 onlyPositive=True,
                                 fixedRange= 2*inputScaling / kw,
                                 )
  dot = inputVectors.matmul(weights.t())
  numMatches = ((dot >= theta).sum()).item()
  pctMatches = numMatches / float(m1*m2)

  return pctMatches, numMatches, m1*m2
168750
protected void maximization() {
		// discard previous parameters by zeroing
		for (int i = 0; i < mixture.size; i++) {
			mixture.get(i).zero();
		}

		// compute the new mean
		for (int i = 0; i < info.size; i++) {
			PointInfo p = info.get(i);

			for (int j = 0; j < mixture.size; j++) {
				mixture.get(j).addMean(p.point,p.weights.get(j));
			}
		}
		for (int i = 0; i < mixture.size; i++) {
			GaussianGmm_F64 g = mixture.get(i);
			if( g.weight > 0 )
				CommonOps_DDRM.divide(g.mean,g.weight);
		}

		// compute new covariance
		for (int i = 0; i < info.size; i++) {
			PointInfo pp = info.get(i);
			double[] p = pp.point;

			for (int j = 0; j < mixture.size; j++) {
				GaussianGmm_F64 g = mixture.get(j);

				for (int k = 0; k < p.length; k++) {
					dx[k] = p[k]-g.mean.data[k];
				}

				mixture.get(j).addCovariance(dx, pp.weights.get(j));
			}
		}
		double totalMixtureWeight = 0;
		for (int i = 0; i < mixture.size; i++) {
			GaussianGmm_F64 g = mixture.get(i);
			if( g.weight > 0 ) {
				CommonOps_DDRM.divide(g.covariance, g.weight);
				totalMixtureWeight += g.weight;
			}
		}

		// update the weight
		for (int i = 0; i < mixture.size; i++) {
			mixture.get(i).weight /= totalMixtureWeight;
		}
	}
1306743
private void calculateFeatureWeights(Dataframe trainingData) {
        ModelParameters modelParameters = knowledgeBase.getModelParameters();
        TrainingParameters trainingParameters = knowledgeBase.getTrainingParameters();
        Map<Object, TypeInference.DataType> columnTypes = trainingData.getXDataTypes();
        
        Map<Object, Double> featureWeights = modelParameters.getFeatureWeights();
        
        if(trainingParameters.isWeighted()==false) {
            //the unweighted version of the algorithm
            double gammaWeight = trainingParameters.getCategoricalGamaMultiplier();
            streamExecutor.forEach(StreamMethods.stream(columnTypes.entrySet().stream(), isParallelized()), e -> {
                //standard kmeans has equal weights in all numeric features
                //for categorical, dummy or ordinal feature, use the Gamma Multiplier of Kprototypes
                double weight = (e.getValue()!=TypeInference.DataType.NUMERICAL)?gammaWeight:1.0;
                featureWeights.put(e.getKey(), weight);
            });
        }
        else {
            //calculate weights for the features
            
            int n = trainingData.size();
            
            StorageEngine storageEngine = knowledgeBase.getStorageEngine();
            
            Map<Object, Double> tmp_categoricalFrequencies = storageEngine.getBigMap("tmp_categoricalFrequencies", Object.class, Double.class, MapType.HASHMAP, StorageHint.IN_MEMORY, true, true);
            Map<Object, Double> tmp_varianceSumX = storageEngine.getBigMap("tmp_varianceSumX", Object.class, Double.class, MapType.HASHMAP, StorageHint.IN_MEMORY, true, true);
            Map<Object, Double> tmp_varianceSumXsquare = storageEngine.getBigMap("tmp_varianceSumXsquare", Object.class, Double.class, MapType.HASHMAP, StorageHint.IN_MEMORY, true, true);
        
            //calculate variance and frequencies
            for(Record r : trainingData) { 
                for(Map.Entry<Object, Object> e : r.getX().entrySet()) {
                    Double value = TypeInference.toDouble(e.getValue());
                    if (value!=null && value!=0.0) {
                        Object feature = e.getKey();
                        
                        if(columnTypes.get(feature)!=TypeInference.DataType.NUMERICAL) {
                            Double previousValue = tmp_categoricalFrequencies.getOrDefault(feature, 0.0);
                            tmp_categoricalFrequencies.put(feature, previousValue+1.0);
                        }
                        else {
                            Double previousValueSumX = tmp_varianceSumX.getOrDefault(feature, 0.0);
                            Double previousValueSumXsquare = tmp_varianceSumXsquare.getOrDefault(feature, 0.0);
                            tmp_varianceSumX.put(feature, previousValueSumX+value);
                            tmp_varianceSumXsquare.put(feature, previousValueSumXsquare+value*value);
                        }
                    }
                }
            }
            
            double gammaWeight = trainingParameters.getCategoricalGamaMultiplier();
            
            //estimate weights
            streamExecutor.forEach(StreamMethods.stream(columnTypes.entrySet().stream(), isParallelized()), e -> {
                Object feature = e.getKey();
                TypeInference.DataType type = e.getValue();
                
                double weight;
                if(type!=TypeInference.DataType.NUMERICAL) {
                    double percentage = tmp_categoricalFrequencies.get(feature)/n;
                    weight = 1.0 -percentage*percentage;
                }
                else {
                    double mean = tmp_varianceSumX.get(feature)/n;
                    weight = 2.0*((tmp_varianceSumXsquare.get(feature)/n)-mean*mean);
                }
                
                
                if(weight>0) {
                    weight = 1/weight;
                }
                
                //apply muliplier if categorical
                if(type!=TypeInference.DataType.NUMERICAL) {
                    weight *= gammaWeight;
                }
                
                featureWeights.put(feature, weight);
            });
            
            //Drop the temporary Collection
            storageEngine.dropBigMap("tmp_categoricalFrequencies", tmp_categoricalFrequencies);
            storageEngine.dropBigMap("tmp_varianceSumX", tmp_categoricalFrequencies);
            storageEngine.dropBigMap("tmp_varianceSumXsquare", tmp_categoricalFrequencies);
        }
    }
1317899
@Override
    public void setWeights(Map<String, INDArray> weights) throws InvalidKerasConfigurationException {
        this.weights = new HashMap<>();
        /* Keras stores LSTM parameters in distinct arrays (e.g., the recurrent weights
         * are stored in four matrices: U_c, U_f, U_i, U_o) while DL4J stores them
         * concatenated into one matrix (e.g., U = [ U_c U_f U_o U_i ]). Thus we have
         * to map the Keras weight matrix to its corresponding DL4J weight submatrix.
         */
        INDArray W_i;
        INDArray W_f;
        INDArray W_c;
        INDArray W_o;
        INDArray U_i;
        INDArray U_f;
        INDArray U_c;
        INDArray U_o;
        INDArray b_i;
        INDArray b_f;
        INDArray b_c;
        INDArray b_o;


        if (kerasMajorVersion == 2) {
            INDArray W;
            if (weights.containsKey(conf.getKERAS_PARAM_NAME_W()))
                W = weights.get(conf.getKERAS_PARAM_NAME_W());
            else
                throw new InvalidKerasConfigurationException(
                        "Keras LSTM layer does not contain parameter " + conf.getKERAS_PARAM_NAME_W());
            INDArray U;
            if (weights.containsKey(conf.getKERAS_PARAM_NAME_RW()))
                U = weights.get(conf.getKERAS_PARAM_NAME_RW());
            else
                throw new InvalidKerasConfigurationException(
                        "Keras LSTM layer does not contain parameter " + conf.getKERAS_PARAM_NAME_RW());
            INDArray b;
            if (weights.containsKey(conf.getKERAS_PARAM_NAME_B()))
                b = weights.get(conf.getKERAS_PARAM_NAME_B());
            else
                throw new InvalidKerasConfigurationException(
                        "Keras LSTM layer does not contain parameter " + conf.getKERAS_PARAM_NAME_B());

            val sliceInterval = b.length() / 4;
            W_i = W.get(NDArrayIndex.all(), NDArrayIndex.interval(0, sliceInterval));
            W_f = W.get(NDArrayIndex.all(), NDArrayIndex.interval(sliceInterval, 2 * sliceInterval));
            W_c = W.get(NDArrayIndex.all(), NDArrayIndex.interval(2 * sliceInterval, 3 * sliceInterval));
            W_o = W.get(NDArrayIndex.all(), NDArrayIndex.interval(3 * sliceInterval, 4 * sliceInterval));
            U_i = U.get(NDArrayIndex.all(), NDArrayIndex.interval(0, sliceInterval));
            U_f = U.get(NDArrayIndex.all(), NDArrayIndex.interval(sliceInterval, 2 * sliceInterval));
            U_c = U.get(NDArrayIndex.all(), NDArrayIndex.interval(2 * sliceInterval, 3 * sliceInterval));
            U_o = U.get(NDArrayIndex.all(), NDArrayIndex.interval(3 * sliceInterval, 4 * sliceInterval));
            b_i = b.get(NDArrayIndex.interval(0, sliceInterval));
            b_f = b.get(NDArrayIndex.interval(sliceInterval, 2 * sliceInterval));
            b_c = b.get(NDArrayIndex.interval(2 * sliceInterval, 3 * sliceInterval));
            b_o = b.get(NDArrayIndex.interval(3 * sliceInterval, 4 * sliceInterval));
        } else {
            if (weights.containsKey(KERAS_PARAM_NAME_W_C))
                W_c = weights.get(KERAS_PARAM_NAME_W_C);
            else
                throw new InvalidKerasConfigurationException(
                        "Keras LSTM layer does not contain parameter " + KERAS_PARAM_NAME_W_C);
            if (weights.containsKey(KERAS_PARAM_NAME_W_F))
                W_f = weights.get(KERAS_PARAM_NAME_W_F);
            else
                throw new InvalidKerasConfigurationException(
                        "Keras LSTM layer does not contain parameter " + KERAS_PARAM_NAME_W_F);
            if (weights.containsKey(KERAS_PARAM_NAME_W_O))
                W_o = weights.get(KERAS_PARAM_NAME_W_O);
            else
                throw new InvalidKerasConfigurationException(
                        "Keras LSTM layer does not contain parameter " + KERAS_PARAM_NAME_W_O);
            if (weights.containsKey(KERAS_PARAM_NAME_W_I))
                W_i = weights.get(KERAS_PARAM_NAME_W_I);
            else
                throw new InvalidKerasConfigurationException(
                        "Keras LSTM layer does not contain parameter " + KERAS_PARAM_NAME_W_I);
            if (weights.containsKey(KERAS_PARAM_NAME_U_C))
                U_c = weights.get(KERAS_PARAM_NAME_U_C);
            else
                throw new InvalidKerasConfigurationException(
                        "Keras LSTM layer does not contain parameter " + KERAS_PARAM_NAME_U_C);
            if (weights.containsKey(KERAS_PARAM_NAME_U_F))
                U_f = weights.get(KERAS_PARAM_NAME_U_F);
            else
                throw new InvalidKerasConfigurationException(
                        "Keras LSTM layer does not contain parameter " + KERAS_PARAM_NAME_U_F);
            if (weights.containsKey(KERAS_PARAM_NAME_U_O))
                U_o = weights.get(KERAS_PARAM_NAME_U_O);
            else
                throw new InvalidKerasConfigurationException(
                        "Keras LSTM layer does not contain parameter " + KERAS_PARAM_NAME_U_O);
            if (weights.containsKey(KERAS_PARAM_NAME_U_I))
                U_i = weights.get(KERAS_PARAM_NAME_U_I);
            else
                throw new InvalidKerasConfigurationException(
                        "Keras LSTM layer does not contain parameter " + KERAS_PARAM_NAME_U_I);
            if (weights.containsKey(KERAS_PARAM_NAME_B_C))
                b_c = weights.get(KERAS_PARAM_NAME_B_C);
            else
                throw new InvalidKerasConfigurationException(
                        "Keras LSTM layer does not contain parameter " + KERAS_PARAM_NAME_B_C);
            if (weights.containsKey(KERAS_PARAM_NAME_B_F))
                b_f = weights.get(KERAS_PARAM_NAME_B_F);
            else
                throw new InvalidKerasConfigurationException(
                        "Keras LSTM layer does not contain parameter " + KERAS_PARAM_NAME_B_F);
            if (weights.containsKey(KERAS_PARAM_NAME_B_O))
                b_o = weights.get(KERAS_PARAM_NAME_B_O);
            else
                throw new InvalidKerasConfigurationException(
                        "Keras LSTM layer does not contain parameter " + KERAS_PARAM_NAME_B_O);
            if (weights.containsKey(KERAS_PARAM_NAME_B_I))
                b_i = weights.get(KERAS_PARAM_NAME_B_I);
            else
                throw new InvalidKerasConfigurationException(
                        "Keras LSTM layer does not contain parameter " + KERAS_PARAM_NAME_B_I);

        }

        // Need to convert from IFCO to CFOI order
        int wCols = W_c.columns();
        int wRows = W_c.rows();

        INDArray W = Nd4j.zeros(wRows, 4 * wCols);
        W.put(new INDArrayIndex[]{NDArrayIndex.interval(0, wRows), NDArrayIndex.interval(0, wCols)}, W_c);
        W.put(new INDArrayIndex[]{NDArrayIndex.interval(0, wRows), NDArrayIndex.interval(wCols, 2 * wCols)}, W_f);
        W.put(new INDArrayIndex[]{NDArrayIndex.interval(0, wRows), NDArrayIndex.interval(2 * wCols, 3 * wCols)}, W_o);
        W.put(new INDArrayIndex[]{NDArrayIndex.interval(0, wRows), NDArrayIndex.interval(3 * wCols, 4 * wCols)}, W_i);
        this.weights.put(LSTMParamInitializer.INPUT_WEIGHT_KEY, W);

        int uCols = U_c.columns();
        int uRows = U_c.rows();
        INDArray U = Nd4j.zeros(uRows, 4 * uCols);
        U.put(new INDArrayIndex[]{NDArrayIndex.interval(0, U.rows()), NDArrayIndex.interval(0, uCols)}, U_c);
        U.put(new INDArrayIndex[]{NDArrayIndex.interval(0, U.rows()), NDArrayIndex.interval(uCols, 2 * uCols)}, U_f);
        U.put(new INDArrayIndex[]{NDArrayIndex.interval(0, U.rows()), NDArrayIndex.interval(2 * uCols, 3 * uCols)}, U_o);
        U.put(new INDArrayIndex[]{NDArrayIndex.interval(0, U.rows()), NDArrayIndex.interval(3 * uCols, 4 * uCols)}, U_i);
        this.weights.put(LSTMParamInitializer.RECURRENT_WEIGHT_KEY, U);


        int bCols = b_c.columns();
        int bRows = b_c.rows();
        INDArray b = Nd4j.zeros(bRows, 4 * bCols);
        b.put(new INDArrayIndex[]{NDArrayIndex.interval(0, b.rows()), NDArrayIndex.interval(0, bCols)}, b_c);
        b.put(new INDArrayIndex[]{NDArrayIndex.interval(0, b.rows()), NDArrayIndex.interval(bCols, 2 * bCols)}, b_f);
        b.put(new INDArrayIndex[]{NDArrayIndex.interval(0, b.rows()), NDArrayIndex.interval(2 * bCols, 3 * bCols)}, b_o);
        b.put(new INDArrayIndex[]{NDArrayIndex.interval(0, b.rows()), NDArrayIndex.interval(3 * bCols, 4 * bCols)}, b_i);
        this.weights.put(LSTMParamInitializer.BIAS_KEY, b);

        if (weights.size() > NUM_WEIGHTS_IN_KERAS_LSTM) {
            Set<String> paramNames = weights.keySet();
            paramNames.remove(KERAS_PARAM_NAME_W_C);
            paramNames.remove(KERAS_PARAM_NAME_W_F);
            paramNames.remove(KERAS_PARAM_NAME_W_I);
            paramNames.remove(KERAS_PARAM_NAME_W_O);
            paramNames.remove(KERAS_PARAM_NAME_U_C);
            paramNames.remove(KERAS_PARAM_NAME_U_F);
            paramNames.remove(KERAS_PARAM_NAME_U_I);
            paramNames.remove(KERAS_PARAM_NAME_U_O);
            paramNames.remove(KERAS_PARAM_NAME_B_C);
            paramNames.remove(KERAS_PARAM_NAME_B_F);
            paramNames.remove(KERAS_PARAM_NAME_B_I);
            paramNames.remove(KERAS_PARAM_NAME_B_O);
            String unknownParamNames = paramNames.toString();
            log.warn("Attemping to set weights for unknown parameters: "
                    + unknownParamNames.substring(1, unknownParamNames.length() - 1));
        }
    }
576540
def predict(self, Xnew=None, filteronly=False, include_likelihood=True, balance=None, **kw):
        
        
        if balance is None:
            p_balance = self.balance
        else:
            p_balance = balance
            
        # Run the Kalman filter to get the state
        (m, V) = self._raw_predict(Xnew,filteronly=filteronly, p_balance=p_balance)

        # Add the noise variance to the state variance
        if include_likelihood:
            V += float(self.likelihood.variance)

        # Lower and upper bounds
        #lower = m - 2*np.sqrt(V)
        #upper = m + 2*np.sqrt(V)

        # Return mean and variance
        return m, V
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
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)
1023663
def build_weights(realizations, imt_dt):
    
    arr = numpy.zeros((len(realizations), len(imt_dt.names)))
    for m, imt in enumerate(imt_dt.names):
        arr[:, m] = [rlz.weight[imt] for rlz in realizations]
    return arr
1273596
function weight(kernel, bandwidth, x_0, x_i) {
  const arg = (x_i - x_0) / bandwidth;
  return kernel(arg);
}
380694
def weights(self):
        
        if self._weights is not None and len(self._weights):
            return self._weights
        else:
            return np.full((self.Ntriangles, 3), 1./3)
1370211
def _raw_weights(self):
        
        if self._debug:
            return np.array([[],[],[],[]])

        if not self._running:
            raise ValueError('Weight sensor is not running!')
        if len(self._weight_buffers) == 0:
            time.sleep(0.3)
            if len(self._weight_buffers) == 0:
                raise ValueError('Weight sensor is not retrieving data!')
        weights = np.array(self._weight_buffers)
        return weights
1271123
def init_net_params(scale, layer_sizes, rs=npr.RandomState(0)):
    """"""
    return [(scale * rs.randn(m, n),   # weight matrix
             scale * rs.randn(n))      # bias vector
            for m, n in zip(layer_sizes[:-1], layer_sizes[1:])]
1247906
def xstep(self):
        
        """

        ngsit = 0
        gsrrs = np.inf
        while gsrrs > self.opt['GSTol'] and ngsit < self.opt['MaxGSIter']:
            self.X = self.GaussSeidelStep(self.S, self.X,
                                          self.cnst_AT(self.Y-self.U),
                                          self.rho, self.lcw, self.Wdf2)
            gsrrs = sl.rrs(
                self.rho*self.cnst_AT(self.cnst_A(self.X)) +
                self.Wdf2*self.X, self.Wdf2*self.S +
                self.rho*self.cnst_AT(self.Y - self.U))
            ngsit += 1

        self.xs = (ngsit, gsrrs)
1060867
private void computeRatio() {
    for (int i = 0; i < vectorSize; i++) {
      double keyWeight = getWeight(keyVector[i]);
      double fpWeight = getWeight(fpVector[i]);

      if (keyWeight > 0 && fpWeight > 0) {
        ratio[i] = keyWeight / fpWeight;
      }
    }
  }
417841
private static void balbak(DenseMatrix V, double[] scale) {
        int n = V.nrows();
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                V.mul(i, j, scale[i]);
            }
        }
    }
193844
def _preprocess_inputs(x, weights):
    
    if weights is None:
        w_arr = np.ones(len(x))
    else:
        w_arr = np.array(weights)
    x_arr = np.array(x)
    if x_arr.ndim == 2:
        if w_arr.ndim == 1:
            w_arr = w_arr[:, np.newaxis]
    return x_arr, w_arr