Python math.log2() Examples
The following are 30
code examples of math.log2().
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 Project: flores Author: facebookresearch File: train.py License: Creative Commons Attribution Share Alike 4.0 International | 6 votes |
def train(src, tgt, train_config, savedir, databin): # expect to have 'hyperparameters', 'src', 'tgt', 'databin' in train_config os.makedirs(savedir, exist_ok=True) logpath = os.path.join(savedir, 'train.log') checkpoint = os.path.join(savedir, 'checkpoint_best.pt') if check_last_line(logpath, 'done') and os.path.exists(checkpoint): print(f"Training is finished. Best checkpoint: {checkpoint}") return cuda_visible_devices = list(range(torch.cuda.device_count())) num_visible_gpu = len(cuda_visible_devices) num_gpu = min(train_config['gpu'], 2**int(math.log2(num_visible_gpu))) cuda_devices_clause = f"CUDA_VISIBLE_DEVICES={','.join([str(i) for i in cuda_visible_devices[:num_gpu]])}" update_freq = train_config['gpu'] / num_gpu call(f"""{cuda_devices_clause} fairseq-train {databin} \ --source-lang {src} --target-lang {tgt} \ --save-dir {savedir} \ --update-freq {update_freq} \ {" ".join(train_config['parameters'])} \ | tee {logpath} """, shell=True)
Example #2
Source Project: Sets2Sets Author: HaojiHu File: Sets2Sets.py License: Apache License 2.0 | 6 votes |
def get_NDCG(groundtruth, pred_rank_list, k): count = 0 dcg = 0 for pred in pred_rank_list: if count >= k: break if groundtruth[pred] == 1: dcg += (1) / math.log2(count + 1 + 1) count += 1 idcg = 0 num_real_item = np.sum(groundtruth) num_item = int(min(num_real_item, k)) for i in range(num_item): idcg += (1) / math.log2(i + 1 + 1) ndcg = dcg / idcg return ndcg
Example #3
Source Project: angr Author: angr File: bucketizer.py License: BSD 2-Clause "Simplified" License | 6 votes |
def _accept_transition(self, state, transition): """ :param SimState state: :param tuple transition: :return: """ t = self._get_transition_dict(state) if t[transition] == 0: _l.error("Impossible: Transition %s has 0 occurrences.", transition) return True n = math.log2(t[transition]) if n.is_integer(): return True return False
Example #4
Source Project: angr Author: angr File: div_simplifier.py License: BSD 2-Clause "Simplified" License | 6 votes |
def _ail_handle_Convert(self, expr): if expr.from_bits == 128 and expr.to_bits == 64: operand_expr = self._expr(expr.operand) if isinstance(operand_expr, Expr.BinaryOp) \ and operand_expr.op == 'Mul' \ and isinstance(operand_expr.operands[1], Expr.Const) \ and isinstance(operand_expr.operands[0], Expr.BinaryOp): if operand_expr.operands[0].op in {'Shr', 'DivMod'} \ and isinstance(operand_expr.operands[0].operands[1], Expr.Const): if operand_expr.operands[0].op == 'Shr': Y = operand_expr.operands[0].operands[1].value else: Y = int(math.log2(operand_expr.operands[0].operands[1].value)) C = operand_expr.operands[1].value divisor = self._check_divisor(pow(2, 64+Y), C) if divisor: X = operand_expr.operands[0].operands[0] new_const = Expr.Const(expr.idx, None, divisor, 64) return Expr.BinaryOp(expr.idx, 'DivMod', [X, new_const], expr.signed, **expr.tags) return super()._ail_handle_Convert(expr)
Example #5
Source Project: dcgan_vae_pytorch Author: seangal File: main.py License: BSD 3-Clause "New" or "Revised" License | 6 votes |
def __init__(self,imageSize): super(_Encoder, self).__init__() n = math.log2(imageSize) assert n==round(n),'imageSize must be a power of 2' assert n>=3,'imageSize must be at least 8' n=int(n) self.conv1 = nn.Conv2d(ngf * 2**(n-3), nz, 4) self.conv2 = nn.Conv2d(ngf * 2**(n-3), nz, 4) self.encoder = nn.Sequential() # input is (nc) x 64 x 64 self.encoder.add_module('input-conv',nn.Conv2d(nc, ngf, 4, 2, 1, bias=False)) self.encoder.add_module('input-relu',nn.LeakyReLU(0.2, inplace=True)) for i in range(n-3): # state size. (ngf) x 32 x 32 self.encoder.add_module('pyramid.{0}-{1}.conv'.format(ngf*2**i, ngf * 2**(i+1)), nn.Conv2d(ngf*2**(i), ngf * 2**(i+1), 4, 2, 1, bias=False)) self.encoder.add_module('pyramid.{0}.batchnorm'.format(ngf * 2**(i+1)), nn.BatchNorm2d(ngf * 2**(i+1))) self.encoder.add_module('pyramid.{0}.relu'.format(ngf * 2**(i+1)), nn.LeakyReLU(0.2, inplace=True)) # state size. (ngf*8) x 4 x 4
Example #6
Source Project: dcgan_vae_pytorch Author: seangal File: main.py License: BSD 3-Clause "New" or "Revised" License | 6 votes |
def __init__(self, imageSize, ngpu): super(_netD, self).__init__() self.ngpu = ngpu n = math.log2(imageSize) assert n==round(n),'imageSize must be a power of 2' assert n>=3,'imageSize must be at least 8' n=int(n) self.main = nn.Sequential() # input is (nc) x 64 x 64 self.main.add_module('input-conv', nn.Conv2d(nc, ndf, 4, 2, 1, bias=False)) self.main.add_module('relu', nn.LeakyReLU(0.2, inplace=True)) # state size. (ndf) x 32 x 32 for i in range(n-3): self.main.add_module('pyramid.{0}-{1}.conv'.format(ngf*2**(i), ngf * 2**(i+1)), nn.Conv2d(ndf * 2 ** (i), ndf * 2 ** (i+1), 4, 2, 1, bias=False)) self.main.add_module('pyramid.{0}.batchnorm'.format(ngf * 2**(i+1)), nn.BatchNorm2d(ndf * 2 ** (i+1))) self.main.add_module('pyramid.{0}.relu'.format(ngf * 2**(i+1)), nn.LeakyReLU(0.2, inplace=True)) self.main.add_module('output-conv', nn.Conv2d(ndf * 2**(n-3), 1, 4, 1, 0, bias=False)) self.main.add_module('output-sigmoid', nn.Sigmoid())
Example #7
Source Project: qiskit-terra Author: Qiskit File: uc_pauli_rot.py License: Apache License 2.0 | 6 votes |
def __init__(self, angle_list, rot_axis): self.rot_axes = rot_axis # Check if angle_list has type "list" if not isinstance(angle_list, list): raise QiskitError('The angles are not provided in a list.') # Check if the angles in angle_list are real numbers for angle in angle_list: try: float(angle) except TypeError: raise QiskitError( 'An angle cannot be converted to type float (real angles are expected).') num_contr = math.log2(len(angle_list)) if num_contr < 0 or not num_contr.is_integer(): raise QiskitError( 'The number of controlled rotation gates is not a non-negative power of 2.') if rot_axis not in ('X', 'Y', 'Z'): raise QiskitError('Rotation axis is not supported.') # Create new gate. num_qubits = int(num_contr) + 1 super().__init__('ucr' + rot_axis.lower(), num_qubits, angle_list)
Example #8
Source Project: qiskit-terra Author: Qiskit File: diagonal.py License: Apache License 2.0 | 6 votes |
def __init__(self, diag): """Check types""" # Check if diag has type "list" if not isinstance(diag, list): raise QiskitError("The diagonal entries are not provided in a list.") # Check if the right number of diagonal entries is provided and if the diagonal entries # have absolute value one. num_action_qubits = math.log2(len(diag)) if num_action_qubits < 1 or not num_action_qubits.is_integer(): raise QiskitError("The number of diagonal entries is not a positive power of 2.") for z in diag: try: complex(z) except TypeError: raise QiskitError("Not all of the diagonal entries can be converted to " "complex numbers.") if not np.abs(z) - 1 < _EPS: raise QiskitError("A diagonal entry has not absolute value one.") # Create new gate. super().__init__("diagonal", int(num_action_qubits), diag)
Example #9
Source Project: qiskit-terra Author: Qiskit File: diagonal.py License: Apache License 2.0 | 6 votes |
def _dec_diag(self): """ Call to create a circuit implementing the diagonal gate. """ q = QuantumRegister(self.num_qubits) circuit = QuantumCircuit(q) # Since the diagonal is a unitary, all its entries have absolute value one and the diagonal # is fully specified by the phases of its entries diag_phases = [cmath.phase(z) for z in self.params] n = len(self.params) while n >= 2: angles_rz = [] for i in range(0, n, 2): diag_phases[i // 2], rz_angle = _extract_rz(diag_phases[i], diag_phases[i + 1]) angles_rz.append(rz_angle) num_act_qubits = int(np.log2(n)) contr_qubits = q[self.num_qubits - num_act_qubits + 1:self.num_qubits] target_qubit = q[self.num_qubits - num_act_qubits] circuit.ucrz(angles_rz, contr_qubits, target_qubit) n //= 2 return circuit # extract a Rz rotation (angle given by first output) such that exp(j*phase)*Rz(z_angle) # is equal to the diagonal matrix with entires exp(1j*ph1) and exp(1j*ph2)
Example #10
Source Project: tensorrt-utils Author: rmccorm4 File: onnx_to_tensorrt.py License: Apache License 2.0 | 5 votes |
def get_batch_sizes(max_batch_size): # Returns powers of 2, up to and including max_batch_size max_exponent = math.log2(max_batch_size) for i in range(int(max_exponent)+1): batch_size = 2**i yield batch_size if max_batch_size != batch_size: yield max_batch_size # TODO: This only covers dynamic shape for batch size, not dynamic shape for other dimensions
Example #11
Source Project: PythonClassBook Author: PythonClassRoom File: carrera.py License: GNU General Public License v3.0 | 5 votes |
def avanzar(self): return super(tractor, self).avanzar(funcion_rendimiento=math.log2)
Example #12
Source Project: Competitive_Programming Author: amitrajitbose File: PowerOfFour.py License: MIT License | 5 votes |
def isPowerOfFour(self, n: int) -> bool: return n > 0 and n == (4 ** (math.log2(n) // 2))
Example #13
Source Project: Competitive_Programming Author: amitrajitbose File: MinXorPair.py License: MIT License | 5 votes |
def minXor(arr): m = 2**31 maxbits = floor(log2(max(arr))) + 1 trie = Trie() trie.insert(arr[0], maxbits) arr.pop(0) for i in arr: m = min(m, trie.xorUtil(i, maxbits)) trie.insert(i, maxbits) return m
Example #14
Source Project: Competitive_Programming Author: amitrajitbose File: MaxXorPair.py License: MIT License | 5 votes |
def findMaximumXOR(self, nums: List[int]) -> int: try: maxbit = floor(log2(max(nums))) + 1 except: maxbit = 0 head = TrieNode() for n in nums: head = insert(head, n, maxbit) maxXor = -float('inf') for n in nums: currXor = 0 curr = head for i in range(maxbit - 1, -1, -1): bit = (n>>i) & 1 # if bit is set, try to unset it to get max pair if bit: if curr.left: currXor += 2**i curr = curr.left else: curr = curr.right else: if curr.right: currXor += 2**i curr = curr.right else: curr = curr.left maxXor = max(maxXor, currXor) return maxXor
Example #15
Source Project: psychsim Author: pynadath File: probability.py License: MIT License | 5 votes |
def entropy(self): """ :returns: entropy (in bits) of this distribution """ return sum([-p*math.log2(p) for p in dict.values(self)])
Example #16
Source Project: AIX360 Author: IBM File: train_tutorial_dermatology_models.py License: Apache License 2.0 | 5 votes |
def __init__(self, latent_dim=20, num_filters=64, num_channels=3, image_size=128, activation_type='relu', args=None): super(ConvEncNet, self).__init__() self.args = args if activation_type == 'relu': self.activation = nn.ReLU(inplace=True) elif activation_type == 'tanh': self.activation = nn.Tanh(inplace=True) else: print("Activation Type not supported") return self.conv_hidden = [] self.conv1 = nn.Conv2d(num_channels, num_filters, 4, 2, 1, bias=True) num_layers = math.log2(image_size) assert num_layers == round(num_layers), 'Image size that are power of 2 are supported.' num_layers = int(num_layers) for i in np.arange(num_layers - 3): self.conv_hidden.append(nn.Conv2d(num_filters * 2 ** i, num_filters * 2 ** (i + 1), 4, 2, 1, bias=True)) self.conv_hidden.append(nn.BatchNorm2d(num_filters * 2 ** (i + 1))) self.conv_hidden.append(self.activation) self.features = nn.Sequential(*self.conv_hidden) self.conv_mu = nn.Conv2d(num_filters * 2 ** (num_layers - 3), latent_dim, 4) self.conv_var = nn.Conv2d(num_filters * 2 ** (num_layers - 3), latent_dim, 4) for m in self.modules(): if isinstance(m, nn.Conv2d): nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu') elif isinstance(m, nn.BatchNorm2d): nn.init.constant_(m.weight, 1) nn.init.constant_(m.bias, 0) elif isinstance(m, nn.Linear): nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
Example #17
Source Project: AIX360 Author: IBM File: train_tutorial_dermatology_models.py License: Apache License 2.0 | 5 votes |
def __init__(self, latent_dim=20, num_filters=64, num_channels=3, image_size=128, activation_type='relu', args=None): super(ConvDecNet, self).__init__() self.args = args if activation_type == 'relu': self.activation = nn.ReLU(inplace=True) elif activation_type == 'tanh': self.activation = nn.Tanh(inplace=True) else: print("Activation Type not supported") return self.deconv_hidden = [] num_layers = math.log2(image_size) assert num_layers == round(num_layers), 'Image size that are power of 2 are supported.' num_layers = int(num_layers) self.deconv1 = nn.ConvTranspose2d(latent_dim, num_filters * 2 ** (num_layers - 3), 4, 1, 0, bias=True) self.bn1 = nn.BatchNorm2d(num_filters * 2 ** (num_layers - 3)) for i in np.arange(num_layers - 3, 0, -1): self.deconv_hidden.append(nn.ConvTranspose2d(num_filters * 2 ** i, num_filters * 2 ** (i - 1), 4, 2, 1, bias=True)) self.deconv_hidden.append(nn.BatchNorm2d(num_filters * 2 ** (i - 1))) self.deconv_hidden.append(self.activation) self.features = nn.Sequential(*self.deconv_hidden) self.deconv_out = nn.ConvTranspose2d(num_filters, num_channels, 4, 2,1, bias=True) for m in self.modules(): if isinstance(m, nn.Conv2d): nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu') elif isinstance(m, nn.BatchNorm2d): nn.init.constant_(m.weight, 1) nn.init.constant_(m.bias, 0) elif isinstance(m, nn.Linear): nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
Example #18
Source Project: Chatbot Author: zake7749 File: bm25Matcher.py License: GNU General Public License v3.0 | 5 votes |
def calculateIDF(self): # 構建詞集與紀錄詞出現位置的字典 if len(self.wordset) == 0: self.buildWordSet() if len(self.words_location_record) == 0: self.buildWordLocationRecord() # 計算 idf for word in self.wordset: self.words_idf[word] = math.log2((self.D + .5)/(self.words_location_record[word] + .5))
Example #19
Source Project: torf Author: rndusr File: _utils.py License: GNU General Public License v3.0 | 5 votes |
def is_power_of_2(num): """Return whether `num` is a power of two""" if num == 0: return False log = math.log2(abs(num)) return int(log) == float(log)
Example #20
Source Project: ACE Author: IntegralDefense File: __init__.py License: Apache License 2.0 | 5 votes |
def human_readable_size(size): from math import log2 _suffixes = ['bytes', 'K', 'M', 'G', 'T', 'E', 'Z'] # determine binary order in steps of size 10 # (coerce to int, // still returns a float) order = int(log2(size) / 10) if size else 0 # format file size # (.4g results in rounded numbers for exact matches and max 3 decimals, # should never resort to exponent values) return '{:.4g} {}'.format(size / (1 << (order * 10)), _suffixes[order])
Example #21
Source Project: ACE Author: IntegralDefense File: __init__.py License: Apache License 2.0 | 5 votes |
def human_readable_size(self): from math import log2 _suffixes = ['bytes', 'K', 'M', 'G', 'T', 'E', 'Z'] # determine binary order in steps of size 10 # (coerce to int, // still returns a float) order = int(log2(self.size) / 10) if self.size else 0 # format file size # (.4g results in rounded numbers for exact matches and max 3 decimals, # should never resort to exponent values) return '{:.4g} {}'.format(self.size / (1 << (order * 10)), _suffixes[order])
Example #22
Source Project: huawei-lte-examples Author: littlejo File: GraphicTrafficInfo.py License: GNU General Public License v3.0 | 5 votes |
def number_scale(size): if size == 0: return 0 elif int(math.log2(size)) <= 0: return 1 else: return int(math.log2(size)) + 1
Example #23
Source Project: ands Author: nbro File: RBT.py License: MIT License | 5 votes |
def upper_bound_height(t: RBT) -> bool: """Returns true if the height of the red-black tre t is bounded above by log₂(n + 1).""" return t.height() <= 2 * math.log2(t.size + 1)
Example #24
Source Project: ands Author: nbro File: MinMaxHeap.py License: MIT License | 5 votes |
def _is_on_even_level(self, i: int) -> bool: """Returns true if node at index i is on a even-level, i.e., if i is on a level multiple of 2. Time complexity: O(int(log(i + 1) % 2) == 0).""" assert self._is_good_index(i) return int(math.log2(i + 1) % 2) == 0
Example #25
Source Project: scikit-multiflow Author: scikit-multiflow File: adaptive_random_forest_regressor.py License: BSD 3-Clause "New" or "Revised" License | 5 votes |
def _set_max_features(self, n): if self.max_features == 'auto' or self.max_features == 'sqrt': self.max_features = int(round(math.sqrt(n))) elif self.max_features == 'log2': self.max_features = int(round(math.log2(n))) elif isinstance(self.max_features, int): # Consider 'max_features' features at each split. pass elif isinstance(self.max_features, float): # Consider 'max_features' as a percentage if self.max_features <= 0 or self.max_features > 1: raise ValueError('Invalid max_features value: {}'.format(self.max_features)) self.max_features = int(self.max_features * n) elif self.max_features is None: self.max_features = n else: # Default to "auto" self.max_features = int(round(math.sqrt(n))) # Sanity checks # max_features is negative, use max_features + n if self.max_features < 0: self.max_features += n # max_features <= 0 # (m can be negative if max_features is negative # and abs(max_features) > n) # use max_features = 1 if self.max_features <= 0: self.max_features = 1 # max_features > n, then use n if self.max_features > n: self.max_features = n
Example #26
Source Project: scikit-multiflow Author: scikit-multiflow File: adaptive_random_forests.py License: BSD 3-Clause "New" or "Revised" License | 5 votes |
def _set_max_features(self, n): if self.max_features == 'auto' or self.max_features == 'sqrt': self.max_features = round(math.sqrt(n)) elif self.max_features == 'log2': self.max_features = round(math.log2(n)) elif isinstance(self.max_features, int): # Consider 'max_features' features at each split. pass elif isinstance(self.max_features, float): # Consider 'max_features' as a percentage self.max_features = int(self.max_features * n) elif self.max_features is None: self.max_features = n else: # Default to "auto" self.max_features = round(math.sqrt(n)) # Sanity checks # max_features is negative, use max_features + n if self.max_features < 0: self.max_features += n # max_features <= 0 # (m can be negative if max_features is negative and abs(max_features) > n), # use max_features = 1 if self.max_features <= 0: self.max_features = 1 # max_features > n, then use n if self.max_features > n: self.max_features = n
Example #27
Source Project: Sets2Sets Author: HaojiHu File: Sets2Sets.py License: Apache License 2.0 | 5 votes |
def get_DCG(groundtruth, pred_rank_list, k): count = 0 dcg = 0 for pred in pred_rank_list: if count >= k: break if groundtruth[pred] == 1: dcg += (1) / math.log2(count + 1 + 1) count += 1 return dcg
Example #28
Source Project: inferbeddings Author: uclnlp File: base.py License: MIT License | 5 votes |
def __init__(self, k=None, G=lambda x: 2 ** x - 1, eta=lambda x: 1 / math.log2(x + 1), *args, **kwargs): super().__init__(*args, **kwargs) self.k = k self.G = G self.eta = eta
Example #29
Source Project: inferbeddings Author: uclnlp File: base.py License: MIT License | 5 votes |
def __init__(self, k=None, G=lambda x: 2 ** x - 1, eta=lambda x: 1 / math.log2(x + 1), *args, **kwargs): super().__init__(*args, **kwargs) self.k = k self.dcg = DCG(k=self.k, G=G, eta=eta, *args, **kwargs)
Example #30
Source Project: inferbeddings Author: uclnlp File: test_extra.py License: MIT License | 5 votes |
def test_dcg(): y = np.array([1, 1, 1, 1, 0, 0]) scores = np.array([1., .9, .8, .7, .6, .5]) G = lambda x: x eta = lambda x: 1 if x < 1.5 else 1 / math.log2(x) dcg = metrics.DCG(normalize_scores=False, G=G, eta=eta, k=len(y)) value = dcg(y, scores) # 1/1 + 1/log2(2) + 1/log2(3) + 1/log2(4) = 3.131 np.testing.assert_allclose(value, 3.131, rtol=1e-2) G = lambda x: 2 ** x - 1 eta = lambda x: 1 / math.log2(x + 1) dcg = metrics.DCG(normalize_scores=False, G=G, eta=eta, k=len(y)) value = dcg(y, scores) # (2**1 - 1)/log2(1 + 1) + (2**1 - 1)/log2(2 + 1) + # (2**1 - 1)/log2(3 + 1) + (2**1 - 1)/log2(4 + 1) = 2.562 np.testing.assert_allclose(value, 2.562, rtol=1e-2) y = np.array([1, 1, 0, 1, 0, 0]) scores = np.array([1., .9, .8, .7, .6, .5]) value_lower = dcg(y, scores) np.testing.assert_allclose(value_lower, 2.062, rtol=1e-2) assert value_lower < value y = np.array([0, 1, 0, 1, 0, 1]) scores = np.array([.5, .9, .8, .7, .6, 1.]) value_lower_2 = dcg(y, scores) np.testing.assert_allclose(value_lower_2, 2.062, rtol=1e-2)