本文整理匯總了Python中numpy.square方法的典型用法代碼示例。如果您正苦於以下問題:Python numpy.square方法的具體用法?Python numpy.square怎麽用?Python numpy.square使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類numpy
的用法示例。
在下文中一共展示了numpy.square方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: reward
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import square [as 別名]
def reward(tsptw_sequence,speed):
# Convert sequence to tour (end=start)
tour = np.concatenate((tsptw_sequence,np.expand_dims(tsptw_sequence[0],0)))
# Compute tour length
inter_city_distances = np.sqrt(np.sum(np.square(tour[:-1,:2]-tour[1:,:2]),axis=1))
distance = np.sum(inter_city_distances)
# Compute develiry times at each city and count late cities
elapsed_time = -10
late_cities = 0
for i in range(tsptw_sequence.shape[0]-1):
travel_time = inter_city_distances[i]/speed
tw_open = tour[i+1,2]
tw_close = tour[i+1,3]
elapsed_time += travel_time
if elapsed_time <= tw_open:
elapsed_time = tw_open
elif elapsed_time > tw_close:
late_cities += 1
# Reward
return distance + 100000000*late_cities
# Swap city[i] with city[j] in sequence
示例2: pred_test
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import square [as 別名]
def pred_test(testing_data, exe, param_list=None, save_path=""):
ret = numpy.zeros((testing_data.shape[0], 2))
if param_list is None:
for i in range(testing_data.shape[0]):
exe.arg_dict['data'][:] = testing_data[i, 0]
exe.forward(is_train=False)
ret[i, 0] = exe.outputs[0].asnumpy()
ret[i, 1] = numpy.exp(exe.outputs[1].asnumpy())
numpy.savetxt(save_path, ret)
else:
for i in range(testing_data.shape[0]):
pred = numpy.zeros((len(param_list),))
for j in range(len(param_list)):
exe.copy_params_from(param_list[j])
exe.arg_dict['data'][:] = testing_data[i, 0]
exe.forward(is_train=False)
pred[j] = exe.outputs[0].asnumpy()
ret[i, 0] = pred.mean()
ret[i, 1] = pred.std()**2
numpy.savetxt(save_path, ret)
mse = numpy.square(ret[:, 0] - testing_data[:, 0] **3).mean()
return mse, ret
示例3: preprocess_sample_normalize
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import square [as 別名]
def preprocess_sample_normalize(self, threadIndex, audio_paths, overwrite, return_dict):
if len(audio_paths) > 0:
audio_clip = audio_paths[0]
feat = self.featurize(audio_clip=audio_clip, overwrite=overwrite)
feat_squared = np.square(feat)
count = float(feat.shape[0])
dim = feat.shape[1]
if len(audio_paths) > 1:
for audio_path in audio_paths[1:]:
next_feat = self.featurize(audio_clip=audio_path, overwrite=overwrite)
next_feat_squared = np.square(next_feat)
feat_vertically_stacked = np.concatenate((feat, next_feat)).reshape(-1, dim)
feat = np.sum(feat_vertically_stacked, axis=0, keepdims=True)
feat_squared_vertically_stacked = np.concatenate(
(feat_squared, next_feat_squared)).reshape(-1, dim)
feat_squared = np.sum(feat_squared_vertically_stacked, axis=0, keepdims=True)
count += float(next_feat.shape[0])
return_dict[threadIndex] = {'feat': feat, 'feat_squared': feat_squared, 'count': count}
示例4: test_ndarray_elementwise
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import square [as 別名]
def test_ndarray_elementwise():
np.random.seed(0)
nrepeat = 10
maxdim = 4
all_type = [np.float32, np.float64, np.float16, np.uint8, np.int32]
real_type = [np.float32, np.float64, np.float16]
for repeat in range(nrepeat):
for dim in range(1, maxdim):
check_with_uniform(lambda x, y: x + y, 2, dim, type_list=all_type)
check_with_uniform(lambda x, y: x - y, 2, dim, type_list=all_type)
check_with_uniform(lambda x, y: x * y, 2, dim, type_list=all_type)
check_with_uniform(lambda x, y: x / y, 2, dim, type_list=real_type)
check_with_uniform(lambda x, y: x / y, 2, dim, rmin=1, type_list=all_type)
check_with_uniform(mx.nd.sqrt, 1, dim, np.sqrt, rmin=0)
check_with_uniform(mx.nd.square, 1, dim, np.square, rmin=0)
check_with_uniform(lambda x: mx.nd.norm(x).asscalar(), 1, dim, np.linalg.norm)
示例5: test_broadcast
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import square [as 別名]
def test_broadcast():
sample_num = 1000
def test_broadcast_to():
for i in range(sample_num):
ndim = np.random.randint(1, 6)
target_shape = np.random.randint(1, 11, size=ndim)
shape = target_shape.copy()
axis_flags = np.random.randint(0, 2, size=ndim)
axes = []
for (axis, flag) in enumerate(axis_flags):
if flag:
shape[axis] = 1
dat = np.random.rand(*shape) - 0.5
numpy_ret = dat
ndarray_ret = mx.nd.array(dat).broadcast_to(shape=target_shape)
if type(ndarray_ret) is mx.ndarray.NDArray:
ndarray_ret = ndarray_ret.asnumpy()
assert (ndarray_ret.shape == target_shape).all()
err = np.square(ndarray_ret - numpy_ret).mean()
assert err < 1E-8
test_broadcast_to()
示例6: test_square
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import square [as 別名]
def test_square():
input1 = np.random.randint(1, 10, (2, 3)).astype("float32")
ipsym = mx.sym.Variable("input1")
square = mx.sym.square(data=ipsym)
model = mx.mod.Module(symbol=square, data_names=['input1'], label_names=None)
model.bind(for_training=False, data_shapes=[('input1', np.shape(input1))], label_shapes=None)
model.init_params()
args, auxs = model.get_params()
params = {}
params.update(args)
params.update(auxs)
converted_model = onnx_mxnet.export_model(square, params, [np.shape(input1)], np.float32, "square.onnx")
sym, arg_params, aux_params = onnx_mxnet.import_model(converted_model)
result = forward_pass(sym, arg_params, aux_params, ['input1'], input1)
numpy_op = np.square(input1)
npt.assert_almost_equal(result, numpy_op)
示例7: adjacencyToLaplacian
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import square [as 別名]
def adjacencyToLaplacian(W):
"""
adjacencyToLaplacian: Computes the Laplacian from an Adjacency matrix
Input:
W (np.array): adjacency matrix
Output:
L (np.array): Laplacian matrix
"""
# Check that the matrix is square
assert W.shape[0] == W.shape[1]
# Compute the degree vector
d = np.sum(W, axis = 1)
# And build the degree matrix
D = np.diag(d)
# Return the Laplacian
return D - W
示例8: normalizeAdjacency
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import square [as 別名]
def normalizeAdjacency(W):
"""
NormalizeAdjacency: Computes the degree-normalized adjacency matrix
Input:
W (np.array): adjacency matrix
Output:
A (np.array): degree-normalized adjacency matrix
"""
# Check that the matrix is square
assert W.shape[0] == W.shape[1]
# Compute the degree vector
d = np.sum(W, axis = 1)
# Invert the square root of the degree
d = 1/np.sqrt(d)
# And build the square root inverse degree matrix
D = np.diag(d)
# Return the Normalized Adjacency
return D @ W @ D
示例9: normalizeLaplacian
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import square [as 別名]
def normalizeLaplacian(L):
"""
NormalizeLaplacian: Computes the degree-normalized Laplacian matrix
Input:
L (np.array): Laplacian matrix
Output:
normL (np.array): degree-normalized Laplacian matrix
"""
# Check that the matrix is square
assert L.shape[0] == L.shape[1]
# Compute the degree vector (diagonal elements of L)
d = np.diag(L)
# Invert the square root of the degree
d = 1/np.sqrt(d)
# And build the square root inverse degree matrix
D = np.diag(d)
# Return the Normalized Laplacian
return D @ L @ D
示例10: _gripper_visualization
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import square [as 別名]
def _gripper_visualization(self):
"""
Do any needed visualization here. Overrides superclass implementations.
"""
# color the gripper site appropriately based on distance to cube
if self.gripper_visualization:
# get distance to cube
cube_site_id = self.sim.model.site_name2id("cube")
dist = np.sum(
np.square(
self.sim.data.site_xpos[cube_site_id]
- self.sim.data.get_site_xpos("grip_site")
)
)
# set RGBA for the EEF site here
max_dist = 0.1
scaled = (1.0 - min(dist / max_dist, 1.)) ** 15
rgba = np.zeros(4)
rgba[0] = 1 - scaled
rgba[1] = scaled
rgba[3] = 0.5
self.sim.model.site_rgba[self.eef_site_id] = rgba
示例11: SpectralClustering
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import square [as 別名]
def SpectralClustering(CKSym, n):
# This is direct port of JHU vision lab code. Could probably use sklearn SpectralClustering.
CKSym = CKSym.astype(float)
N, _ = CKSym.shape
MAXiter = 1000 # Maximum number of iterations for KMeans
REPlic = 20 # Number of replications for KMeans
DN = np.diag(np.divide(1, np.sqrt(np.sum(CKSym, axis=0) + np.finfo(float).eps)))
LapN = identity(N).toarray().astype(float) - np.matmul(np.matmul(DN, CKSym), DN)
_, _, vN = np.linalg.svd(LapN)
vN = vN.T
kerN = vN[:, N - n:N]
normN = np.sqrt(np.sum(np.square(kerN), axis=1))
kerNS = np.divide(kerN, normN.reshape(len(normN), 1) + np.finfo(float).eps)
km = KMeans(n_clusters=n, n_init=REPlic, max_iter=MAXiter, n_jobs=-1).fit(kerNS)
return km.labels_
示例12: find_errors
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import square [as 別名]
def find_errors(gt_pose, final_pose):
# Simple euler distand between translation part.
gt_position = gt_pose[0:3]
predicted_position = final_pose[0:3]
translation_error = np.sqrt(np.sum(np.square(gt_position - predicted_position)))
# Convert euler angles rotation matrix.
gt_euler = gt_pose[3:6]
pt_euler = final_pose[3:6]
gt_mat = t3d.euler2mat(gt_euler[2],gt_euler[1],gt_euler[0],'szyx')
pt_mat = t3d.euler2mat(pt_euler[2],pt_euler[1],pt_euler[0],'szyx')
# Multiply inverse of one rotation matrix with another rotation matrix.
error_mat = np.dot(pt_mat,np.linalg.inv(gt_mat))
_,angle = transforms3d.axangles.mat2axangle(error_mat) # Convert matrix to axis angle representation and that angle is error.
return translation_error, abs(angle*(180/np.pi))
# Store all the results.
# if not os.path.exists(LOG_DIR): os.mkdir(LOG_DIR)
示例13: find_errors
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import square [as 別名]
def find_errors(self, gt_pose, final_pose):
import transforms3d
gt_position = gt_pose[0,0:3]
predicted_position = final_pose[0,0:3]
translation_error = np.sqrt(np.sum(np.square(gt_position - predicted_position)))
print("Translation Error: {}".format(translation_error))
gt_euler = gt_pose[0,3:6]
pt_euler = final_pose[0,3:6]
gt_mat = t3d.euler2mat(gt_euler[2],gt_euler[1],gt_euler[0],'szyx')
pt_mat = t3d.euler2mat(pt_euler[2],pt_euler[1],pt_euler[0],'szyx')
error_mat = np.dot(pt_mat,np.linalg.inv(gt_mat))
_,angle = transforms3d.axangles.mat2axangle(error_mat)
print("Rotation Error: {}".format(abs(angle*(180/np.pi))))
return translation_error, angle*(180/np.pi)
示例14: find_errors
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import square [as 別名]
def find_errors(gt_pose, final_pose):
# Simple euler distand between translation part.
gt_position = gt_pose[0:3]
predicted_position = final_pose[0:3]
translation_error = np.sqrt(np.sum(np.square(gt_position - predicted_position)))
# Convert euler angles rotation matrix.
gt_euler = gt_pose[3:6]
pt_euler = final_pose[3:6]
gt_mat = t3d.euler2mat(gt_euler[2],gt_euler[1],gt_euler[0],'szyx')
pt_mat = t3d.euler2mat(pt_euler[2],pt_euler[1],pt_euler[0],'szyx')
# Multiply inverse of one rotation matrix with another rotation matrix.
error_mat = np.dot(pt_mat,np.linalg.inv(gt_mat))
_,angle = transforms3d.axangles.mat2axangle(error_mat) # Convert matrix to axis angle representation and that angle is error.
return translation_error, abs(angle*(180/np.pi))
示例15: _pdist
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import square [as 別名]
def _pdist(a, b):
"""Compute pair-wise squared distance between points in `a` and `b`.
Parameters
----------
a : array_like
An NxM matrix of N samples of dimensionality M.
b : array_like
An LxM matrix of L samples of dimensionality M.
Returns
-------
ndarray
Returns a matrix of size len(a), len(b) such that eleement (i, j)
contains the squared distance between `a[i]` and `b[j]`.
"""
a, b = np.asarray(a), np.asarray(b)
if len(a) == 0 or len(b) == 0:
return np.zeros((len(a), len(b)))
a2, b2 = np.square(a).sum(axis=1), np.square(b).sum(axis=1)
r2 = -2. * np.dot(a, b.T) + a2[:, None] + b2[None, :]
r2 = np.clip(r2, 0., float(np.inf))
return r2