Gets the prediction from the tree with the lowest mean absolute error.
511010
def _get_best_prediction(self, record, train=True):
        
        if not self.trees:
            return
        best = (+1e999999, None)
        for tree in self.trees:
            best = min(best, (tree.mae.mean, tree))
        _, best_tree = best
        prediction, tree_mae = best_tree.predict(record, train=train)
        return prediction.mean
744035
def predict(self, record):
        
        
        # Get raw predictions.
        # {tree:raw prediction}
        predictions = {}
        for tree in self.trees:
            _p = tree.predict(record)
            if _p is None:
                continue
            if isinstance(_p, CDist):
                if _p.mean is None:
                    continue
            elif isinstance(_p, DDist):
                if not _p.count:
                    continue
            predictions[tree] = _p
        if not predictions:
            return

        # Normalize weights and aggregate final prediction.
        weights = self.weighting_method(predictions.keys())
        if not weights:
            return
#        assert sum(weights) == 1.0, "Sum of weights must equal 1."
        if self.data.is_continuous_class:
            # Merge continuous class predictions.
            total = sum(w*predictions[tree].mean for w, tree in weights)
        else:
            # Merge discrete class predictions.
            total = DDist()
            for weight, tree in weights:
                prediction = predictions[tree]
                for cls_value, cls_prob in prediction.probs:
                    total.add(cls_value, cls_prob*weight)
        
        return total
804654
def predict(self, Xnew, kern=None, pred_init=None, Y_metadata=None,
                median=False, deg_gauss_hermite=20, likelihood=None):
        
        #mu, var = GP._raw_predict(self, Xnew)
        # now push through likelihood
        #mean, var = self.likelihood.predictive_values(mu, var)
        
        mean, var = super(WarpedGP, self).predict(Xnew, kern=kern, full_cov=False, likelihood=likelihood)


        if self.predict_in_warped_space:
            std = np.sqrt(var)
            if median:
                wmean = self.warping_function.f_inv(mean, y=pred_init)
            else:
                wmean = self._get_warped_mean(mean, std, pred_init=pred_init,
                                              deg_gauss_hermite=deg_gauss_hermite).T
            wvar = self._get_warped_variance(mean, std, pred_init=pred_init,
                                             deg_gauss_hermite=deg_gauss_hermite).T
        else:
            wmean = mean
            wvar = var
        return wmean, wvar
976778
private RedBlackTreeNode<Key, Value> min(RedBlackTreeNode<Key, Value> x) {
	// assert x != null;
	if (x.getLeft() == null)
	    return x;
	else
	    return min(x.getLeft());
    }
465983
def best_oob_mae_weight(trees):
        
        best = (+1e999999, None)
        for tree in trees:
            oob_mae = tree.out_of_bag_mae
            if oob_mae is None or oob_mae.mean is None:
                continue
            best = min(best, (oob_mae.mean, tree))
        best_mae, best_tree = best
        if best_tree is None:
            return
        return [(1.0, best_tree)]
1319506
def predict_maxprob(self, x, **kwargs):
        
        return self.base_estimator_.predict(x.values, **kwargs)
1174769
function(node, l, b, r, t)
{
    return (max(node.bb_r, r) - min(node.bb_l, l))*(max(node.bb_t, t) - min(node.bb_b, b));
}
652178
def model_predictions(self):
        
        if isinstance(self.observed, ContinuousColumn):
            return ValueError("Cannot make model predictions on a continuous scale")
        pred = np.zeros(self.data_size).astype('object')
        for node in self:
            if node.is_terminal:
                pred[node.indices] = max(node.members, key=node.members.get)
        return pred
1068752
def compute_absolute_error(self, predicted_data, record, dataframe_record):
        ''''''

        new_idxs = []
        for analysis_set in self.get_analysis_sets(record):
            ddg_details = record['DDG'][analysis_set]
            exp_ddg_fieldname = BenchmarkRun.get_analysis_set_fieldname('Experimental', analysis_set)
            absolute_error_fieldname = BenchmarkRun.get_analysis_set_fieldname('AbsoluteError', analysis_set)
            new_idxs.append(absolute_error_fieldname)
            dataframe_record[absolute_error_fieldname] = None

            if ddg_details and predicted_data[self.ddg_analysis_type] != None:
                absolute_error = abs(dataframe_record[exp_ddg_fieldname] - predicted_data[self.ddg_analysis_type])
                dataframe_record[absolute_error_fieldname] = absolute_error

        # Update the CSV headers
        try:
            idx = self.csv_headers.index('AbsoluteError')
            self.csv_headers = self.csv_headers[:idx] + new_idxs + self.csv_headers[idx + 1:]
        except ValueError, e: pass
1303714
def predict_proba(estimator, X):
    # type: (Any, Any) -> Optional[np.ndarray]
    
    if is_probabilistic_classifier(estimator):
        try:
            proba, = estimator.predict_proba(X)
            return proba
        except NotImplementedError:
            return None
    else:
        return None
526972
protected Predict<int[]> getPath(Node[][] lattice) {

		Predict<int[]> res = new Predict<int[]>();
		if (lattice.length == 0)
			return res;

		float max = Float.NEGATIVE_INFINITY;
		int cur = 0;
		for (int c = 0; c < ysize(); c++) {
			if (lattice[lattice.length-1][c] == null)
				continue;
			
			if (lattice[lattice.length - 1][c].score > max) {
				max = lattice[lattice.length - 1][c].score;
				cur = c;
			}
		}

		int[] path = new int[lattice.length];
		path[lattice.length - 1] = cur;
		for (int l = lattice.length - 1; l > 0; l--) {
			cur = lattice[l][cur].prev;
			path[l - 1] = cur;
		}
		res.add(path,max);

		return res;
	}
1297814
public static float classify( AutoBuffer ts, Chunk[] chks, int row, int modelDataMap[], short badData, boolean regression ) {
    ts.get4();    // Skip tree-id
    ts.get8();    // Skip seed
    ts.get1();    // Skip producer id
    byte b;

    while( (b = (byte) ts.get1()) != '[' ) { // While not a leaf indicator
      assert b == '(' || b == 'S' || b == 'E';
      int col = modelDataMap[ts.get2()]; // Column number in model-space mapped to data-space
      float fcmp = ts.get4f();  // Float to compare against
      if( chks[col].isNA0(row) ) return badData;
      float fdat = (float)chks[col].at0(row);
      int skip = (ts.get1()&0xFF);
      if( skip == 0 ) skip = ts.get3();
      if (b == 'E') {
        if (fdat != fcmp)
          ts.position(ts.position() + skip);
      } else {
        // Picking right subtree? then skip left subtree
        if( fdat > fcmp ) ts.position(ts.position() + skip);
      }
    }
    if (regression) {
      return ts.get4f();
    }
    return (float)((short) ( ts.get1()&0xFF ));      // Return the leaf's class
  }
782708
@Override
    public int predict(T x) {
        double minDist = Double.MAX_VALUE;
        int bestCluster = 0;

        for (int i = 0; i < k; i++) {
            double dist = distance.d(x, medoids[i]);
            if (dist < minDist) {
                minDist = dist;
                bestCluster = i;
            }
        }

        return bestCluster;
    }
175567
def predict_proba(self, dataframe):
        
        ret = numpy.ones((dataframe.shape[0], 2))
        ret[:, 0] = (1 - self.mean)
        ret[:, 1] = self.mean
        return ret
856522
def accuracy(batch, model_predictions):
  """"""
  _, targets = batch
  model_predictions, targets = _make_list(model_predictions, targets)
  correct = []
  for (prediction, target) in zip(model_predictions, targets):
    predicted_class = np.argmax(prediction, axis=-1)
    correct.append(np.equal(predicted_class, target))
  return masked_mean(correct, targets)
363859
def _predict_tree(model, X, joint_contribution=False):
    
    leaves = model.apply(X)
    paths = _get_tree_paths(model.tree_, 0)

    for path in paths:
        path.reverse()

    leaf_to_path = {}
    #map leaves to paths
    for path in paths:
        leaf_to_path[path[-1]] = path         
    
    # remove the single-dimensional inner arrays
    values = model.tree_.value.squeeze(axis=1)
    # reshape if squeezed into a single float
    if len(values.shape) == 0:
        values = np.array([values])
    if isinstance(model, DecisionTreeRegressor):
        biases = np.full(X.shape[0], values[paths[0][0]])
        line_shape = X.shape[1]
    elif isinstance(model, DecisionTreeClassifier):
        # scikit stores category counts, we turn them into probabilities
        normalizer = values.sum(axis=1)[:, np.newaxis]
        normalizer[normalizer == 0.0] = 1.0
        values /= normalizer

        biases = np.tile(values[paths[0][0]], (X.shape[0], 1))
        line_shape = (X.shape[1], model.n_classes_)
    direct_prediction = values[leaves]
    
    
    #make into python list, accessing values will be faster
    values_list = list(values)
    feature_index = list(model.tree_.feature)
    
    contributions = []
    if joint_contribution:
        for row, leaf in enumerate(leaves):
            path = leaf_to_path[leaf]
            
            
            path_features = set()
            contributions.append({})
            for i in range(len(path) - 1):
                path_features.add(feature_index[path[i]])
                contrib = values_list[path[i+1]] - \
                         values_list[path[i]]
                #path_features.sort()
                contributions[row][tuple(sorted(path_features))] = \
                    contributions[row].get(tuple(sorted(path_features)), 0) + contrib
        return direct_prediction, biases, contributions
        
    else:
        unique_leaves = np.unique(leaves)
        unique_contributions = {}
        
        for row, leaf in enumerate(unique_leaves):
            for path in paths:
                if leaf == path[-1]:
                    break
            
            contribs = np.zeros(line_shape)
            for i in range(len(path) - 1):
                
                contrib = values_list[path[i+1]] - \
                         values_list[path[i]]
                contribs[feature_index[path[i]]] += contrib
            unique_contributions[leaf] = contribs
            
        for row, leaf in enumerate(leaves):
            contributions.append(unique_contributions[leaf])

        return direct_prediction, biases, np.array(contributions)
1076164
def _get_representative(self, obj):
        """"""

        if obj not in self._parents:
            self._parents[obj] = obj
            self._weights[obj] = 1
            self._prev_next[obj] = [obj, obj]
            self._min_values[obj] = obj
            return obj

        path = [obj]
        root = self._parents[obj]
        while root != path[-1]:
            path.append(root)
            root = self._parents[root]

        # compress the path and return
        for ancestor in path:
            self._parents[ancestor] = root
        return root