本文整理汇总了Python中math.log2方法的典型用法代码示例。如果您正苦于以下问题:Python math.log2方法的具体用法?Python math.log2怎么用?Python math.log2使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类math
的用法示例。
在下文中一共展示了math.log2方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: train
# 需要导入模块: import math [as 别名]
# 或者: from math import log2 [as 别名]
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)
示例2: get_NDCG
# 需要导入模块: import math [as 别名]
# 或者: from math import log2 [as 别名]
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
示例3: _accept_transition
# 需要导入模块: import math [as 别名]
# 或者: from math import log2 [as 别名]
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
示例4: _ail_handle_Convert
# 需要导入模块: import math [as 别名]
# 或者: from math import log2 [as 别名]
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)
示例5: __init__
# 需要导入模块: import math [as 别名]
# 或者: from math import log2 [as 别名]
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
示例6: __init__
# 需要导入模块: import math [as 别名]
# 或者: from math import log2 [as 别名]
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)
示例7: __init__
# 需要导入模块: import math [as 别名]
# 或者: from math import log2 [as 别名]
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)
示例8: _dec_diag
# 需要导入模块: import math [as 别名]
# 或者: from math import log2 [as 别名]
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)
示例9: get_batch_sizes
# 需要导入模块: import math [as 别名]
# 或者: from math import log2 [as 别名]
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
示例10: avanzar
# 需要导入模块: import math [as 别名]
# 或者: from math import log2 [as 别名]
def avanzar(self):
return super(tractor, self).avanzar(funcion_rendimiento=math.log2)
示例11: isPowerOfFour
# 需要导入模块: import math [as 别名]
# 或者: from math import log2 [as 别名]
def isPowerOfFour(self, n: int) -> bool:
return n > 0 and n == (4 ** (math.log2(n) // 2))
示例12: minXor
# 需要导入模块: import math [as 别名]
# 或者: from math import log2 [as 别名]
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
示例13: findMaximumXOR
# 需要导入模块: import math [as 别名]
# 或者: from math import log2 [as 别名]
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
示例14: entropy
# 需要导入模块: import math [as 别名]
# 或者: from math import log2 [as 别名]
def entropy(self):
"""
:returns: entropy (in bits) of this distribution
"""
return sum([-p*math.log2(p) for p in dict.values(self)])
示例15: __init__
# 需要导入模块: import math [as 别名]
# 或者: from math import log2 [as 别名]
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')