本文整理汇总了Python中math.sqrt方法的典型用法代码示例。如果您正苦于以下问题:Python math.sqrt方法的具体用法?Python math.sqrt怎么用?Python math.sqrt使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类math
的用法示例。
在下文中一共展示了math.sqrt方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: swirl
# 需要导入模块: import math [as 别名]
# 或者: from math import sqrt [as 别名]
def swirl(x, y, step):
x -= (u_width / 2)
y -= (u_height / 2)
dist = math.sqrt(pow(x, 2) + pow(y, 2)) / 2.0
angle = (step / 10.0) + (dist * 1.5)
s = math.sin(angle)
c = math.cos(angle)
xs = x * c - y * s
ys = x * s + y * c
r = abs(xs + ys)
r = r * 12.0
r -= 20
return (r, r + (s * 130), r + (c * 130))
# roto-zooming checker board
示例2: __init__
# 需要导入模块: import math [as 别名]
# 或者: from math import sqrt [as 别名]
def __init__(self, block, layers, num_classes=1000):
self.inplanes = 64
super(MyResNet, self).__init__()
self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3,
bias=False)
self.bn1 = nn.BatchNorm2d(64)
self.relu = nn.ReLU(inplace=True)
self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
# note the increasing dilation
self.layer1 = self._make_layer(block, 64, layers[0])
self.layer2 = self._make_layer(block, 128, layers[1], stride=2, dilation=1)
self.layer3 = self._make_layer(block, 256, layers[2], stride=1, dilation=2)
self.layer4 = self._make_layer(block, 512, layers[3], stride=1, dilation=4)
# these layers will not be used
self.avgpool = nn.AvgPool2d(7)
self.fc = nn.Linear(512 * block.expansion, num_classes)
for m in self.modules():
if isinstance(m, nn.Conv2d):
n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
m.weight.data.normal_(0, math.sqrt(2. / n))
elif isinstance(m, nn.BatchNorm2d):
m.weight.data.fill_(1)
m.bias.data.zero_()
示例3: _compute_dE
# 需要导入模块: import math [as 别名]
# 或者: from math import sqrt [as 别名]
def _compute_dE(self, pos=None, lengths=None, weights=None, m=None):
dEx = 0
dEy = 0
d2Ex2 = 0
d2Ey2 = 0
d2Exy = 0
d2Eyx = 0
for i in pos:
if i != m:
xmi = pos[m][0] - pos[i][0]
ymi = pos[m][1] - pos[i][1]
xmi2 = xmi * xmi
ymi2 = ymi * ymi
xmi_ymi2 = xmi2 + ymi2
lmi = lengths[m][i]
kmi = weights[m][i] / (lmi * lmi)
dEx += kmi * (xmi - (lmi * xmi) / math.sqrt(xmi_ymi2))
dEy += kmi * (ymi - (lmi * ymi) / math.sqrt(xmi_ymi2))
d2Ex2 += kmi * (1 - (lmi * ymi2) / math.pow(xmi_ymi2, 1.5))
d2Ey2 += kmi * (1 - (lmi * xmi2) / math.pow(xmi_ymi2, 1.5))
res = kmi * (lmi * xmi * ymi) / math.pow(xmi_ymi2, 1.5)
d2Exy += res
d2Eyx += res
return dEx, dEy, d2Ex2, d2Ey2, d2Exy, d2Eyx
示例4: __init__
# 需要导入模块: import math [as 别名]
# 或者: from math import sqrt [as 别名]
def __init__(self, block, layers, num_classes=1000):
self.inplanes = 64
super(ResNet, self).__init__()
self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3,
bias=False)
self.bn1 = nn.BatchNorm2d(64)
self.relu = nn.ReLU(inplace=True)
# maxpool different from pytorch-resnet, to match tf-faster-rcnn
self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
self.layer1 = self._make_layer(block, 64, layers[0])
self.layer2 = self._make_layer(block, 128, layers[1], stride=2)
self.layer3 = self._make_layer(block, 256, layers[2], stride=2)
# use stride 1 for the last conv4 layer (same as tf-faster-rcnn)
self.layer4 = self._make_layer(block, 512, layers[3], stride=1)
for m in self.modules():
if isinstance(m, nn.Conv2d):
n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
m.weight.data.normal_(0, math.sqrt(2. / n))
elif isinstance(m, nn.BatchNorm2d):
m.weight.data.fill_(1)
m.bias.data.zero_()
开发者ID:Sunarker,项目名称:Collaborative-Learning-for-Weakly-Supervised-Object-Detection,代码行数:24,代码来源:resnet_v1.py
示例5: _attn
# 需要导入模块: import math [as 别名]
# 或者: from math import sqrt [as 别名]
def _attn(self, q, k, v, sequence_mask):
w = torch.matmul(q, k)
if self.scale:
w = w / math.sqrt(v.size(-1))
b_subset = self.b[:, :, :w.size(-2), :w.size(-1)]
if sequence_mask is not None:
b_subset = b_subset * sequence_mask.view(
sequence_mask.size(0), 1, -1)
b_subset = b_subset.permute(1, 0, 2, 3)
w = w * b_subset + -1e9 * (1 - b_subset)
w = nn.Softmax(dim=-1)(w)
w = self.attn_dropout(w)
return torch.matmul(w, v)
示例6: __call__
# 需要导入模块: import math [as 别名]
# 或者: from math import sqrt [as 别名]
def __call__(self, video):
for attempt in range(10):
area = video.shape[-3]*video.shape[-2]
target_area = random.uniform(0.08, 1.0)*area
aspect_ratio = random.uniform(3./4, 4./3)
w = int(round(math.sqrt(target_area*aspect_ratio)))
h = int(round(math.sqrt(target_area/aspect_ratio)))
if random.random() < 0.5:
w, h = h, w
if w <= video.shape[-2] and h <= video.shape[-3]:
x1 = random.randint(0, video.shape[-2]-w)
y1 = random.randint(0, video.shape[-3]-h)
video = video[..., y1:y1+h, x1:x1+w, :]
return resize(video, (self.size, self.size), self.interpolation)
# Fallback
scale = Scale(self.size, interpolation=self.interpolation)
crop = CenterCrop(self.size)
return crop(scale(video))
示例7: genCubeVector
# 需要导入模块: import math [as 别名]
# 或者: from math import sqrt [as 别名]
def genCubeVector(x, y, z, x_mult=1, y_mult=1, z_mult=1):
"""Generates a map of vector lengths from the center point to each coordinate
x - width of matrix to generate
y - height of matrix to generate
z - depth of matrix to generate
x_mult - value to scale x-axis by
y_mult - value to scale y-axis by
z_mult - value to scale z-axis by
"""
cX = (x - 1) / 2.0
cY = (y - 1) / 2.0
cZ = (z - 1) / 2.0
def vect(_x, _y, _z):
return int(math.sqrt(math.pow(_x - cX, 2 * x_mult) +
math.pow(_y - cY, 2 * y_mult) +
math.pow(_z - cZ, 2 * z_mult)))
return [[[vect(_x, _y, _z) for _z in range(z)] for _y in range(y)] for _x in range(x)]
示例8: distance
# 需要导入模块: import math [as 别名]
# 或者: from math import sqrt [as 别名]
def distance(origin, destination):
"""Determine distance between 2 sets of [lat,lon] in km"""
lat1, lon1 = origin
lat2, lon2 = destination
radius = 6371 # km
dlat = math.radians(lat2 - lat1)
dlon = math.radians(lon2 - lon1)
a = (math.sin(dlat / 2) * math.sin(dlat / 2) +
math.cos(math.radians(lat1)) *
math.cos(math.radians(lat2)) * math.sin(dlon / 2) *
math.sin(dlon / 2))
c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a))
d = radius * c
return d
示例9: __init__
# 需要导入模块: import math [as 别名]
# 或者: from math import sqrt [as 别名]
def __init__(self, block, layers, in_channels=3):
self.inplanes = 64
super(ResNet, self).__init__()
self.conv1 = nn.Conv2d(in_channels, 64, kernel_size=7, stride=2, padding=3,
bias=False)
self.bn1 = nn.BatchNorm2d(64)
self.relu = nn.ReLU(inplace=True)
self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
self.layer1 = self._make_layer(block, 64, layers[0])
self.layer2 = self._make_layer(block, 128, layers[1], stride=2)
self.layer3 = self._make_layer(block, 256, layers[2], stride=2)
self.layer4 = self._make_layer(block, 512, layers[3], stride=2)
for m in self.modules():
if isinstance(m, nn.Conv2d):
n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
m.weight.data.normal_(0, math.sqrt(2. / n))
elif isinstance(m, nn.BatchNorm2d):
m.weight.data.fill_(1)
m.bias.data.zero_()
示例10: __init__
# 需要导入模块: import math [as 别名]
# 或者: from math import sqrt [as 别名]
def __init__(self, interval, stat_func=None, pattern='.*', sort=False):
if stat_func is None:
def asum_stat(x):
"""returns |x|/size(x), async execution."""
return ndarray.norm(x)/sqrt(x.size)
stat_func = asum_stat
self.stat_func = stat_func
self.interval = interval
self.activated = False
self.queue = []
self.step = 0
self.exes = []
self.re_prog = re.compile(pattern)
self.sort = sort
def stat_helper(name, array):
"""wrapper for executor callback"""
array = ctypes.cast(array, NDArrayHandle)
array = NDArray(array, writable=False)
if not self.activated or not self.re_prog.match(py_str(name)):
return
self.queue.append((self.step, py_str(name), self.stat_func(array)))
self.stat_helper = stat_helper
示例11: matthewscc
# 需要导入模块: import math [as 别名]
# 或者: from math import sqrt [as 别名]
def matthewscc(self):
"""
Calculate the Matthew's Correlation Coefficent
"""
if not self.total_examples:
return 0.
true_pos = float(self.true_positives)
false_pos = float(self.false_positives)
false_neg = float(self.false_negatives)
true_neg = float(self.true_negatives)
terms = [(true_pos + false_pos),
(true_pos + false_neg),
(true_neg + false_pos),
(true_neg + false_neg)]
denom = 1.
for t in filter(lambda t: t != 0., terms):
denom *= t
return ((true_pos * true_neg) - (false_pos * false_neg)) / math.sqrt(denom)
示例12: set_verbosity
# 需要导入模块: import math [as 别名]
# 或者: from math import sqrt [as 别名]
def set_verbosity(self, verbose=False, print_func=None):
"""Switch on/off verbose mode
Parameters
----------
verbose : bool
switch on/off verbose mode
print_func : function
A function that computes statistics of initialized arrays.
Takes an `NDArray` and returns an `str`. Defaults to mean
absolute value str((|x|/size(x)).asscalar()).
"""
self._verbose = verbose
if print_func is None:
def asum_stat(x):
"""returns |x|/size(x), async execution."""
return str((ndarray.norm(x)/sqrt(x.size)).asscalar())
print_func = asum_stat
self._print_func = print_func
return self
示例13: _init_weight
# 需要导入模块: import math [as 别名]
# 或者: from math import sqrt [as 别名]
def _init_weight(self, name, arr):
shape = arr.shape
hw_scale = 1.
if len(shape) < 2:
raise ValueError('Xavier initializer cannot be applied to vector {0}. It requires at'
' least 2D.'.format(name))
if len(shape) > 2:
hw_scale = np.prod(shape[2:])
fan_in, fan_out = shape[1] * hw_scale, shape[0] * hw_scale
factor = 1.
if self.factor_type == "avg":
factor = (fan_in + fan_out) / 2.0
elif self.factor_type == "in":
factor = fan_in
elif self.factor_type == "out":
factor = fan_out
else:
raise ValueError("Incorrect factor type")
scale = np.sqrt(self.magnitude / factor)
if self.rnd_type == "uniform":
random.uniform(-scale, scale, out=arr)
elif self.rnd_type == "gaussian":
random.normal(0, scale, out=arr)
else:
raise ValueError("Unknown random type")
示例14: _get_lbmult
# 需要导入模块: import math [as 别名]
# 或者: from math import sqrt [as 别名]
def _get_lbmult(self, nup):
"""Returns lr scaling factor for large batch according to warmup schedule
(to be implemented)
"""
nwup = self.warmup_epochs * self.updates_per_epoch
strategy = self.warmup_strategy
maxmult = float(self.batch_scale)
if nup >= nwup:
mult = maxmult
elif nwup <= 1:
mult = 1.0
else:
if (strategy == 'linear'):
mult = 1.0 + (maxmult - 1) * nup / nwup
elif (strategy == 'power2'):
mult = 1.0 + (maxmult-1) * (nup*nup)/(nwup*nwup)
elif (strategy == 'sqrt'):
mult = 1.0 + (maxmult - 1) * math.sqrt(float(nup) / nwup)
else:
mult = 1.0
return mult
示例15: update
# 需要导入模块: import math [as 别名]
# 或者: from math import sqrt [as 别名]
def update(self, index, weight, grad, state):
assert(isinstance(weight, NDArray))
assert(isinstance(grad, NDArray))
self._update_count(index)
lr = self._get_lr(index)
wd = self._get_wd(index)
is_sparse = grad.stype == 'row_sparse'
history = state
if is_sparse:
kwargs = {'epsilon': self.float_stable_eps,
'rescale_grad': self.rescale_grad}
if self.clip_gradient:
kwargs['clip_gradient'] = self.clip_gradient
sparse.adagrad_update(weight, grad, history, out=weight, lr=lr, wd=wd, **kwargs)
else:
grad = grad * self.rescale_grad
if self.clip_gradient is not None:
grad = clip(grad, -self.clip_gradient, self.clip_gradient)
history[:] += square(grad)
div = grad / sqrt(history + self.float_stable_eps)
weight[:] += (div + weight * wd) * -lr