Python calculate score

60 Python code examples are found related to " calculate score". You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.
Example 1
Source File: basic_consolidation.py    From watcher with Apache License 2.0 8 votes vote down vote up
def calculate_score_node(self, node):
        """Calculate the score that represent the utilization level

        :param node: :py:class:`~.ComputeNode` instance
        :return: Score for the given compute node
        :rtype: float
        """
        host_avg_cpu_util = self.get_compute_node_cpu_usage(node)

        if host_avg_cpu_util is None:
            resource_id = "%s_%s" % (node.uuid, node.hostname)
            LOG.error(
                "No values returned by %(resource_id)s "
                "for %(metric_name)s", dict(
                    resource_id=resource_id,
                    metric_name='host_cpu_usage'))
            host_avg_cpu_util = 100

        total_cores_used = node.vcpus * (host_avg_cpu_util / 100.0)

        return self.calculate_weight(node, total_cores_used, 0, 0) 
Example 2
Source File: germselection.py    From pyGSTi with Apache License 2.0 6 votes vote down vote up
def calculate_germset_score(germs, target_model=None, neighborhood=None,
                            neighborhoodSize=5,
                            randomizationStrength=1e-2, scoreFunc='all',
                            opPenalty=0.0, l1Penalty=0.0):
    """Calculate the score of a germ set with respect to a model.
    """
    def scoreFn(x): return _scoring.list_score(x, scoreFunc=scoreFunc)
    if neighborhood is None:
        neighborhood = [target_model.randomize_with_unitary(randomizationStrength)
                        for n in range(neighborhoodSize)]
    scores = [compute_composite_germ_score(scoreFn, model=model,
                                           partialGermsList=germs,
                                           opPenalty=opPenalty,
                                           l1Penalty=l1Penalty)
              for model in neighborhood]

    return max(scores) 
Example 3
Source File: similarity.py    From timesketch with Apache License 2.0 6 votes vote down vote up
def calculate_score(lsh, minhash, total_num_events):
    """Calculate a score based on Jaccard distance.

    The score is calculated based on how many similar events that there are
    for the event being scored. This is called neighbours and we simply
    calculate how many neighbours the event has divided by the total events
    in the LSH.

    Args:
        lsh: instance of datasketch.lsh.MinHashLSH
        minhash: instance of datasketch.minhash.MinHash
        total_num_events: integer of how many events in the LSH

    Returns:
        A float between 0 and 1.
    """
    neighbours = lsh.query(minhash)
    return float(len(neighbours)) / float(total_num_events) 
Example 4
Source File: compare.py    From q2mm with MIT License 6 votes vote down vote up
def calculate_score(r_data, c_data):
    """
    *** Depracated: All of this is in compare_data()
    Calculates the objective function score.
    """
    score_tot = 0.
    for r_datum, c_datum in zip(r_data, c_data):
        # Could add a check here to assure that the data points are aligned.
        # Ex.) assert r_datum.ind_1 == c_datum.ind_1, 'Oh no!'

        # For torsions, ensure the difference between -179 and 179 is 2, not
        # 358.
        if c_datum.typ == 't':
            diff = abs(r_datum.val - c_datum.val)
            if diff > 180.:
                diff = 360. - diff
        else:
            diff = r_datum.val - c_datum.val
        score_ind = r_datum.wht**2 * diff**2
        score_tot += score_ind
        logger.log(1, '>>> {} {} {}'.format(r_datum, c_datum, score_ind))

    logger.log(5, 'SCORE: {}'.format(score_tot))
    return score_tot 
Example 5
Source File: inception_utils.py    From BigGAN-PyTorch with MIT License 6 votes vote down vote up
def calculate_inception_score(pred, num_splits=10):
  scores = []
  for index in range(num_splits):
    pred_chunk = pred[index * (pred.shape[0] // num_splits): (index + 1) * (pred.shape[0] // num_splits), :]
    kl_inception = pred_chunk * (np.log(pred_chunk) - np.log(np.expand_dims(np.mean(pred_chunk, 0), 0)))
    kl_inception = np.mean(np.sum(kl_inception, 1))
    scores.append(np.exp(kl_inception))
  return np.mean(scores), np.std(scores)


# Loop and run the sampler and the net until it accumulates num_inception_images
# activations. Return the pool, the logits, and the labels (if one wants 
# Inception Accuracy the labels of the generated class will be needed) 
Example 6
Source File: metric.py    From dsb2018_topcoders with MIT License 6 votes vote down vote up
def calculate_cell_score_selim(y_true, y_pred, num_threads=32, ids=None):
    yps = []
    for m in range(len(y_true)):
        yps.append((y_true[m].copy(), y_pred[m].copy()))
    pool = Pool(num_threads)
    results = pool.map(calculate_jaccard, yps)
    if ids:
        import pandas as pd
        s_iou = np.argsort(results)
        d = []
        for i in range(len(s_iou)):
            id = ids[s_iou[i]]
            res = results[s_iou[i]]
            d.append([id, res])
            pd.DataFrame(d, columns=["ID", "METRIC_SCORE"]).to_csv("gt_vs_oof.csv", index=False)

    return np.array(results).mean() 
Example 7
Source File: generic.py    From DeTTECT with GNU General Public License v3.0 6 votes vote down vote up
def calculate_score(list_detections, zero_value=0):
    """
    Calculates the average score in the given list which may contain multiple detection dictionaries
    :param list_detections: list
    :param zero_value: the value when no scores are there, default 0
    :return: average score
    """
    avg_score = 0
    number = 0
    for v in list_detections:
        score = get_latest_score(v)
        if score is not None and score >= 0:
            avg_score += score
            number += 1

    avg_score = int(round(avg_score / number, 0) if number > 0 else zero_value)
    return avg_score 
Example 8
Source File: awd_lstm_utils.py    From end2end-asr-pytorch with MIT License 6 votes vote down vote up
def calculate_lm_score(seq, lm, id2label):
    """
    seq: (1, seq_len)
    id2label: map
    """
    # print(seq)
    # for char in seq[0]:
    #     print(char.item())
    seq_str = "".join(id2label[char.item()] for char in seq[0]).replace(constant.PAD_CHAR,"").replace(constant.SOS_CHAR,"").replace(constant.EOS_CHAR,"")
    seq_str = seq_str.replace("  ", " ")
    if seq_str == "":
        return -999
        
    score = lm.evaluate(seq_str)
    # print(seq_str)
    return -1 * (score / len(seq_str.split())), len(seq_str.split()) 
Example 9
Source File: SVIM_merging.py    From svim with GNU General Public License v3.0 6 votes vote down vote up
def calculate_score_insertion(main_score, translocation_distances, translocation_stds, destination_stds):
    """Calculate the score of a merged insertion or duplication detected from an insertion.
       Parameters: - main_score - score of the underlying main insertion
                   - translocation_distances - mean distance of the translocation clusters flanking the main insertion (left)
                   - translocation_stds - standard deviation of the translocation clusters flanking the main insertion (left)
                   - destination_stds - standard deviations of the left and right translocation destinations"""
    #scale translocation distance to [0, 1] range
    td0 = max(0, 100 - translocation_distances[0]) / 100
    td1 = max(0, 100 - translocation_distances[1]) / 100

    #scale translocation std to [0, 1] range
    ts0 = max(0, 100 - translocation_stds[0]) / 100
    ts1 = max(0, 100 - translocation_stds[1]) / 100

    #scale destination stds to [0, 1] range
    ds0 = max(0, 100 - destination_stds[0]) / 100
    ds1 = max(0, 100 - destination_stds[1]) / 100

    #calculate final score as product of components
    product = td0 * td1 * ts0 * ts1 * ds0 * ds1
    final_score = pow(product, 1/6) * main_score
    return final_score 
Example 10
Source File: calculations.py    From cvsslib with GNU Lesser General Public License v3.0 6 votes vote down vote up
def calculate_modified_impact_sub_score(scope: ModifiedScope,
                                        modified_conf: ModifiedConfidentialityImpact,
                                        modified_integ: ModifiedIntegrityImpact,
                                        modified_avail: ModifiedAvailabilityImpact,
                                        conf_req: ConfidentialityRequirement,
                                        integ_req: IntegrityRequirement,
                                        avail_req: AvailabilityRequirement):
    modified = min(
        1 -
        (1 - modified_conf * conf_req) *
        (1 - modified_integ * integ_req) *
        (1 - modified_avail * avail_req),
        D("0.915")
    )

    if scope == ModifiedScope.UNCHANGED.value:
        return IMPACT_UNCHANGED_COEFFECIENT * modified
    else:
        return IMPACT_CHANGED_COEFFECIENT * (modified - D("0.029")) - D("3.25") * D(math.pow(modified - D(0.02), 15)) 
Example 11
Source File: dummy_scoring_container.py    From watcher with Apache License 2.0 6 votes vote down vote up
def calculate_score(self, features):
        LOG.debug('Calculating score, features: %s', features)

        # Basic input validation
        try:
            flist = jsonutils.loads(features)
        except Exception as e:
            raise ValueError(_('Unable to parse features: %s') % e)
        if type(flist) is not list:
            raise ValueError(_('JSON list expected in feature argument'))
        if len(flist) < 1:
            raise ValueError(_('At least one feature is required'))

        # Calculate the result
        result = self._aggregate_function(flist)

        # Return the aggregated result
        return jsonutils.dumps([result]) 
Example 12
Source File: basic_consolidation.py    From watcher with Apache License 2.0 6 votes vote down vote up
def calculate_score_instance(self, instance):
        """Calculate Score of virtual machine

        :param instance: the virtual machine
        :return: score
        """
        instance_cpu_utilization = self.get_instance_cpu_usage(instance)
        if instance_cpu_utilization is None:
            LOG.error(
                "No values returned by %(resource_id)s "
                "for %(metric_name)s", dict(
                    resource_id=instance.uuid,
                    metric_name='instance_cpu_usage'))
            instance_cpu_utilization = 100

        total_cores_used = instance.vcpus * (instance_cpu_utilization / 100.0)

        return self.calculate_weight(instance, total_cores_used, 0, 0) 
Example 13
Source File: calculations.py    From cvsslib with GNU Lesser General Public License v3.0 6 votes vote down vote up
def calculate_base_score(run_calculation, scope: Scope, privilege: PrivilegeRequired):
    impact_sub_score = run_calculation(calculate_impact_sub_score)

    if impact_sub_score <= 0:
        return 0
    else:

        override = {}
        if scope == Scope.CHANGED.value:
            # Ok, so the privilege enum needs slightly different values depending on the scope. God damn.
            modified_privilege = PrivilegeRequired.extend("PrivilegeRequired", {"LOW": D("0.68"), "HIGH": D("0.50")})
            privilege = getattr(modified_privilege, PrivilegeRequired(privilege).name)
            override[PrivilegeRequired] = privilege.value

        exploitability_sub_score = run_calculation(calculate_exploitability_sub_score, override=override)

        combined_score = impact_sub_score + exploitability_sub_score

        if scope == Scope.CHANGED.value:
            return roundup(min(D("1.08") * combined_score, 10))
        else:
            return roundup(min(combined_score, 10)) 
Example 14
Source File: scrabble.py    From Scrabble with MIT License 6 votes vote down vote up
def calculate_word_score(self):
        #Calculates the score of a word, allowing for the impact by premium squares.
        global LETTER_VALUES, premium_spots
        word_score = 0
        for letter in self.word:
            for spot in premium_spots:
                if letter == spot[0]:
                    if spot[1] == "TLS":
                        word_score += LETTER_VALUES[letter] * 2
                    elif spot[1] == "DLS":
                        word_score += LETTER_VALUES[letter]
            word_score += LETTER_VALUES[letter]
        for spot in premium_spots:
            if spot[1] == "TWS":
                word_score *= 3
            elif spot[1] == "DWS":
                word_score *= 2
        self.player.increase_score(word_score) 
Example 15
Source File: stemmedsynword.py    From mishkal with GNU General Public License v3.0 6 votes vote down vote up
def calculate_score(self, ):
        """
        Recalculate score.
        @return: nothing
        @rtype: void
        """
        self.score =  0
        
        # the score is calculated
        #
        # syntaxic relations
        self.score =  len(self.next)*10 #self.has_next()*10
        self.score +=  len(self.previous)*10#(self.previous>0)*10
        self.score +=  len(self.sem_previous)*100 #(self.sem_previous>0)
        self.score +=  len(self.sem_next)*100 # self.has_sem_next()*100 
        self.score +=  round(math.log(self.freq+1), 2)
        self.score +=  self.is_stopword()*50
        self.add_syntax("Scr:"+str(self.score)) 
Example 16
Source File: multisegbeam.py    From sgnmt with Apache License 2.0 6 votes vote down vote up
def calculate_score(self, pred_weights, defaults = []):
        """Calculates the full word score for this continuation using 
        the predictor stub scores.
        
        Args:
            pred_weights (list): Predictor weights. Length of this list
                                 must match the number of stubs
            defaults (list): Score which should be used if a predictor
                             stub is set to None
        
        Returns:
            float. Full score of this continuation, or an optimistic
            estimate if the continuation is not complete.
        """
        return sum(map(lambda x: x[0]*x[1],
                       zip(pred_weights,
                           [s.score if s else defaults[pidx]
                                  for pidx, s in enumerate(self.pred_stubs)]))) 
Example 17
Source File: boundary_utils.py    From anomalydetector with MIT License 6 votes vote down vote up
def calculate_anomaly_score(value, expected_value, unit, is_anomaly):
    if not is_anomaly:
        return 0.0

    distance = np.abs(expected_value - value)
    margins = [calculate_margin(unit, i) for i in range(101)][::-1]
    lb = bisect.bisect_left(margins, distance)

    if lb == 0:
        return 0
    elif lb >= 100:
        return 1.0
    else:
        a, b = margins[lb-1], margins[lb]
        score = lb - 1 + (distance - a) / (b - a)

    return score / 100.0 
Example 18
Source File: DecodeGreedyCoverage.py    From shuca with Apache License 2.0 5 votes vote down vote up
def CalculateScore(self, term_vector, weight):
        score = 0
        for key, value in term_vector.items():
            score = score + weight[key]
        return score 
Example 19
Source File: core.py    From antismash with GNU Affero General Public License v3.0 5 votes vote down vote up
def calculate_synteny_score(hitgroups: Dict[int, List[int]],
                            hitpositions: List[Tuple[int, int]],
                            core_genes_found: List[bool]) -> int:
    """ Calculate the synteny score of a ranking

        Scores will only be non-zero if more than one hit exists.
        Each query and each hit can only be considered once for scoring.

        Arguments:
            hitgroups: a dictionary mapping each unique Query index to
                               a list of Subject indices that hit that Query
            hitpositions: a list of Query, Subject index pairs ordered by best pairing
            core_genes_found: a list of booleans for each pair in hitpositions,
                                representing whether a core gene was found in
                                that pairing

        Returns:
            a int representing the synteny score
    """
    scored_queries = set()  # type: Set[int]
    scored_hits = set()  # type: Set[int]
    synteny_score = 0
    for i, pos in enumerate(hitpositions[:-1]):
        query, subject = pos
        next_query, next_subject = hitpositions[i + 1]
        # Check if a gene homologous to this gene has already been
        # scored for synteny in the previous entry
        if subject in hitgroups[next_query] or query in scored_queries or subject in scored_hits:
            continue
        if (abs(query - next_query) < 2) and abs(query - next_query) == abs(subject - next_subject):
            synteny_score += 1
            if core_genes_found[i] or core_genes_found[i + 1]:
                synteny_score += 1
            scored_queries.add(query)
            scored_hits.add(subject)
    return synteny_score 
Example 20
Source File: 24_03_Trim.py    From Coursera-Bioinformatics with GNU General Public License v3.0 5 votes vote down vote up
def calculateLinearScore(self, peptide, spectrumDict):
        theoSpectrumDict = self.LinearSpectrumDict(peptide)
        score = 0
        for s, v in theoSpectrumDict.items():
            v0 = spectrumDict.get(s, 0)
            if v0 >= v:
                score += v
            else:
                score += v0
        return score 
Example 21
Source File: 24_02_LinearScore.py    From Coursera-Bioinformatics with GNU General Public License v3.0 5 votes vote down vote up
def calculateScore(self, peptide, spectrum):
        theoSpectrumDict = self.LinearSpectrumDict(peptide)
        score = 0
        spectrumDict = dict()
        for s in spectrum:
            spectrumDict[s] = spectrumDict.get(s, 0) + 1
        for s, v in theoSpectrumDict.items():
            v0 = spectrumDict.get(s, 0)
            if v0 >= v:
                score += v
            else:
                score += v0
        return score 
Example 22
Source File: metric.py    From torchgan with MIT License 5 votes vote down vote up
def calculate_score(self, x):
        r"""
        Subclasses must override this function and provide their own score calculation.

        :raises NotImplementedError: If the subclass doesn't override this function.
        """
        raise NotImplementedError 
Example 23
Source File: score.py    From BIGSI with MIT License 5 votes vote down vote up
def calculate_score(self, score_counter, convert):
        max_score = copy.copy(self.MATCH * sum(score_counter["1"]))
        min_score = copy.copy(max_score)
        mean_score = copy.copy(min_score)

        SNP_t = 31 + self.kmer_adjust  # correct for the 'remove_short_ones'
        max_total_N_snps = 0
        min_total_N_snps = 0
        for i in score_counter["0"]:
            min_N_snps = float(i) / SNP_t
            max_N_snps = (i - SNP_t) + 1
            if max_N_snps < min_N_snps:
                max_N_snps = min_N_snps
            max_total_N_snps += max_N_snps
            min_total_N_snps += min_N_snps
            mean_N_snps = min_N_snps + 0.05 * max_N_snps

            max_penalty = self.MISMATCH * (max_N_snps)
            min_penalty = self.MISMATCH * (min_N_snps)
            mean_penalty = self.MISMATCH * (mean_N_snps)

            points_for_max = self.MATCH * (i - max_penalty)
            points_for_min = self.MATCH * (i - min_penalty)
            points_for_mean = self.MATCH * (i - mean_penalty)

            max_score = round(max_score - min_penalty + points_for_min, 2)
            min_score = round(min_score - max_penalty + points_for_max, 2)
            mean_score = round(mean_score - mean_penalty + points_for_mean, 2)

        return {
            "score": round(mean_score * convert, 2),
            "min_score": round(min_score * convert, 2),
            "max_score": round(max_score * convert, 2),
            "max_mismatches": math.ceil(max_total_N_snps),
            "min_mismatches": math.floor(min_total_N_snps),
            "mismatches": math.ceil(
                math.ceil(min_total_N_snps) + (0.05 * math.floor(max_total_N_snps))
            ),
        } 
Example 24
Source File: model.py    From flow-gan with MIT License 5 votes vote down vote up
def calculate_inception_and_mode_score(self):
    #to get mode scores add code to load your favourite mnist classifier in inception_score.py
    if self.dataset_name == "mnist": 
      return [0.0, 0.0, 0.0, 0.0]
    sess = self.sess
    all_samples = []
    for i in range(18):
        if self.prior == "uniform":
          batch_z = np.random.uniform(-1, 1, [self.batch_size, self.z_dim]) \
              .astype(np.float32)
        elif self.prior == "logistic":
          batch_z = np.random.logistic(loc=0.,scale=1.0,size=[self.batch_size, self.z_dim]) \
              .astype(np.float32)
        elif self.prior == "gaussian":
          batch_z = np.random.normal(0.0, 1.0, size=(self.batch_size , self.z_dim))
        else:
          print("ERROR: Unrecognized prior...exiting")
          exit(-1)
        samples_curr = self.sess.run(
            [self.sampler],
            feed_dict={
                self.z: batch_z,}
          )
        all_samples.append(samples_curr[0])
    all_samples = np.concatenate(all_samples, axis=0)
    # return all_samples
    all_samples = (all_samples*255.).astype('int32')
    
    return inception_score.get_inception_and_mode_score(list(all_samples), sess=sess) 
Example 25
Source File: global_optimization.py    From DVCNN_Lane_Detection with Apache License 2.0 5 votes vote down vote up
def calculate_rois_score(self):
        """
        Calculate the each rois' score according the roi length and angle
        :return:
        """
        merged_roi_list = self.__merge_rois_by_wlink(self.__rois)
        result = []
        for index, roi in enumerate(merged_roi_list):
            lane_length = roi.get_roi_line_length()
            top_image_height = 350.0
            rho = roi.get_roi_line_angle()
            result.append((roi, 0.7*self.__calculate_wlen_l(s_l=lane_length, h=top_image_height) +
                           0.3*self.__calculate_rho_l(rho=rho)))
        return result 
Example 26
Source File: FunctionCandidate.py    From smda with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def calculateScore(self):
        score = 0
        score += 10000 if self.is_symbol else 0
        score += 1000 if self.is_stub else 0
        score += 100 if self.lang_spec is not None else 0
        score += self.getFunctionStartScore()
        num_call_refs = len(self.call_ref_sources)
        if num_call_refs >= 10:
            call_ref_score = 10 + int(num_call_refs / 10)
        else:
            call_ref_score = num_call_refs
        score += 10 * call_ref_score
        score += 1 if self.alignment else 0
        return score 
Example 27
Source File: metric.py    From dsb2018_topcoders with MIT License 5 votes vote down vote up
def calculate_cell_score_kaggle(y_true, y_pred, num_threads=32):
    yps = []
    for m in range(len(y_true)):
        yps.append((y_true[m].copy(), y_pred[m].copy()))
    pool = Pool(num_threads)
    results = pool.map(score_kaggle, yps)
    return np.mean(results) 
Example 28
Source File: tip_pos_tagger.py    From yelp with GNU Lesser General Public License v2.1 5 votes vote down vote up
def calculate_word_score(self, tagged_word):

        """
        Takes a tagged word (in the form of a pair (word, tag)) and returns the
        score associated to that word. In other words it returns how positive
        or negative the word is in the range [-1, 1] where -1 is the most
        negative, 1 is the most positive and 0 is neutral. The tag refers to the
        part of speech tag associated to the word, i.e. noun, verb,
        adjective, etc.

        :rtype : float
        :param tagged_word: the word from which we want the score and its part
        of speech tag
        :return: a float number that represents how positive or negative is the
        word
        """
        word = tagged_word[0].lower()
        tag = tagged_word[1]

        if tag.startswith('JJ'):
            tag = 'a'
        else:
            return 0

        dict_word = tag + '/' + word
        total_score = 0

        if dict_word in self.sentiment_words:
            score = self.sentiment_words[dict_word]
            total_score = score[0] - score[1]

        return total_score 
Example 29
Source File: fuzzy.py    From aws-shell with Apache License 2.0 5 votes vote down vote up
def calculate_score(search_string, word):
    """Calculate how well the search string matches the word."""
    # See the module docstring for a high level description
    # of what we're trying to do.
    # * If the search string is larger than the word, we know
    #   immediately that this can't be a match.
    if len(search_string) > len(word):
        return 0
    original_word = word
    score = 1
    search_index = 0
    while True:
        scale = 1.0
        search_char = search_string[search_index]
        i = word.find(search_char)
        if i < 0:
            return 0
        if i > 0 and word[i - 1] == '-':
            scale = 0.95
        else:
            scale = 1 - (i / float(len(word)))
        score *= scale
        word = word[i + 1:]
        search_index += 1
        if search_index >= len(search_string):
            break
    # The more characters that matched the word, the better
    # so prefer more complete matches.
    completion_scale = 1 - (len(word) / float(len(original_word)))
    score *= completion_scale
    return score 
Example 30
Source File: SVIM_clustering.py    From svim with GNU General Public License v3.0 5 votes vote down vote up
def calculate_score(cluster, std_span, std_pos, span, type):
    if std_span == None or std_pos == None:
        span_deviation_score = 0
        pos_deviation_score = 0
    else:
        span_deviation_score = 1 - min(1, std_span / span)
        pos_deviation_score = 1 - min(1, std_pos / span)

    if type == "INV":
        directions = [signature.direction for signature in cluster]
        direction_counts = [0, 0, 0, 0, 0]
        for direction in directions:
            if direction == "left_fwd":
                direction_counts[0] += 1
            if direction == "left_rev":
                direction_counts[1] += 1
            if direction == "right_fwd":
                direction_counts[2] += 1
            if direction == "right_rev":
                direction_counts[3] += 1
            if direction == "all":
                direction_counts[4] += 1
        left_signatures = direction_counts[0] + direction_counts[1]
        right_signatures = direction_counts[2] + direction_counts[3]
        valid_signatures = min(left_signatures, right_signatures) + direction_counts[4]
        num_signatures = min(80, valid_signatures)
    else:
        num_signatures = min(80, len(cluster))
    return num_signatures + span_deviation_score * (num_signatures / 8) + pos_deviation_score * (num_signatures / 8) 
Example 31
Source File: press_model.py    From aca with MIT License 5 votes vote down vote up
def calculate_press_score(t_author_press):
    press_list = []
    for k,v in t_author_press.items():
        press_list.extend(v)

    c_press = Counter(press_list)
    #len_interest = len(interest)
    press_score = {}
    for k,v in c_press.items():
        num = math.exp(-1/v)
        press_score.setdefault(k,num)
    return press_score,c_press 
Example 32
Source File: press_model.py    From aca with MIT License 5 votes vote down vote up
def calculate_interest_score(interest_count,length):

    interest_idf = {}
    for k,v in interest_count.items():
        idf = math.exp(-1/v**3)
        interest_idf.setdefault(k,idf)
    return interest_idf 
Example 33
Source File: forms.py    From hypha with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def calculate_score(self, data):
        scores = list()

        for field in self.instance.score_fields:
            score = data.get(field.id)[1]
            # Include NA answers as 0.
            if score == NA:
                score = 0
            scores.append(score)

        try:
            return sum(scores) / len(scores)
        except ZeroDivisionError:
            return NA 
Example 34
Source File: model.py    From ProductGenius with MIT License 5 votes vote down vote up
def calculate_pg_score(self, pg_average=3.0, C=10):
        """Calculate Product Genius score with bayesian average"""

        stars, n_scores = self.get_total_stars()
        pg_score = (C * pg_average + stars)/(C + n_scores)

        return pg_score 
Example 35
Source File: model.py    From ProductGenius with MIT License 5 votes vote down vote up
def calculate_score_distribution(self):
        """Calculates the distribution of 1,2,3,4,5 star reviews"""

        distribution = [0, 0, 0, 0, 0]

        for review in self.reviews:
            distribution[review.score - 1] += 1

        return distribution 
Example 36
Source File: nlp.py    From ReSAN with Apache License 2.0 5 votes vote down vote up
def calculate_idx_seq_f1_score(input_idx_seq, label_idx_seq, recall_factor=1.):
    assert len(input_idx_seq) > 0 and len(label_idx_seq)>0
    # recall
    recall_counter = sum(1 for label_idx in label_idx_seq if label_idx in input_idx_seq)
    precision_counter = sum(1 for input_idx in input_idx_seq if input_idx in label_idx_seq)

    recall = 1.0*recall_counter/ len(label_idx_seq)
    precision = 1.0*precision_counter / len(input_idx_seq)

    recall = recall/recall_factor

    if recall + precision <= 0.:
        return 0.
    else:
        return 2.*recall*precision / (recall + precision) 
Example 37
Source File: problem_335.py    From daily-coding-problem with MIT License 5 votes vote down vote up
def calculate_score(node: str, g: Graph, page_scores: Dict):
    agg_score = 0
    for other in g.edges:
        if node in g.edges[other]:
            agg_score += page_scores[other] / len(g.edges[other])

    score = ((1 - DAMPING) / len(g.edges)) + (DAMPING * agg_score)
    return score 
Example 38
Source File: lstm.py    From user-behavior-anomaly-detector with MIT License 5 votes vote down vote up
def calculate_score(self, real, predicted, score):
        rmse = math.sqrt(mean_squared_error(real, predicted))
        # total = helpers.sigmoid(1/rmse * scores[i]) * 100
        total = round(rmse * score / 100, 2)
        return total 
Example 39
Source File: Naive_algo.py    From SKF-Chatbot with GNU Affero General Public License v3.0 5 votes vote down vote up
def calculate_class_score(Question, class_name, show_details=True):
    score = 0
    # tokenize each word in our new Question
    for word in nltk.word_tokenize(Question):
        # check to see if the stem of the word is in any of our classes
        if stemmer.stem(word.lower()) in class_words[class_name]:
            # treat each word with same weight
            score += 1
            
            if show_details:
                print ("   match: %s" % stemmer.stem(word.lower() ))
    return score

# we can now calculate a score for a new Question 
Example 40
Source File: TrainMood.py    From QQZoneMood with MIT License 5 votes vote down vote up
def calculate_score_for_each_mood(self):
        """
        利用谷歌nima模型对图片进行评分
        paper: https://arxiv.org/abs/1709.05424
        pytorch model: https://github.com/truskovskiyk/nima.pytorch.git

        计算每条说说中图片的平均分
        对于没有图片的按均值进行填充
        :return:
        """
        # nima模型预测结果文件
        self.IMAGE_SCORE_FILE_PATH = '/Users/maicius/code/nima.pytorch/nima/result_dict.json'
        with open(self.IMAGE_SCORE_FILE_PATH, 'r', encoding='utf-8') as r:
            self.image_score_dict = json.load(r)
        self.image_score_df = pd.DataFrame(self.image_score_dict)

        mean_score = self.image_score_df[self.image_score_df['score'] != -1].mean()[0]
        self.image_score_df.loc[self.image_score_df.score == -1, 'score'] = mean_score
        tid_list = self.mood_data_df['tid'].values
        for tid in tid_list:
            scores = self.image_score_df[self.image_score_df.image.str.contains(tid)].score
            if len(scores) > 0:
                self.mood_data_df.loc[self.mood_data_df.tid == tid, 'score'] = round(scores.mean(), 2)
        self.mood_data_df.fillna(mean_score)
        print("score shape:", self.mood_data_df.shape)
        self.mood_data_df.to_csv(self.MOOD_DATA_SCORE_FILE_NAME) 
Example 41
Source File: pyspantask.py    From py-span-task with GNU General Public License v2.0 5 votes vote down vote up
def calculate_score(s, t, allow_sloppy_spelling, heed_order):
  # Allow one typo: omission, addition, substitution of a character, or
  # transposition of two characters.
  if allow_sloppy_spelling:
    errors_allowed = 1
  else:
    errors_allowed = 0
  # Collect correctly recalled words:
  hits = []
  for w1 in s:
    for w2 in t:
      if damerau_levenshtein(w1,w2) <= errors_allowed:
        hits.append(w2)
        continue
  # Remove duplicates from list of hits (although duplicates should
  # not occur when the experiment is properly configured):
  seen = set()
  seen_add = seen.add
  hits = [x for x in hits if not (x in seen or seen_add(x))]

  if heed_order:
    # Subtract points for items recalled in incorrect order:
    correct = len(t) - damerau_levenshtein(hits, t)
  else:
    correct = len(hits)

  return correct 
Example 42
Source File: evaluate.py    From object_centric_VAD with MIT License 5 votes vote down vote up
def calculate_score(loss_file,reverse,smoothing):
    if not os.path.isdir(loss_file):
        loss_file_path = loss_file
    else:
        optical_result = compute_auc(loss_file,reverse,smoothing)
        loss_file_path = optical_result.loss_file
        print('##### optimal result and model = {}'.format(optical_result))
    dataset, psnr_records, gt = load_psnr_gt(loss_file=loss_file_path)

    # the number of videos
    num_videos = len(psnr_records)

    scores = np.array([], dtype=np.float32)
    labels = np.array([], dtype=np.int8)
    # video normalization
    for i in range(num_videos):
        distance = psnr_records[i]

        distance = (distance - distance.min()) / (distance.max() - distance.min())
        if reverse:
            distance=1-distance
        if smoothing:
            distance = score_smoothing(distance)
        scores = np.concatenate((scores[:], distance[DECIDABLE_IDX:-DECIDABLE_IDX]), axis=0)
        labels = np.concatenate((labels[:], gt[i][DECIDABLE_IDX:-DECIDABLE_IDX]), axis=0)

    mean_normal_scores = np.mean(scores[labels == 0])
    mean_abnormal_scores = np.mean(scores[labels == 1])
    print('mean normal scores = {}, mean abnormal scores = {}, '
          'delta = {}'.format(mean_normal_scores, mean_abnormal_scores, mean_normal_scores - mean_abnormal_scores)) 
Example 43
Source File: shutit_exam.py    From shutit with MIT License 5 votes vote down vote up
def calculate_score(self):
		max_score   = 0.0
		total_score = 0.0
		for stage in self.stages:
			max_score += stage.difficulty
			# If they succeeded, start with the diffulty score (100%)
			if stage.result == 'OK':
				stage.score = stage.difficulty
				for item in range(0,stage.num_resets):
					item = item # pylint
					stage.score = stage.score - (stage.score * stage.reduction_per_reset)
				for item in range(0,stage.num_hints):
					stage.score = stage.score - (stage.score * stage.reduction_per_hint)
				total_time = stage.end_time - stage.start_time
				total_time -= stage.grace_period
				if total_time > 0:
					num_minutes = total_time / 60
					num_seconds = total_time % 60
					num_minutes = num_minutes + (num_seconds / 60)
					while num_minutes > 1:
						num_minutes -= 1
						stage.score = stage.score - (stage.score * stage.reduction_per_minute)
					if num_minutes > 0:
						stage.score = stage.score - (stage.score * stage.reduction_per_minute * num_minutes)
				total_score = total_score + stage.score
			else:
				stage.score = 0
		self.final_score = total_score / max_score * 100.00
		return self.final_score 
Example 44
Source File: utils.py    From torchbench with Apache License 2.0 5 votes vote down vote up
def calculate_inception_score(
    sample_dataloader,
    test_dataloader,
    device="cuda",
    num_images=50000,
    splits=10,
):
    """Calculate the inception score for a model's samples.

    Args:
        sample_dataloader: Dataloader for the generated image samples from the
            model.
        test_dataloader: Dataloader for the real images from the dataset to
            compare to.
        device: to perform the evaluation (e.g. 'cuda' for GPU).
        num_images: number of images to evaluate.
        splits: nu,ber of splits to perform for the evaluation.

    Returns:
        dict: Dictionary with key being the metric name, and values being the
            metric scores.
    """
    inception_model = InceptionScore(device=device)
    inception_model.eval()

    preds = np.zeros((num_images, 1000))

    for i, batch in enumerate(sample_dataloader, 0):
        batch = batch.to(device=device)
        batchv = Variable(batch)
        batch_size_i = batch.size()[0]
        predictions = inception_model(batchv)
        start = i * test_dataloader.batch_size
        n_predictions = len(preds[start : start + batch_size_i])
        preds[start : start + batch_size_i] = predictions[:n_predictions]

    split_scores = []

    for k in range(splits):
        part = preds[
            k * (num_images // splits) : (k + 1) * (num_images // splits), :
        ]
        py = np.mean(part, axis=0)
        scores = []
        for i in range(part.shape[0]):
            pyx = part[i, :]
            scores.append(entropy(pyx, py))
        split_scores.append(np.exp(np.mean(scores)))

    return {"Inception Score": np.mean(split_scores)} 
Example 45
Source File: xblock_jupyter_graded.py    From jupyter-edx-grader-xblock with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def calculate_score(self):
        return Score(raw_earned=self.student_score, 
            raw_possible=self.raw_possible)

    # ----------- Views ----------- 
Example 46
Source File: mc_perceptron.py    From multiclass_perceptron with MIT License 5 votes vote down vote up
def calculate_fbeta_score(self):
        """
        Calculates the fbeta score of the classifier by running algorithm against test set and comparing
        the output to the actual categorization.

        Calculated by taking the harmonic mean of the precision and recall values.
        """
        print "F-BETA SCORES: "
        for c in self.precision:
            self.fbeta_score[c] = 2 * ((self.precision[c] * self.recall[c]) / (self.precision[c] + self.recall[c]))
            print "%s Class F-Beta Score:", self.fbeta_score[c] 
Example 47
Source File: FeedRecordedFuture.py    From content with MIT License 5 votes vote down vote up
def calculate_indicator_score(self, risk_from_feed):
        """Calculates the Dbot score of an indicator based on its Risk value from the feed.
        Args:
            risk_from_feed (str): The indicator's risk value from the feed
        Returns:
            int. The indicator's Dbot score
        """
        dbot_score = 0
        risk_from_feed = int(risk_from_feed)
        if risk_from_feed >= self.threshold or risk_from_feed >= 65:
            dbot_score = 3
        elif risk_from_feed >= 5:
            dbot_score = 2

        return dbot_score 
Example 48
Source File: calculations.py    From cvsslib with GNU Lesser General Public License v3.0 5 votes vote down vote up
def calculate_environmental_score(run_calculation,
                                  collat_damage: CollateralDamagePotential,
                                  target_dist: TargetDistribution):
    adjusted_base_score = run_calculation(calculate_base_score, calculate_adjusted_impact)
    adjusted_temporal = run_calculation(calculate_temporal_score, adjusted_base_score)

    return round(
        (adjusted_temporal +
         (10 - adjusted_temporal) *
         collat_damage) *
        target_dist, 1
    ) 
Example 49
Source File: utils.py    From atari-representation-learning with MIT License 5 votes vote down vote up
def calculate_multiclass_f1_score(preds, labels):
    preds = torch.argmax(preds, dim=1).detach().numpy()
    labels = labels.numpy()
    f1score = compute_f1_score(labels, preds, average="weighted")
    return f1score 
Example 50
Source File: least_used.py    From workload-collocation-agent with Apache License 2.0 5 votes vote down vote up
def calculate_least_used_score(
        requested_fraction: Dict[ResourceType, float], weights: Dict[ResourceType, float]) \
        -> Tuple[Dict[ResourceType, float], float]:
    """Least used score based on requested_fraction and weigths for resources."""
    weights_sum = sum([weight for weight in weights.values()])
    free_fraction = {dim: 1.0 - fraction for dim, fraction in requested_fraction.items()}
    least_used_score = \
        sum([free_fraction * weights[dim] for dim, free_fraction in free_fraction.items()]) \
        / weights_sum
    return free_fraction, least_used_score 
Example 51
Source File: models.py    From arguman.org with GNU Affero General Public License v3.0 4 votes vote down vote up
def calculate_score(self):
        """The hot formula. Should match the equivalent function in postgres."""
        s = self.premises.exclude(user__id=self.user.id).count()
        if s < 1:
            return 0
        order = log(max(abs(s), 1), 10)
        sign = 1 if s > 0 else -1 if s < 0 else 0
        seconds = self.epoch_seconds(self.date_creation) - 1134028003
        return round(sign * order + seconds / 45000, 7) 
Example 52
Source File: app.py    From ESPN-Fantasy-Basketball with MIT License 4 votes vote down vote up
def calculate_score(team1, team2, categories, league_id):
    wins = 0
    losses = 0
    ties = 0
    won_margin = []
    lost_margin = []
    tied_margin = []

    bad_categories = ['FGMI', 'FTMI', '3PMI', 'TO', 'EJ', 'FF', 'PF', 'TF', 'DQ']

    bad_categories_idx = []
    for bad_category in bad_categories:
        try:
            bad_categories_idx.append(categories.index(bad_category))
        except ValueError:
            pass

    for idx, (a, b) in enumerate(zip(team1, team2)):
        try:
            a, b = float(a), float(b)
        except ValueError as e:
            app.logger.error('%s - %s', league_id, str(e))
            a, b = 0.0, 0.0

        # When comparing turnovers, having a smaller value is a "win".
        if idx in bad_categories_idx:
            if a < b:
                wins += 1
                won_margin.append((categories[idx], b - a))
            elif a == b:
                ties += 1
                tied_margin.append((categories[idx], b - a))
            else:
                losses += 1
                lost_margin.append((categories[idx], b - a))
        else:
            if a > b:
                wins += 1
                won_margin.append((categories[idx], round((a - b), 4)))
            elif a == b:
                ties += 1
                tied_margin.append((categories[idx], round((a - b), 4)))
            else:
                losses += 1
                lost_margin.append((categories[idx], round((a - b), 4)))
    score = (wins, losses, ties), won_margin, lost_margin, tied_margin
    return score


# Run the Flask app. 
Example 53
Source File: sascorer.py    From icml18-jtnn with MIT License 4 votes vote down vote up
def calculateScore(m):
  if _fscores is None: readFragmentScores()

  # fragment score
  fp = rdMolDescriptors.GetMorganFingerprint(m,2)  #<- 2 is the *radius* of the circular fingerprint
  fps = fp.GetNonzeroElements()
  score1 = 0.
  nf = 0
  for bitId,v in iteritems(fps):
    nf += v
    sfp = bitId
    score1 += _fscores.get(sfp,-4)*v
  score1 /= nf

  # features score
  nAtoms = m.GetNumAtoms()
  nChiralCenters = len(Chem.FindMolChiralCenters(m,includeUnassigned=True))
  ri = m.GetRingInfo()
  nBridgeheads,nSpiro=numBridgeheadsAndSpiro(m,ri)
  nMacrocycles=0
  for x in ri.AtomRings():
    if len(x)>8: nMacrocycles+=1

  sizePenalty = nAtoms**1.005 - nAtoms
  stereoPenalty = math.log10(nChiralCenters+1)
  spiroPenalty = math.log10(nSpiro+1)
  bridgePenalty = math.log10(nBridgeheads+1)
  macrocyclePenalty = 0.
  # ---------------------------------------
  # This differs from the paper, which defines:
  #  macrocyclePenalty = math.log10(nMacrocycles+1)
  # This form generates better results when 2 or more macrocycles are present
  if nMacrocycles > 0: macrocyclePenalty = math.log10(2)

  score2 = 0. -sizePenalty -stereoPenalty -spiroPenalty -bridgePenalty -macrocyclePenalty

  # correction for the fingerprint density
  # not in the original publication, added in version 1.1
  # to make highly symmetrical molecules easier to synthetise
  score3 = 0.
  if nAtoms > len(fps):
    score3 = math.log(float(nAtoms) / len(fps)) * .5

  sascore = score1 + score2 + score3

  # need to transform "raw" value into scale between 1 and 10
  min = -4.0
  max = 2.5
  sascore = 11. - (sascore - min + 1) / (max - min) * 9.
  # smooth the 10-end
  if sascore > 8.: sascore = 8. + math.log(sascore+1.-9.)
  if sascore > 10.: sascore = 10.0
  elif sascore < 1.: sascore = 1.0 

  return sascore 
Example 54
Source File: GO_Elite.py    From altanalyze with Apache License 2.0 4 votes vote down vote up
def calculate_score_for_children(tree, zscore_changed_path_db):
    temp_list = []
    child_highest_score = {}
    for entry in tree:  ###The tree is a key with one or more nodes representing a branch, chewed back, with or without children
        for item in tree[entry]: #get the children of the tree
            if item in zscore_changed_path_db:
                if filter_method == 'z-score':
                    new_item = zscore_changed_path_db[item].ZScore(), item
                    temp_list.append(new_item)
                elif filter_method == 'gene number':
                    new_item = zscore_changed_path_db[item].NumChanged(), item
                    temp_list.append(new_item)
                elif filter_method == 'combination':
                    z_score_val = zscore_changed_path_db[item].ZScore()
                    gene_num = math.log(zscore_changed_path_db[item].NumChanged(),2)
                    new_item = gene_num*z_score_val, item
                    temp_list.append(new_item)
                    #print new_item,z_score_val
                else:
                    print 'error, no filter method selected!!'
                    break
            """elif item == 'siblings_type1': #this will only occur if an parent had multiple children, none of them with nested children
                 if filter_method == 'z-score':
                    parent_item = entry[-1]
                    new_item = zscore_changed_path_db[parent_item][0], parent_item
                    temp_list.append(new_item)
                elif filter_method == 'gene number':
                    new_item = zscore_changed_path_db[parent_item][1], parent_item
                    temp_list.append(new_item)
                elif filter_method == 'combination':
                    z_score_val = zscore_changed_path_db[parent_item][0]
                    gene_num = math.log(zscore_changed_path_db[parent_item][1],2)
                    new_item = gene_num*z_score_val, parent_item
                    temp_list.append(new_item)"""
        #print new_item,z_score_val               
        if len(temp_list)> 0:  #if there is at least one nested go_path
            max_child_score = max(temp_list)[0]
            max_child_path = max(temp_list)[1]
            child_highest_score[entry]=max_child_path
            temp_list = []
    """for entry in child_highest_score:
        print entry,':',child_highest_score[entry]"""
    return child_highest_score 
Example 55
Source File: calculations.py    From cvsslib with GNU Lesser General Public License v3.0 4 votes vote down vote up
def calculate_temporal_score(base_score,
                             exploit: Exploitability,
                             remediation: RemediationLevel,
                             confidence: ReportConfidence):
    return round(base_score * exploit * remediation * confidence, 1)


# AdjustedImpact = min(10,10.41*(1-(1-ConfImpact*ConfReq)*(1-IntegImpact*IntegReq)*(1-AvailImpact*AvailReq))) 
Example 56
Source File: sascorer.py    From rl_graph_generation with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def calculateScore(m):
  if _fscores is None:
    readFragmentScores()

  # fragment score
  fp = rdMolDescriptors.GetMorganFingerprint(m,
                                             2)  #<- 2 is the *radius* of the circular fingerprint
  fps = fp.GetNonzeroElements()
  score1 = 0.
  nf = 0
  for bitId, v in iteritems(fps):
    nf += v
    sfp = bitId
    score1 += _fscores.get(sfp, -4) * v
  score1 /= nf

  # features score
  nAtoms = m.GetNumAtoms()
  nChiralCenters = len(Chem.FindMolChiralCenters(m, includeUnassigned=True))
  ri = m.GetRingInfo()
  nBridgeheads, nSpiro = numBridgeheadsAndSpiro(m, ri)
  nMacrocycles = 0
  for x in ri.AtomRings():
    if len(x) > 8:
      nMacrocycles += 1

  sizePenalty = nAtoms**1.005 - nAtoms
  stereoPenalty = math.log10(nChiralCenters + 1)
  spiroPenalty = math.log10(nSpiro + 1)
  bridgePenalty = math.log10(nBridgeheads + 1)
  macrocyclePenalty = 0.
  # ---------------------------------------
  # This differs from the paper, which defines:
  #  macrocyclePenalty = math.log10(nMacrocycles+1)
  # This form generates better results when 2 or more macrocycles are present
  if nMacrocycles > 0:
    macrocyclePenalty = math.log10(2)

  score2 = 0. - sizePenalty - stereoPenalty - spiroPenalty - bridgePenalty - macrocyclePenalty

  # correction for the fingerprint density
  # not in the original publication, added in version 1.1
  # to make highly symmetrical molecules easier to synthetise
  score3 = 0.
  if nAtoms > len(fps):
    score3 = math.log(float(nAtoms) / len(fps)) * .5

  sascore = score1 + score2 + score3

  # need to transform "raw" value into scale between 1 and 10
  min = -4.0
  max = 2.5
  sascore = 11. - (sascore - min + 1) / (max - min) * 9.
  # smooth the 10-end
  if sascore > 8.:
    sascore = 8. + math.log(sascore + 1. - 9.)
  if sascore > 10.:
    sascore = 10.0
  elif sascore < 1.:
    sascore = 1.0

  return sascore