Compute the micro average scores for the ROCAUC curves.
420891
def _score_micro_average(self, y, y_pred, classes, n_classes):
        
        # Convert y to binarized array for micro and macro scores
        y = label_binarize(y, classes=classes)
        if n_classes == 2:
            y = np.hstack((1-y, y))

        # Compute micro-average
        self.fpr[MICRO], self.tpr[MICRO], _ = roc_curve(y.ravel(), y_pred.ravel())
        self.roc_auc[MICRO] = auc(self.fpr[MICRO], self.tpr[MICRO])
425782
def value(self):
        

        if self.scores.numel() == 0:
            return 0
        ap = torch.zeros(self.scores.size(1))
        rg = torch.arange(1, self.scores.size(0)).float()

        # compute average precision for each class
        for k in range(self.scores.size(1)):
            # sort scores
            scores = self.scores[:, k]
            targets = self.targets[:, k]

            # compute average precision
            ap[k] = AveragePrecisionMeter.average_precision(scores, targets, self.difficult_examples)
        return ap
960952
def score(self, i):
        """"""
        if self.minimize:
            return self.data[i][0]
        else:
            return self.data[(-1 * i) - 1][0]
1303063
def calculate_statistics(self):
        ""
        rev_ids = range(0, 100, 1)
        feature_values = zip(rev_ids, [0] * 100)
        scores = [self.score(f) for f in feature_values]
        labels = [s['prediction'] for s in scores]
        statistics = Classification(labels, threshold_ndigits=1, decision_key='probability')
        score_labels = list(zip(scores, labels))
        statistics.fit(score_labels)
        return statistics
505059
def _compute_vline_scores(self):
        
        M, N, L = self.M, self.N, self.L
        vline_score = {}
        for x in range(M):
            laststart = [0 if (x, 0, 1, k) in self else None for k in range(L)]
            for y in range(N):
                block = [0] * (y + 1)
                for k in range(L):
                    if (x, y, 1, k) not in self:
                        laststart[k] = None
                    elif laststart[k] is None:
                        laststart[k] = y
                        block[y] += 1
                    elif y and (x, y, 1, k) not in self[x, y - 1, 1, k]:
                        laststart[k] = y
                    else:
                        for y1 in range(laststart[k], y + 1):
                            block[y1] += 1
                for y1 in range(y + 1):
                    vline_score[x, y1, y] = block[y1]
        self._vline_score = vline_score
405130
def averageSequenceAccuracy(self, minOverlap, maxOverlap,
                              firstStat=0, lastStat=None):
    
    numCorrectSparsity = 0.0
    numCorrectClassifications = 0.0
    numStats = 0.0

    # For each object or sequence we classify every point or element
    #
    # A sequence element is considered correctly classified only if the number
    # of predictedActive cells is within a reasonable range and if the KNN
    # Classifier correctly classifies the active cell representation as
    # belonging to this sequence.
    #
    # A point on an object is considered correctly classified by the TM if the
    # number of predictedActive cells is within range.
    for stats in self.statistics[firstStat:lastStat]:

      # Keep running total of how often the number of predictedActive cells are
      # in the range.  We always skip the first (unpredictable) count.
      predictedActiveStat = stats["TM PredictedActive C0"][1:]
      TMRepresentationStat = stats["TM Full Representation C0"][1:]
      # print "\n-----------"
      # print stats["object"], predictedActiveStat
      for numCells,sdr in zip(predictedActiveStat, TMRepresentationStat):
        numStats += 1.0
        # print "numCells: ", numCells
        if numCells in range(minOverlap, maxOverlap + 1):
          numCorrectSparsity += 1.0

          # Check KNN Classifier
          sdr = list(sdr)
          sdr.sort()
          dense = numpy.zeros(self.numTMCells)
          dense[sdr] = 1.0
          (winner, inferenceResult, dist, categoryDist) = \
            self.classifier.infer(dense)
          # print sdr, winner, stats['object'], winner == stats['object']
          # print categoryDist
          # print

          if winner == stats['object']:
            numCorrectClassifications += 1.0

    if numStats==0:
      return 0.0, 0.0

    return ((numCorrectSparsity / numStats),
            (numCorrectClassifications / numStats) )
974265
def _compute_mean(self, C, mag, rrup):
        
        mean = (C['c1'] +
                self._compute_term1(C, mag) +
                self._compute_term2(C, mag, rrup) +
                self._compute_term3(C, rrup))
        return mean
236074
def roc_auc(y_true, y_score):
    
    notnull = ~np.isnan(y_true)
    fpr, tpr, thresholds = sklearn.metrics.roc_curve(y_true[notnull], y_score[notnull])
    return sklearn.metrics.auc(fpr, tpr)
1321716
def inertia(X,y,samples=False):
    
    # pdb.set_trace()
    if samples:
        # return within-class distance for each sample
        inertia = np.zeros(y.shape)
        for label in np.unique(y):
            inertia[y==label] = (X[y==label] - np.mean(X[y==label])) ** 2

    else: # return aggregate score
        inertia = 0
        for i,label in enumerate(np.unique(y)):
            inertia += np.sum((X[y==label] - np.mean(X[y==label])) ** 2)/len(y[y==label])
        inertia = inertia/len(np.unique(y))

    return inertia
154323
def roc(series, window=14):
    
    res = (series - series.shift(window)) / series.shift(window)
    return pd.Series(index=series.index, data=res)
275043
def _compute_mean(self, C, A1, A2, A3, A4, A5, A6, mag, hypo_depth,
                      rrup, mean, idx):
        
        mean[idx] = (A1 + A2 * mag + C['C1'] + C['C2'] * (A3 - mag) ** 3 +
                     C['C3'] * np.log(rrup[idx] + A4 * np.exp(A5 * mag)) +
                     A6 * hypo_depth)
799510
def _compute(self):
        """"""
        delta = 2 * pi / self._len if self._len else 0
        self._x_pos = [.5 * pi + i * delta for i in range(self._len + 1)]
        for serie in self.all_series:
            serie.points = [(v, self._x_pos[i])
                            for i, v in enumerate(serie.values)]
            if self.interpolate:
                extended_x_pos = ([.5 * pi - delta] + self._x_pos)
                extended_vals = (serie.values[-1:] + serie.values)
                serie.interpolated = list(
                    map(
                        tuple,
                        map(
                            reversed,
                            self._interpolate(extended_x_pos, extended_vals)
                        )
                    )
                )

        # x labels space
        self._box.margin *= 2
        self._rmin = self.zero
        self._rmax = self._max or 1
        self._box.set_polar_box(self._rmin, self._rmax)
        self._self_close = True
430090
function scorePattern(point, ratios, matrix) {
        try {
            const horizontalRun = countBlackWhiteRun(point, { x: -1, y: point.y }, matrix, ratios.length);
            const verticalRun = countBlackWhiteRun(point, { x: point.x, y: -1 }, matrix, ratios.length);
            const topLeftPoint = {
                x: Math.max(0, point.x - point.y) - 1,
                y: Math.max(0, point.y - point.x) - 1,
            };
            const topLeftBottomRightRun = countBlackWhiteRun(point, topLeftPoint, matrix, ratios.length);
            const bottomLeftPoint = {
                x: Math.min(matrix.width, point.x + point.y) + 1,
                y: Math.min(matrix.height, point.y + point.x) + 1,
            };
            const bottomLeftTopRightRun = countBlackWhiteRun(point, bottomLeftPoint, matrix, ratios.length);
            const horzError = scoreBlackWhiteRun(horizontalRun, ratios);
            const vertError = scoreBlackWhiteRun(verticalRun, ratios);
            const diagDownError = scoreBlackWhiteRun(topLeftBottomRightRun, ratios);
            const diagUpError = scoreBlackWhiteRun(bottomLeftTopRightRun, ratios);
            const ratioError = Math.sqrt(horzError.error * horzError.error +
                vertError.error * vertError.error +
                diagDownError.error * diagDownError.error +
                diagUpError.error * diagUpError.error);
            const avgSize = (horzError.averageSize + vertError.averageSize + diagDownError.averageSize + diagUpError.averageSize) / 4;
            const sizeError = (Math.pow((horzError.averageSize - avgSize), 2) +
                Math.pow((vertError.averageSize - avgSize), 2) +
                Math.pow((diagDownError.averageSize - avgSize), 2) +
                Math.pow((diagUpError.averageSize - avgSize), 2)) / avgSize;
            return ratioError + sizeError;
        }
        catch (_a) {
            return Infinity;
        }
    }
594453
def calculate_avg_score(res):
    
    c_star_score = 6
    avg_score = 0.0
    nb_reviews = 0
    for comment in res:
        if comment[c_star_score] > 0:
            avg_score += comment[c_star_score]
            nb_reviews += 1
    if nb_reviews == 0:
        return 0.0
    avg_score = avg_score / nb_reviews
    avg_score_unit = avg_score - math.floor(avg_score)
    if avg_score_unit < 0.25:
        avg_score = math.floor(avg_score)
    elif avg_score_unit > 0.75:
        avg_score = math.floor(avg_score) + 1
    else:
        avg_score = math.floor(avg_score) + 0.5
    if avg_score > 5:
        avg_score = 5.0
    return avg_score
134120
def _compute(self):
        """"""
        positive_vals, negative_vals = self._get_separated_values()

        if self.logarithmic:
            positive_vals = list(
                filter(lambda x: x > self.zero, positive_vals)
            )
            negative_vals = list(
                filter(lambda x: x > self.zero, negative_vals)
            )

        self._compute_box(positive_vals, negative_vals)
        positive_vals = positive_vals or [self.zero]
        negative_vals = negative_vals or [self.zero]

        self._x_pos = [
            x / self._len for x in range(self._len + 1)
        ] if self._len > 1 else [0, 1]  # Center if only one value

        self._points(self._x_pos)

        self.negative_cumulation = [0] * self._len
        self.positive_cumulation = [0] * self._len

        if self.secondary_series:
            positive_vals, negative_vals = self._get_separated_values(True)
            positive_vals = positive_vals or [self.zero]
            negative_vals = negative_vals or [self.zero]
            self.secondary_negative_cumulation = [0] * self._len
            self.secondary_positive_cumulation = [0] * self._len
            self._pre_compute_secondary(positive_vals, negative_vals)

        self._x_pos = [(i + .5) / self._len for i in range(self._len)]
213670
def _calc_inst_pmf(self):
        """"""
        # Easy vars
        t = self.t_
        epsilon = self.epsilon
        alpha = self.alpha
        preds = self._preds_avg_in_strata
        weights = self.strata.weights_[:,np.newaxis]
        p1 = self._BB_model.theta_[:,np.newaxis]
        p0 = 1 - p1
        if t==0:
            F = self._F_guess[self.opt_class]
        else:
            F = self._estimate[t - 1, self.opt_class]
            # Fill in non-finite estimates with the initial guess
            nonfinite = ~np.isfinite(F)
            F[nonfinite] = self._F_guess[self.opt_class][nonfinite]

        # Calculate optimal instrumental pmf
        sqrt_arg = np.sum(preds * (alpha**2 * F**2 * p0 + (1 - F)**2 * p1) + \
                          (1 - preds) * (1 - alpha)**2 * F**2 * p1, \
                          axis=1, keepdims=True) #: sum is over classifiers
        inst_pmf = weights * np.sqrt(sqrt_arg)
        # Normalize
        inst_pmf /= np.sum(inst_pmf)
        # Epsilon-greedy: (1 - epsilon) q + epsilon * p
        inst_pmf *= (1 - epsilon)
        inst_pmf += epsilon * weights

        if self.record_inst_hist:
            self._inst_pmf[:,t] = inst_pmf.ravel()
        else:
            self._inst_pmf = inst_pmf.ravel()
538394
def precision_curve(self, delta_tau=0.01):
        
        # compute thresholds based on the sorted probabilities
        orig_thresh = self.threshold
        sorted_labels, sorted_probs = self.sorted_values

        scores = []
        taus = []
        tau = 0
        for k in range(len(sorted_labels)):
            # compute new accuracy
            self.threshold = tau
            scores.append(self.precision)
            taus.append(tau)

            # update threshold
            tau = sorted_probs[k]

        # add last datapoint
        tau = 1.0
        self.threshold = tau
        scores.append(1.0)
        taus.append(tau)

        self.threshold = orig_thresh
        return scores, taus