Args:
            gold: a np.ndarray of gold labels (ints)
            pred: a np.ndarray of predictions (ints)
357801
def add(self, gold, pred):
        
        self.counter.update(zip(gold, pred))
702821
def posterior_predictive_to_xarray(self):
        """"""
        if self.model_fn is None:
            return None

        posterior_preds = []
        sample_size = self.posterior[0].shape[0]

        for i in np.arange(0, sample_size, int(sample_size / self.posterior_predictive_samples)):
            variables = {}
            for var_i, var_name in enumerate(self.var_names):
                variables[var_name] = self.posterior[var_i][i]

            with self.ed.interception(self._value_setter(variables)):
                if self.posterior_predictive_size > 1:
                    posterior_preds.append(
                        [self.model_fn() for _ in range(self.posterior_predictive_size)]
                    )
                else:
                    posterior_preds.append(self.model_fn())

        data = {}
        with self.tf.Session() as sess:
            data["obs"] = np.expand_dims(
                sess.run(posterior_preds, feed_dict=self.feed_dict), axis=0
            )
        return dict_to_dataset(data, library=self.tfp, coords=self.coords, dims=self.dims)
332980
def _make_text_predict_fn(self, labels, instance, column_to_explain):
        

        def _predict_fn(perturbed_text):
            predict_input = []
            for x in perturbed_text:
                instance_copy = dict(instance)
                instance_copy[column_to_explain] = x
                predict_input.append(instance_copy)

            df = _local_predict.get_prediction_results(self._model_dir, predict_input,
                                                       self._headers, with_source=False)
            probs = _local_predict.get_probs_for_labels(labels, df)
            return np.asarray(probs)

        return _predict_fn
1066108
def golds_to_gold_tuples(docs, golds):
    """"""
    tuples = []
    for doc, gold in zip(docs, golds):
        text = doc.text
        ids, words, tags, heads, labels, iob = zip(*gold.orig_annot)
        sents = [((ids, words, tags, heads, labels, iob), [])]
        tuples.append((text, sents))
    return tuples
221830
def b_cubed(clusters, mention_to_gold):
        
        numerator, denominator = 0, 0
        for cluster in clusters:
            if len(cluster) == 1:
                continue
            gold_counts = Counter()
            correct = 0
            for mention in cluster:
                if mention in mention_to_gold:
                    gold_counts[tuple(mention_to_gold[mention])] += 1
            for cluster2, count in gold_counts.items():
                if len(cluster2) != 1:
                    correct += count * count
            numerator += correct / float(len(cluster))
            denominator += len(cluster)
        return numerator, denominator
952874
public String decodePredictions(INDArray predictions) {
        Preconditions.checkState(predictions.size(1) == predictionLabels.size(), "Invalid input array:" +
                " expected array with size(1) equal to numLabels (%s), got array with shape %s", predictionLabels.size(), predictions.shape());

        String predictionDescription = "";
        int[] top5 = new int[5];
        float[] top5Prob = new float[5];

        //brute force collect top 5
        int i = 0;
        for (int batch = 0; batch < predictions.size(0); batch++) {
            predictionDescription += "Predictions for batch ";
            if (predictions.size(0) > 1) {
                predictionDescription += String.valueOf(batch);
            }
            predictionDescription += " :";
            INDArray currentBatch = predictions.getRow(batch).dup();
            while (i < 5) {
                top5[i] = Nd4j.argMax(currentBatch, 1).getInt(0);
                top5Prob[i] = currentBatch.getFloat(batch, top5[i]);
                currentBatch.putScalar(0, top5[i], 0);
                predictionDescription += "\n\t" + String.format("%3f", top5Prob[i] * 100) + "%, "
                                + predictionLabels.get(top5[i]);
                i++;
            }
        }
        return predictionDescription;
    }
1372165
def evaluate(self, text):
        
        cx = BinaryConfusion()
        for (L, P, R, gold, _) in Detector.candidates(text):
            guess = self.predict(L, P, R)
            cx.update(gold, guess)
            if not gold and guess:
                logger.debug("False pos.: L='{}', R='{}'.".format(L, R))
            elif gold and not guess:
                logger.debug("False neg.: L='{}', R='{}'.".format(L, R))
        return cx
908930
def node_predictions(self):
        
        pred = np.zeros(self.data_size)
        for node in self:
            if node.is_terminal:
                pred[node.indices] = node.node_id
        return pred
510668
def rae(label, pred):
    """"""
    numerator = np.mean(np.abs(label - pred), axis=None)
    denominator = np.mean(np.abs(label - np.mean(label, axis=None)), axis=None)
    return numerator / denominator
595391
def less_naive(gold_schemes):
    """"""
    best_schemes = defaultdict(lambda: defaultdict(int))
    for g in gold_schemes:
        best_schemes[len(g)][tuple(g)] += 1

    for i in best_schemes:
        best_schemes[i] = tuple(max(best_schemes[i].items(), key=lambda x: x[1])[0])

    naive_schemes = []
    for g in gold_schemes:
        naive_schemes.append(best_schemes[len(g)])
    return naive_schemes
626669
def compute_colors_for_labels(self, labels):
        
        colors = labels[:, None] * self.palette
        colors = (colors % 255).numpy().astype("uint8")
        return colors
1149464
def _align_bags(predicted: List[Set[str]], gold: List[Set[str]]) -> List[float]:
    
    f1_scores = []
    for gold_index, gold_item in enumerate(gold):
        max_f1 = 0.0
        max_index = None
        best_alignment: Tuple[Set[str], Set[str]] = (set(), set())
        if predicted:
            for pred_index, pred_item in enumerate(predicted):
                current_f1 = _compute_f1(pred_item, gold_item)
                if current_f1 >= max_f1:
                    best_alignment = (gold_item, pred_item)
                    max_f1 = current_f1
                    max_index = pred_index
            match_flag = _match_numbers_if_present(*best_alignment)
            gold[gold_index] = set()
            predicted[max_index] = set()
        else:
            match_flag = False
        if match_flag:
            f1_scores.append(max_f1)
        else:
            f1_scores.append(0.0)
    return f1_scores
1182797
def preds(self, nodeids=None):
        
        if nodeids is None: nodeids = self._nodeids
        _eps = self._eps
        return [_eps[nid][1] for nid in nodeids]
939810
def facc(label, pred):
    
    pred = pred.ravel()
    label = label.ravel()
    return ((pred > 0.5) == label).mean()
899839
def predict(self, inputs: np.ndarray) -> np.ndarray:
        """"""
        return self.sess.run(self.out_var, {self.inp_var: inputs})
1144248
def predict(self):
        
        RV = np.zeros((self.N,self.P))
        for term_i in range(self.n_terms):
            RV+=np.dot(self.Fstar()[term_i],np.dot(self.B()[term_i],self.Astar()[term_i]))
        return RV
476503
def evaluate(self, gold):
        
        tagged_sents = self.tag_sents([w for (w, t) in sent] for sent in gold)
        gold_tokens = sum(gold, [])
        test_tokens = sum(tagged_sents, [])
        accuracy = float(sum(x == y for x, y in six.moves.zip(gold_tokens, test_tokens))) / len(test_tokens)
        return accuracy