Python math.inf() Examples

The following are 30 code examples of math.inf(). 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. You may also want to check out all available functions/classes of the module math , or try the search function .
Example #1
Source File: heap.py    From FATE with Apache License 2.0 6 votes vote down vote up
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 
Example #2
Source File: text_embedding_similarity_transformers.py    From driverlessai-recipes with Apache License 2.0 6 votes vote down vote up
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) 
Example #3
Source File: lazy_segment_tree.py    From Python with MIT License 6 votes vote down vote up
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) 
Example #4
Source File: SFASupervised.py    From SFA_Python with GNU General Public License v3.0 6 votes vote down vote up
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) 
Example #5
Source File: esim.py    From video_captioning_rl with MIT License 6 votes vote down vote up
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 
Example #6
Source File: listener.py    From resolwe with Apache License 2.0 6 votes vote down vote up
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 
Example #7
Source File: exchange.py    From Gemini with GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, no, entry_price, shares, exit_price=0, stop_loss=math.inf):
        """Open the position.

        :param no: A unique position id number
        :type no: int
        :param entry_price: Entry price at which shares are shorted
        :type entry_price: float
        :param shares: Number of shares to short
        :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 short position
        :rtype: short_position
        """       
        if exit_price is False: exit_price = 0
        if stop_loss is False: stop_loss = math.inf
        super().__init__(no, entry_price, shares, exit_price, stop_loss)
        self.type = 'short' 
Example #8
Source File: exchange.py    From Gemini with GNU General Public License v3.0 6 votes vote down vote up
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' 
Example #9
Source File: attribute_sets.py    From ReGraph with MIT License 6 votes vote down vote up
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) 
Example #10
Source File: attribute_sets.py    From ReGraph with MIT License 6 votes vote down vote up
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) 
Example #11
Source File: beam_decode.py    From translate with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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 
Example #12
Source File: attribute_sets.py    From ReGraph with MIT License 6 votes vote down vote up
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 
Example #13
Source File: text_explainer_utils.py    From interpret-text with MIT License 6 votes vote down vote up
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] 
Example #14
Source File: validation.py    From PandasSchema with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, min: float = -math.inf, max: float = math.inf, **kwargs):
        """
        :param min: The minimum (inclusive) value to accept
        :param max: The maximum (exclusive) value to accept
        """
        self.min = min
        self.max = max
        super().__init__(**kwargs) 
Example #15
Source File: dataclasses.py    From kipoiseq with MIT License 5 votes vote down vote up
def truncate(self, chrom_len=math.inf):
        """Truncate the interval to become valid
        """
        if self.is_valid(chrom_len):
            return self
        else:
            obj = self.copy()
            obj._start = max(self._start, 0)
            obj._end = min(self.end, chrom_len - 1)
            return obj 
Example #16
Source File: dataclasses.py    From kipoiseq with MIT License 5 votes vote down vote up
def is_valid(self, chrom_len=math.inf):
        """Check if the interval is valid
        """
        return self.start >= 0 and self.end < chrom_len 
Example #17
Source File: match.py    From map_matching with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, layer=None, way=None, cost=math.inf, path=None,
                 parent=None, skip_node=None):
        self.cost = cost
        self.path = path
        self.parent = parent
        self.layer = layer
        self.way = way
        self.skip_node = skip_node 
Example #18
Source File: SFASupervised.py    From SFA_Python with GNU General Public License v3.0 5 votes vote down vote up
def calcBestCoefficients(self, samples, transformedSignal):
        classes = {}
        for i in range(samples["Samples"]):
            if samples[i].label in classes.keys():
                classes[samples[i].label].append(transformedSignal[i])
            else:
                classes[samples[i].label] = [transformedSignal[i]]

        nSamples = len(transformedSignal)
        nClasses = len(classes.keys())
        length = len(transformedSignal[1])

        f = self.getFoneway(length, classes, nSamples, nClasses)
        f_sorted = sorted(f, reverse = True)
        best = []
        inf_index = 0

        for value in f_sorted:
            if value == -math.inf:
                index = f.index(value) + inf_index
                inf_index += 1
            else:
                index = f.index(value)
                best.append([index, value])  #NOTE Changed to indent

        return best 
Example #19
Source File: evals.py    From translate with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_perplexity(loss):
    try:
        return f"{math.pow(2, loss):.2f}"
    except OverflowError:
        return float("inf") 
Example #20
Source File: inputs.py    From trax with Apache License 2.0 5 votes vote down vote up
def bucket_by_length(generator, length_fn, boundaries, batch_sizes,
                     strict_pad_on_len=False):
  """Bucket by length, like tf.data.experimental.bucket_by_sequence_length.

  Args:
    generator: python generator to draw data from.
    length_fn: a function taking the example and returning the length.
    boundaries: a list of bucket boundaries.
    batch_sizes: a list of batch sizes.
    strict_pad_on_len: bool; if true we pad on the length dimension, dim[0]
      strictly as a multiple of boundary.

  Yields:
    An input batch, which comes from one of the buckets.
  """
  buckets = [[] for _ in range(len(batch_sizes))]
  boundaries = boundaries + [math.inf]  # Max boundary is unlimited.
  for example in generator:
    length = length_fn(example)
    # `bucket_idx` will always be < len(boundaries), since boundaries is right
    # padded by `math.inf`.
    bucket_idx = min([i for i, b in enumerate(boundaries) if length < b])
    buckets[bucket_idx].append(example)
    if len(buckets[bucket_idx]) == batch_sizes[bucket_idx]:
      batch = zip(*buckets[bucket_idx])
      boundary = boundaries[bucket_idx] - 1
      boundary = None if boundary == math.inf else boundary
      padded_batch = tuple(
          pad_to_max_dims(x, boundary, strict_pad_on_len) for x in batch)
      yield padded_batch
      buckets[bucket_idx] = [] 
Example #21
Source File: train.py    From training_results_v0.5 with Apache License 2.0 5 votes vote down vote up
def get_perplexity(loss):
    try:
        return '{:.2f}'.format(math.pow(2, loss))
    except OverflowError:
        return float('inf') 
Example #22
Source File: text_embedding_similarity_transformers.py    From driverlessai-recipes with Apache License 2.0 5 votes vote down vote up
def fit_transform(self, X: dt.Frame, y: np.array = None):
        X.replace([None, math.inf, -math.inf], self._repl_val)
        return self.transform(X) 
Example #23
Source File: core.py    From google-music-scripts with MIT License 5 votes vote down vote up
def get_local_songs(
	paths,
	*,
	filters=None,
	max_depth=math.inf,
	exclude_paths=None,
	exclude_regexes=None,
	exclude_globs=None
):
	logger.log('NORMAL', "Loading local songs")

	local_songs = [
		filepath
		for filepath in get_filepaths(
			paths,
			max_depth=max_depth,
			exclude_paths=exclude_paths,
			exclude_regexes=exclude_regexes,
			exclude_globs=exclude_globs
		)
		if audio_metadata.determine_format(filepath) in [
			audio_metadata.FLAC,
			audio_metadata.MP3,
			audio_metadata.OggOpus,
			audio_metadata.OggVorbis,
			audio_metadata.WAVE,
		]
	]

	logger.info("Found {} local songs", len(local_songs))

	matched_songs = filter_metadata(local_songs, filters)

	return matched_songs 
Example #24
Source File: compiler.py    From ibis with Apache License 2.0 5 votes vote down vote up
def spark_rewrites_is_inf(expr):
    arg = expr.op().arg
    return (arg == ibis.literal(math.inf)) | (arg == ibis.literal(-math.inf)) 
Example #25
Source File: carnival_aco.py    From Grokking-Artificial-Intelligence-Algorithms with GNU Affero General Public License v3.0 5 votes vote down vote up
def __init__(self, number_of_ants_factor):
        self.number_of_ants_factor = number_of_ants_factor
        # Initialize the array for storing ants
        self.ant_colony = []
        # Initialize the 2D matrix for pheromone trails
        self.pheromone_trails = []
        # Initialize the best distance in swarm
        self.best_distance = math.inf
        self.best_ant = None

    # Initialize ants at random starting locations 
Example #26
Source File: drone_pso.py    From Grokking-Artificial-Intelligence-Algorithms with GNU Affero General Public License v3.0 5 votes vote down vote up
def get_best_in_swarm(self):
        best = math.inf
        best_particle = None
        for p in self.swarm:
            p.update_fitness()
            if p.fitness < best:
                best = p.fitness
                best_particle = p
        return best_particle

    # Run the PSO lifecycle for every particle in the swarm 
Example #27
Source File: drone_pso.py    From Grokking-Artificial-Intelligence-Algorithms with GNU Affero General Public License v3.0 5 votes vote down vote up
def __init__(self, x, y, inertia, cognitive_constant, social_constant):
        self.x = x
        self.y = y
        self.fitness = math.inf
        self.velocity = 0
        self.best_x = x
        self.best_y = y
        self.best_fitness = math.inf
        self.inertia = inertia
        self.cognitive_constant = cognitive_constant
        self.social_constant = social_constant
        self.update_fitness()

    # Get the fitness of the particle 
Example #28
Source File: ml_util.py    From leap with MIT License 5 votes vote down vote up
def none_to_infty(bounds):
    if bounds is None:
        bounds = -math.inf, math.inf
    lb, ub = bounds
    if lb is None:
        lb = -math.inf
    if ub is None:
        ub = math.inf
    return lb, ub 
Example #29
Source File: col_exporter.py    From DragonFF with GNU General Public License v3.0 5 votes vote down vote up
def _update_bounds(obj):
        self = col_exporter

        if self.coll.bounds is None:
            self.coll.bounds = [
                [-math.inf] * 3,
                [math.inf] * 3
            ]

        dimensions = obj.dimensions
            
        # Empties don't have a dimensions array
        if obj.type == 'EMPTY':
            
            # Multiplied by 2 because empty_display_size is a radius
            dimensions = [
                max(x * obj.empty_display_size * 2 for x in obj.scale)] * 3
        
        upper_bounds = [x + (y/2) for x, y in zip(obj.location, dimensions)]
        lower_bounds = [x - (y/2) for x, y in zip(obj.location, dimensions)]

        self.coll.bounds = [
            [max(x, y) for x,y in zip(self.coll.bounds[0], upper_bounds)],
            [min(x, y) for x,y in zip(self.coll.bounds[1], lower_bounds)]
        ]

    ####################################################### 
Example #30
Source File: heap.py    From FATE with Apache License 2.0 5 votes vote down vote up
def cal_score(self):
        """
        X^2 = ∑∑(A_ij - E_ij )^2 / E_ij
        where E_ij = (N_i / N) * C_j. N is total count of merged bucket, N_i is the total count of ith bucket
        and C_j is the count of jth label in merged bucket.
        A_ij is number of jth label in ith bucket.
        """

        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

        c1 = self.left_bucket.event_count + self.right_bucket.event_count
        c0 = self.left_bucket.non_event_count + self.right_bucket.non_event_count

        if c1 == 0 or c0 == 0:
            self.score = - math.inf
            return

        e_left_1 = (self.left_bucket.total_count / self.total_count) * c1
        e_left_0 = (self.left_bucket.total_count / self.total_count) * c0
        e_right_1 = (self.right_bucket.total_count / self.total_count) * c1
        e_right_0 = (self.right_bucket.total_count / self.total_count) * c0

        chi_square = np.square(self.left_bucket.event_count - e_left_1) / e_left_1 + \
                     np.square(self.left_bucket.non_event_count - e_left_0) / e_left_0 + \
                     np.square(self.right_bucket.event_count - e_right_1) / e_right_1 + \
                     np.square(self.right_bucket.non_event_count - e_right_0) / e_right_0
        LOGGER.debug("chi_sqaure: {}".format(chi_square))

        self.score = chi_square