本文整理汇总了Python中numpy.sqrt方法的典型用法代码示例。如果您正苦于以下问题:Python numpy.sqrt方法的具体用法?Python numpy.sqrt怎么用?Python numpy.sqrt使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类numpy
的用法示例。
在下文中一共展示了numpy.sqrt方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: calculate_diff_stress
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import sqrt [as 别名]
def calculate_diff_stress(self, x, u, nu, side=1):
"""
Calculate the derivative of the Von Mises stress given the densities x,
displacements u, and young modulus nu. Optionally, provide the side
length (default: 1).
"""
rho = self.penalized_densities(x)
EB = self.E(nu).dot(self.B(side))
EBu = sum([EB.dot(u[:, i][self.edofMat]) for i in range(u.shape[1])])
s11, s22, s12 = numpy.hsplit((EBu * rho / float(u.shape[1])).T, 3)
drho = self.diff_penalized_densities(x)
ds11, ds22, ds12 = numpy.hsplit(
((1 - rho) * drho * EBu / float(u.shape[1])).T, 3)
vm_stress = numpy.sqrt(s11**2 - s11 * s22 + s22**2 + 3 * s12**2)
if abs(vm_stress).sum() > 1e-8:
dvm_stress = (0.5 * (1. / vm_stress) * (2 * s11 * ds11 -
ds11 * s22 - s11 * ds22 + 2 * s22 * ds22 + 6 * s12 * ds12))
return dvm_stress
return 0
示例2: get_fans
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import sqrt [as 别名]
def get_fans(shape, dim_ordering='th'):
if len(shape) == 2:
fan_in = shape[0]
fan_out = shape[1]
elif len(shape) == 4 or len(shape) == 5:
# assuming convolution kernels (2D or 3D).
# TH kernel shape: (depth, input_depth, ...)
# TF kernel shape: (..., input_depth, depth)
if dim_ordering == 'th':
receptive_field_size = np.prod(shape[2:])
fan_in = shape[1] * receptive_field_size
fan_out = shape[0] * receptive_field_size
elif dim_ordering == 'tf':
receptive_field_size = np.prod(shape[:2])
fan_in = shape[-2] * receptive_field_size
fan_out = shape[-1] * receptive_field_size
else:
raise ValueError('Invalid dim_ordering: ' + dim_ordering)
else:
# no specific assumptions
fan_in = np.sqrt(np.prod(shape))
fan_out = np.sqrt(np.prod(shape))
return fan_in, fan_out
示例3: _radial_wvnum
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import sqrt [as 别名]
def _radial_wvnum(k, l, N, nfactor):
""" Creates a radial wavenumber based on two horizontal wavenumbers
along with the appropriate index map
"""
# compute target wavenumbers
k = k.values
l = l.values
K = np.sqrt(k[np.newaxis,:]**2 + l[:,np.newaxis]**2)
nbins = int(N/nfactor)
if k.max() > l.max():
ki = np.linspace(0., l.max(), nbins)
else:
ki = np.linspace(0., k.max(), nbins)
# compute bin index
kidx = np.digitize(np.ravel(K), ki)
# compute number of points for each wavenumber
area = np.bincount(kidx)
# compute the average radial wavenumber for each bin
kr = (np.bincount(kidx, weights=K.ravel())
/ np.ma.masked_where(area==0, area))
return ki, kr[1:-1]
示例4: classical_mds
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import sqrt [as 别名]
def classical_mds(self, D):
'''
Classical multidimensional scaling
Parameters
----------
D : square 2D ndarray
Euclidean Distance Matrix (matrix containing squared distances between points
'''
# Apply MDS algorithm for denoising
n = D.shape[0]
J = np.eye(n) - np.ones((n,n))/float(n)
G = -0.5*np.dot(J, np.dot(D, J))
s, U = np.linalg.eig(G)
# we need to sort the eigenvalues in decreasing order
s = np.real(s)
o = np.argsort(s)
s = s[o[::-1]]
U = U[:,o[::-1]]
S = np.diag(s)[0:self.dim,:]
self.X = np.dot(np.sqrt(S),U.T)
示例5: trilateration
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import sqrt [as 别名]
def trilateration(self, D):
'''
Find the location of points based on their distance matrix using trilateration
Parameters
----------
D : square 2D ndarray
Euclidean Distance Matrix (matrix containing squared distances between points
'''
dist = np.sqrt(D)
# Simpler algorithm (no denoising)
self.X = np.zeros((self.dim, self.m))
self.X[:,1] = np.array([0, dist[0,1]])
for i in xrange(2,m):
self.X[:,i] = self.trilateration_single_point(self.X[1,1],
dist[0,i], dist[1,i])
示例6: mtx_freq2visi
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import sqrt [as 别名]
def mtx_freq2visi(M, p_mic_x, p_mic_y):
"""
build the matrix that maps the Fourier series to the visibility
:param M: the Fourier series expansion is limited from -M to M
:param p_mic_x: a vector that constains microphones x coordinates
:param p_mic_y: a vector that constains microphones y coordinates
:return:
"""
num_mic = p_mic_x.size
ms = np.reshape(np.arange(-M, M + 1, step=1), (1, -1), order='F')
G = np.zeros((num_mic * (num_mic - 1), 2 * M + 1), dtype=complex, order='C')
count_G = 0
for q in range(num_mic):
p_x_outer = p_mic_x[q]
p_y_outer = p_mic_y[q]
for qp in range(num_mic):
if not q == qp:
p_x_qqp = p_x_outer - p_mic_x[qp]
p_y_qqp = p_y_outer - p_mic_y[qp]
norm_p_qqp = np.sqrt(p_x_qqp ** 2 + p_y_qqp ** 2)
phi_qqp = np.arctan2(p_y_qqp, p_x_qqp)
G[count_G, :] = (-1j) ** ms * sp.special.jv(ms, norm_p_qqp) * \
np.exp(1j * ms * phi_qqp)
count_G += 1
return G
示例7: convert_image
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import sqrt [as 别名]
def convert_image(self, filename):
pic = img.imread(filename)
# Set FFT size to be double the image size so that the edge of the spectrum stays clear
# preventing some bandfilter artifacts
self.NFFT = 2*pic.shape[1]
# Repeat image lines until each one comes often enough to reach the desired line time
ffts = (np.flipud(np.repeat(pic[:, :, 0], self.repetitions, axis=0) / 16.)**2.) / 256.
# Embed image in center bins of the FFT
fftall = np.zeros((ffts.shape[0], self.NFFT))
startbin = int(self.NFFT/4)
fftall[:, startbin:(startbin+pic.shape[1])] = ffts
# Generate random phase vectors for the FFT bins, this is important to prevent high peaks in the output
# The phases won't be visible in the spectrum
phases = 2*np.pi*np.random.rand(*fftall.shape)
rffts = fftall * np.exp(1j*phases)
# Perform the FFT per image line, then concatenate them to form the final signal
timedata = np.fft.ifft(np.fft.ifftshift(rffts, axes=1), axis=1) / np.sqrt(float(self.NFFT))
linear = timedata.flatten()
linear = linear / np.max(np.abs(linear))
return linear
示例8: solve_modal
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import sqrt [as 别名]
def solve_modal(model,k:int):
"""
Solve eigen mode of the MDOF system
params:
model: FEModel.
k: number of modes to extract.
"""
K_,M_=model.K_,model.M_
if k>model.DOF:
logger.info('Warning: the modal number to extract is larger than the system DOFs, only %d modes are available'%model.DOF)
k=model.DOF
omega2s,modes = sl.eigsh(K_,k,M_,sigma=0,which='LM')
delta = modes/np.sum(modes,axis=0)
model.is_solved=True
model.mode_=delta
model.omega_=np.sqrt(omega2s).reshape((k,1))
示例9: set_input_shape
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import sqrt [as 别名]
def set_input_shape(self, input_shape):
batch_size, dim = input_shape
self.input_shape = [batch_size, dim]
self.output_shape = [batch_size, self.num_hid]
if self.init_mode == "norm":
init = tf.random_normal([dim, self.num_hid], dtype=tf.float32)
init = init / tf.sqrt(1e-7 + tf.reduce_sum(tf.square(init), axis=0,
keep_dims=True))
init = init * self.init_scale
elif self.init_mode == "uniform_unit_scaling":
scale = np.sqrt(3. / dim)
init = tf.random_uniform([dim, self.num_hid], dtype=tf.float32,
minval=-scale, maxval=scale)
else:
raise ValueError(self.init_mode)
self.W = PV(init)
if self.use_bias:
self.b = PV((np.zeros((self.num_hid,))
+ self.init_b).astype('float32'))
示例10: __forward
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import sqrt [as 别名]
def __forward(self, x, train_flg):
if self.running_mean is None:
N, D = x.shape
self.running_mean = np.zeros(D)
self.running_var = np.zeros(D)
if train_flg:
mu = x.mean(axis=0)
xc = x - mu
var = np.mean(xc ** 2, axis=0)
std = np.sqrt(var + 10e-7)
xn = xc / std
self.batch_size = x.shape[0]
self.xc = xc
self.xn = xn
self.std = std
self.running_mean = self.momentum * self.running_mean + (1 - self.momentum) * mu
self.running_var = self.momentum * self.running_var + (1 - self.momentum) * var
else:
xc = x - self.running_mean
xn = xc / ((np.sqrt(self.running_var + 10e-7)))
out = self.gamma * xn + self.beta
return out
示例11: update
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import sqrt [as 别名]
def update(self, params, grads):
if self.m is None:
self.m, self.v = {}, {}
for key, val in params.items():
self.m[key] = np.zeros_like(val)
self.v[key] = np.zeros_like(val)
self.iter += 1
lr_t = self.lr * np.sqrt(1.0 - self.beta2 ** self.iter) / (1.0 - self.beta1 ** self.iter)
for key in params.keys():
# self.m[key] = self.beta1*self.m[key] + (1-self.beta1)*grads[key]
# self.v[key] = self.beta2*self.v[key] + (1-self.beta2)*(grads[key]**2)
self.m[key] += (1 - self.beta1) * (grads[key] - self.m[key])
self.v[key] += (1 - self.beta2) * (grads[key] ** 2 - self.v[key])
params[key] -= lr_t * self.m[key] / (np.sqrt(self.v[key]) + 1e-7)
# unbias_m += (1 - self.beta1) * (grads[key] - self.m[key]) # correct bias
# unbisa_b += (1 - self.beta2) * (grads[key]*grads[key] - self.v[key]) # correct bias
# params[key] += self.lr * unbias_m / (np.sqrt(unbisa_b) + 1e-7)
示例12: __init_weight
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import sqrt [as 别名]
def __init_weight(self, weight_init_std):
"""设定权重的初始值
Parameters
----------
weight_init_std : 指定权重的标准差(e.g. 0.01)
指定'relu'或'he'的情况下设定“He的初始值”
指定'sigmoid'或'xavier'的情况下设定“Xavier的初始值”
"""
all_size_list = [self.input_size] + self.hidden_size_list + [self.output_size]
for idx in range(1, len(all_size_list)):
scale = weight_init_std
if str(weight_init_std).lower() in ('relu', 'he'):
scale = np.sqrt(2.0 / all_size_list[idx - 1]) # 使用ReLU的情况下推荐的初始值
elif str(weight_init_std).lower() in ('sigmoid', 'xavier'):
scale = np.sqrt(1.0 / all_size_list[idx - 1]) # 使用sigmoid的情况下推荐的初始值
self.params['W' + str(idx)] = scale * np.random.randn(all_size_list[idx - 1], all_size_list[idx])
self.params['b' + str(idx)] = np.zeros(all_size_list[idx])
示例13: plot_n_image
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import sqrt [as 别名]
def plot_n_image(X, n):
""" plot first n images
n has to be a square number
"""
pic_size = int(np.sqrt(X.shape[1]))
grid_size = int(np.sqrt(n))
first_n_images = X[:n, :]
fig, ax_array = plt.subplots(nrows=grid_size, ncols=grid_size,
sharey=True, sharex=True, figsize=(8, 8))
for r in range(grid_size):
for c in range(grid_size):
ax_array[r, c].imshow(first_n_images[grid_size * r + c].reshape((pic_size, pic_size)))
plt.xticks(np.array([]))
plt.yticks(np.array([]))
示例14: run_eval
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import sqrt [as 别名]
def run_eval(sess, test_X, test_y):
ds = tf.data.Dataset.from_tensor_slices((test_X, test_y))
ds = ds.batch(1)
X, y = ds.make_one_shot_iterator().get_next()
with tf.variable_scope("model", reuse=True):
prediction, _, _ = lstm_model(X, [0.0], False)
predictions = []
labels = []
for i in range(TESTING_EXAMPLES):
p, l = sess.run([prediction, y])
predictions.append(p)
labels.append(l)
predictions = np.array(predictions).squeeze()
labels = np.array(labels).squeeze()
rmse = np.sqrt(((predictions-labels) ** 2).mean(axis=0))
print("Mean Square Error is: %f" % rmse)
plt.figure()
plt.plot(predictions, label='predictions')
plt.plot(labels, label='real_sin')
plt.legend()
plt.show()
示例15: point_on_segment
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import sqrt [as 别名]
def point_on_segment(ac, b, atol=1e-8):
'''
point_on_segment((a,b), c) yields True if point x is on segment (a,b) and False otherwise. Note
that this differs from point_in_segment in that a point that if c is equal to a or b it is
considered 'on' but not 'in' the segment.
The option atol can be given and is used only to test for difference from 0; by default it is
1e-8.
'''
(a,c) = ac
abc = [np.asarray(u) for u in (a,b,c)]
if any(len(u.shape) > 1 for u in abc): (a,b,c) = [np.reshape(u,(len(u),-1)) for u in abc]
else: (a,b,c) = abc
vab = b - a
vbc = c - b
vac = c - a
dab = np.sqrt(np.sum(vab**2, axis=0))
dbc = np.sqrt(np.sum(vbc**2, axis=0))
dac = np.sqrt(np.sum(vac**2, axis=0))
return np.isclose(dab + dbc - dac, 0, atol=atol)