当前位置: 首页>>代码示例>>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;未经允许,请勿转载。