當前位置: 首頁>>代碼示例>>Python>>正文


Python math.inf方法代碼示例

本文整理匯總了Python中math.inf方法的典型用法代碼示例。如果您正苦於以下問題:Python math.inf方法的具體用法?Python math.inf怎麽用?Python math.inf使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在math的用法示例。


在下文中一共展示了math.inf方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: _find_golden_doc

# 需要導入模塊: import math [as 別名]
# 或者: from math import inf [as 別名]
def _find_golden_doc(function, evaluation_examples):
    highest_prob_value = -math.inf
    highest_prob_index = -1
    # Find example with highest predicted prob in classification case
    # or highest prediction in regression case
    for index, row in enumerate(evaluation_examples):
        rowArr = [row]
        prediction = function(rowArr)
        if len(prediction.shape) == 2:
            prediction = prediction[0]
        # TODO: Change this to calculate multiple pred_max for each class prediction
        pred_max = max(prediction)
        if pred_max > highest_prob_value:
            highest_prob_value = pred_max
            highest_prob_index = index
    return evaluation_examples[highest_prob_index] 
開發者ID:interpretml,項目名稱:interpret-text,代碼行數:18,代碼來源:text_explainer_utils.py

示例2: __init__

# 需要導入模塊: import math [as 別名]
# 或者: from math import inf [as 別名]
def __init__(self, no, entry_price, shares, exit_price=math.inf, stop_loss=0):
        """Open the position.

        :param no: A unique position id number
        :type no: float
        :param entry_price: Entry price at which shares are longed
        :type entry_price: float
        :param shares: Number of shares to long
        :type shares: float
        :param exit_price: Price at which to take profit
        :type exit_price: float
        :param stop_loss: Price at which to cut losses
        :type stop_loss: float

        :return: A long position
        :rtype: long_position
        """

        if exit_price is False: exit_price = math.inf
        if stop_loss is False: stop_loss = 0
        super().__init__(no, entry_price, shares, exit_price, stop_loss)
        self.type = 'long' 
開發者ID:anfederico,項目名稱:Gemini,代碼行數:24,代碼來源:exchange.py

示例3: check_critical_load

# 需要導入模塊: import math [as 別名]
# 或者: from math import inf [as 別名]
def check_critical_load(self):
        """Check for critical load and log an error if necessary."""
        if self.load_avg.intervals["1m"].value > 1:
            if self.last_load_level == 1 and time.time() - self.last_load_log < 30:
                return
            self.last_load_log = time.time()
            self.last_load_level = 1
            logger.error(
                "Listener load limit exceeded, the system can't handle this!",
                extra=self._make_stats(),
            )

        elif self.load_avg.intervals["1m"].value > 0.8:
            if self.last_load_level == 0.8 and time.time() - self.last_load_log < 30:
                return
            self.last_load_log = time.time()
            self.last_load_level = 0.8
            logger.warning(
                "Listener load approaching critical!", extra=self._make_stats()
            )

        else:
            self.last_load_log = -math.inf
            self.last_load_level = 0 
開發者ID:genialis,項目名稱:resolwe,代碼行數:26,代碼來源:listener.py

示例4: similarity

# 需要導入模塊: import math [as 別名]
# 或者: from math import inf [as 別名]
def similarity(self, s1, l1, s2, l2):
        """
        :param s1: [B, t1, D]
        :param l1: [B]
        :param s2: [B, t2, D]
        :param l2: [B]
        :return:
        """
        batch_size = s1.size(0)
        t1 = s1.size(1)
        t2 = s2.size(1)
        S = torch.bmm(s1, s2.transpose(1,
                                       2))  # [B, t1, D] * [B, D, t2] -> [B, t1, t2] S is the similarity matrix from biDAF paper. [B, T1, T2]

        s_mask = S.data.new(*S.size()).fill_(1).byte()  # [B, T1, T2]
        # Init similarity mask using lengths
        for i, (l_1, l_2) in enumerate(zip(l1, l2)):
            s_mask[i][:l_1, :l_2] = 0

        s_mask = Variable(s_mask)
        S.data.masked_fill_(s_mask.data.byte(), -math.inf)
        return S 
開發者ID:ramakanth-pasunuru,項目名稱:video_captioning_rl,代碼行數:24,代碼來源:esim.py

示例5: _add_to_end_states

# 需要導入模塊: import math [as 別名]
# 或者: from math import inf [as 別名]
def _add_to_end_states(
        self, end_states: List[Tensor], min_score: float, state: Tensor, min_index: int
    ) -> Tuple[List[Tensor], float, int]:
        """
        Maintains a list of atmost `nbest` highest end states
        """
        if len(end_states) < self.nbest:
            end_states.append(state)
            # keep min_score and min_index updated
            if float(state[0]) <= min_score:
                min_score = float(state[0])
                min_index = len(end_states) - 1
        elif bool(state[0] > min_score):
            # replace worst hypo with the new one
            end_states[min_index] = state
            # find new worst hypo, keep min_score and min_index updated
            min_index = -1
            min_score = float("inf")
            for idx in range(len(end_states)):
                s = end_states[idx]
                if bool(float(s[0]) <= min_score):
                    min_index = idx
                    min_score = float(s[0])
        return end_states, min_score, min_index 
開發者ID:pytorch,項目名稱:translate,代碼行數:26,代碼來源:beam_decode.py

示例6: transform

# 需要導入模塊: import math [as 別名]
# 或者: from math import inf [as 別名]
def transform(self, X: dt.Frame):
        X.replace([None, math.inf, -math.inf], self._repl_val)
        from flair.embeddings import WordEmbeddings, BertEmbeddings, DocumentPoolEmbeddings, Sentence
        if self.embedding_name in ["glove", "en"]:
            self.embedding = WordEmbeddings(self.embedding_name)
        elif self.embedding_name in ["bert"]:
            self.embedding = BertEmbeddings()
        self.doc_embedding = DocumentPoolEmbeddings([self.embedding])
        output = []
        X = X.to_pandas()
        text1_arr = X.iloc[:, 0].values
        text2_arr = X.iloc[:, 1].values
        for ind, text1 in enumerate(text1_arr):
            try:
                text1 = Sentence(str(text1).lower())
                self.doc_embedding.embed(text1)
                text2 = text2_arr[ind]
                text2 = Sentence(str(text2).lower())
                self.doc_embedding.embed(text2)
                score = cosine_similarity(text1.get_embedding().reshape(1, -1),
                                          text2.get_embedding().reshape(1, -1))[0, 0]
                output.append(score)
            except:
                output.append(-99)
        return np.array(output) 
開發者ID:h2oai,項目名稱:driverlessai-recipes,代碼行數:27,代碼來源:text_embedding_similarity_transformers.py

示例7: fitTransformed

# 需要導入模塊: import math [as 別名]
# 或者: from math import inf [as 別名]
def fitTransformed(self, samples, wordLength, symbols, normMean):
        length = len(samples[0].data)
        transformedSignal = self.sfa.fitTransformDouble(samples, length, symbols, normMean)

        best = self.calcBestCoefficients(samples, transformedSignal)
        self.bestValues = [0 for i in range(min(len(best), wordLength))]
        self.maxWordLength = 0

        for i in range(len(self.bestValues)):
            if best[i][1] != -math.inf:
                self.bestValues[i] = best[i][0]
                self.maxWordLength = max(best[i][0] + 1, self.maxWordLength)

        self.maxWordLength += self.maxWordLength % 2
        self.sfa.maxWordLength = self.maxWordLength
        return self.sfa.transform(samples, transformedSignal) 
開發者ID:sharford5,項目名稱:SFA_Python,代碼行數:18,代碼來源:SFASupervised.py

示例8: query

# 需要導入模塊: import math [as 別名]
# 或者: from math import inf [as 別名]
def query(self, idx, l, r, a, b):  # noqa: E741
        """
        query(1, 1, N, a, b) for query max of [a,b]
        """
        if self.flag[idx] is True:
            self.st[idx] = self.lazy[idx]
            self.flag[idx] = False
            if l != r:  # noqa: E741
                self.lazy[self.left(idx)] = self.lazy[idx]
                self.lazy[self.right(idx)] = self.lazy[idx]
                self.flag[self.left(idx)] = True
                self.flag[self.right(idx)] = True
        if r < a or l > b:
            return -math.inf
        if l >= a and r <= b:  # noqa: E741
            return self.st[idx]
        mid = (l + r) // 2
        q1 = self.query(self.left(idx), l, mid, a, b)
        q2 = self.query(self.right(idx), mid + 1, r, a, b)
        return max(q1, q2) 
開發者ID:TheAlgorithms,項目名稱:Python,代碼行數:22,代碼來源:lazy_segment_tree.py

示例9: from_json

# 需要導入模塊: import math [as 別名]
# 或者: from math import inf [as 別名]
def from_json(cls, json_data):
        """Create attribute set object from json-like dictionary."""
        if "type" in json_data.keys():
            init_args = None
            if "data" in json_data.keys():
                if not (len(json_data["data"]) == 1 and
                        json_data["data"][0] is None):
                    init_args = json_data["data"]

            # JSON cannot dump tuples, so finite set of tuples is usually
            # represented as a list of lists, if we read from json list of
            # lists, we interpret them as a set of tuples
            if json_data["type"] == "FiniteSet" and init_args is not None:
                for i, element in enumerate(init_args):
                    if type(element) == list:
                        init_args[i] = tuple(element)
            if json_data["type"] == "IntegerSet" and init_args is not None:
                for i, element in enumerate(init_args):
                    if element[0] == "-inf":
                        init_args[i][0] = -math.inf
                    if element[1] == "inf":
                        init_args[i][1] = math.inf

            return getattr(sys.modules[__name__], json_data["type"])(init_args) 
開發者ID:Kappa-Dev,項目名稱:ReGraph,代碼行數:26,代碼來源:attribute_sets.py

示例10: __str__

# 需要導入模塊: import math [as 別名]
# 或者: from math import inf [as 別名]
def __str__(self):
        """String representation of IntegerSet obj."""
        interval_strs = []
        for start, end in self.intervals:
            if start > -math.inf:
                start_str = "%d" % start
            else:
                start_str = "-inf"
            if end < math.inf:
                end_str = "%d" % end
            else:
                end_str = "inf"
            if start_str != end_str:
                interval_strs.append("[" + start_str + ", " + end_str + "]")
            else:
                interval_strs.append("{" + start_str + "}")
        return ", ".join(interval_strs) 
開發者ID:Kappa-Dev,項目名稱:ReGraph,代碼行數:19,代碼來源:attribute_sets.py

示例11: to_json

# 需要導入模塊: import math [as 別名]
# 或者: from math import inf [as 別名]
def to_json(self):
        """JSON represenation of IntegerSet."""
        json_data = {}
        json_data["type"] = "IntegerSet"
        json_data["data"] = []
        for start, end in self.intervals:
            if math.isinf(-start):
                new_start = "-inf"
            else:
                new_start = start
            if math.isinf(end):
                new_end = "inf"
            else:
                new_end = end
        json_data["data"].append([new_start, new_end])

        return json_data 
開發者ID:Kappa-Dev,項目名稱:ReGraph,代碼行數:19,代碼來源:attribute_sets.py

示例12: cal_score

# 需要導入模塊: import math [as 別名]
# 或者: from math import inf [as 別名]
def cal_score(self):
        """
        gini = 1 - ∑(p_i^2 ) = 1 -(event / total)^2 - (nonevent / total)^2
        """

        self.event_count = self.left_bucket.event_count + self.right_bucket.event_count
        self.non_event_count = self.left_bucket.non_event_count + self.right_bucket.non_event_count
        if self.total_count == 0:
            self.score = -math.inf
            return

        # if self.total_count == 0 or self.left_bucket.left_bound == self.right_bucket.right_bound:
        #     self.score = -math.inf
        #     return
        merged_gini = 1 - (1.0 * self.event_count / self.total_count) ** 2 - \
                      (1.0 * self.non_event_count / self.total_count) ** 2
        self.score = merged_gini - self.left_bucket.gini - self.right_bucket.gini 
開發者ID:FederatedAI,項目名稱:FATE,代碼行數:19,代碼來源:heap.py

示例13: replace

# 需要導入模塊: import math [as 別名]
# 或者: from math import inf [as 別名]
def replace(self, expression: Expression, max_count: int=math.inf) -> Union[Expression, Sequence[Expression]]:
        """Replace all occurrences of the patterns according to the replacement rules.

        Args:
            expression:
                The expression to which the replacement rules are applied.
            max_count:
                If given, at most *max_count* applications of the rules are performed. Otherwise, the rules
                are applied until there is no more match. If the set of replacement rules is not confluent,
                the replacement might not terminate without a *max_count* set.

        Returns:
            The resulting expression after the application of the replacement rules. This can also be a sequence of
            expressions, if the root expression is replaced with a sequence of expressions by a rule.
        """
        replaced = True
        replace_count = 0
        while replaced and replace_count < max_count:
            replaced = False
            for subexpr, pos in preorder_iter_with_position(expression):
                try:
                    replacement, subst = next(iter(self.matcher.match(subexpr)))
                    result = replacement(**subst)
                    expression = functions.replace(expression, pos, result)
                    replaced = True
                    break
                except StopIteration:
                    pass
            replace_count += 1
        return expression 
開發者ID:HPAC,項目名稱:matchpy,代碼行數:32,代碼來源:many_to_one.py

示例14: query

# 需要導入模塊: import math [as 別名]
# 或者: from math import inf [as 別名]
def query(st,ql,qh,low,high,pos):
  if(ql<=low and qh>=high):
    return st[pos]
  if(ql > high or qh < low):
    return math.inf
  mid = (low + high)/2
  return min(query(st,ql,qh,low,mid,2*pos + 1),
  query(st,ql,qh,mid+1,high,2*pos + 2)) 
開發者ID:bhavinjawade,項目名稱:Advanced-Data-Structures-with-Python,代碼行數:10,代碼來源:segment_Tree.py

示例15: _postprocessing

# 需要導入模塊: import math [as 別名]
# 或者: from math import inf [as 別名]
def _postprocessing(scenario, dic_scenario_flows, graph, **kwargs):
    dic_scen_PressLevel = {}
    dic_scen_MaxViolPress = math.inf
    # copy a list of nodes
    tmp_nodes = copy.deepcopy(list(graph.nodes))
    # we now set iteratively the pressure level of a single node to its upper pressure bound and then compute the
    # unique pressure levels until we find valid pressure levels or have tested all nodes
    while tmp_nodes:
        # we have not found valid pressure levels for this scenario
        # temporary pressure levels
        dic_tmp_pressure = {}
        for node in list(graph.nodes):
            dic_tmp_pressure[node] = None
        # choose the node which pressure level is fixed to the upper pressure bound
        current_node = tmp_nodes[0]
        validation, tmp_viol = computePressureAtNode(graph=graph, node=current_node, nodeUpperBound=current_node,
            dic_scenario_flows=dic_scenario_flows[scenario], dic_node_pressure=dic_tmp_pressure, **kwargs)
        # if validation true, then we have feasible pressure levels; empty list of nodes that have to be
        # considered
        if validation:
            tmp_nodes = []
            # we have feasible pressure level and save them
            dic_scen_PressLevel = dic_tmp_pressure
            dic_scen_MaxViolPress = tmp_viol
        else:
            # remove considered entry from list of nodes that will be considered for fixing the pressure level
            tmp_nodes.remove(tmp_nodes[0])
            # we update the maximal pressure level violation
            if tmp_viol < dic_scen_MaxViolPress:
                # save currently best pressure levels
                dic_scen_PressLevel = copy.deepcopy(dic_tmp_pressure)
                dic_scen_MaxViolPress = tmp_viol

    return scenario, dic_scen_PressLevel, dic_scen_MaxViolPress 
開發者ID:FZJ-IEK3-VSA,項目名稱:FINE,代碼行數:36,代碼來源:robustPipelineSizing.py


注:本文中的math.inf方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。