本文整理匯總了Python中numpy.multiply方法的典型用法代碼示例。如果您正苦於以下問題:Python numpy.multiply方法的具體用法?Python numpy.multiply怎麽用?Python numpy.multiply使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類numpy
的用法示例。
在下文中一共展示了numpy.multiply方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: get_audio_data
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import multiply [as 別名]
def get_audio_data(self):
frames = self.rec.get_frames()
result = [0] * self.bins
if len(frames) > 0:
# keeps only the last frame
current_frame = frames[-1]
# plots the time signal
# self.line_top.set_data(self.time_vect, current_frame)
# computes and plots the fft signal
fft_frame = np.fft.rfft(current_frame)
if self.auto_gain:
fft_frame /= np.abs(fft_frame).max()
else:
fft_frame *= (1 + self.gain) / 5000000.
fft_frame = np.abs(fft_frame)
if self.log_scale:
fft_frame = np.log10(np.add(1, np.multiply(10, fft_frame)))
result = [min(int(max(i, 0.) * 1023), 1023) for i in fft_frame][0:self.bins]
return result
示例2: cost0
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import multiply [as 別名]
def cost0(params, input_size, hidden_size, num_labels, X, y, learning_rate):
m = X.shape[0]
X = np.matrix(X)
y = np.matrix(y)
# reshape the parameter array into parameter matrices for each layer
theta1 = np.matrix(np.reshape(params[:hidden_size * (input_size + 1)], (hidden_size, (input_size + 1))))
theta2 = np.matrix(np.reshape(params[hidden_size * (input_size + 1):], (num_labels, (hidden_size + 1))))
# run the feed-forward pass
a1, z2, a2, z3, h = forward_propagate(X, theta1, theta2)
# compute the cost
J = 0
for i in range(m):
first_term = np.multiply(-y[i,:], np.log(h[i,:]))
second_term = np.multiply((1 - y[i,:]), np.log(1 - h[i,:]))
J += np.sum(first_term - second_term)
J = J / m
return J
示例3: cost
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import multiply [as 別名]
def cost(params, input_size, hidden_size, num_labels, X, y, learning_rate):
m = X.shape[0]
X = np.matrix(X)
y = np.matrix(y)
# reshape the parameter array into parameter matrices for each layer
theta1 = np.matrix(np.reshape(params[:hidden_size * (input_size + 1)], (hidden_size, (input_size + 1))))
theta2 = np.matrix(np.reshape(params[hidden_size * (input_size + 1):], (num_labels, (hidden_size + 1))))
# run the feed-forward pass
a1, z2, a2, z3, h = forward_propagate(X, theta1, theta2)
# compute the cost
J = 0
for i in range(m):
first_term = np.multiply(-y[i,:], np.log(h[i,:]))
second_term = np.multiply((1 - y[i,:]), np.log(1 - h[i,:]))
J += np.sum(first_term - second_term)
J = J / m
# add the cost regularization term
J += (float(learning_rate) / (2 * m)) * (np.sum(np.power(theta1[:,1:], 2)) + np.sum(np.power(theta2[:,1:], 2)))
return J
示例4: cost
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import multiply [as 別名]
def cost(params, Y, R, num_features):
Y = np.matrix(Y) # (1682, 943)
R = np.matrix(R) # (1682, 943)
num_movies = Y.shape[0]
num_users = Y.shape[1]
# reshape the parameter array into parameter matrices
X = np.matrix(np.reshape(params[:num_movies * num_features], (num_movies, num_features))) # (1682, 10)
Theta = np.matrix(np.reshape(params[num_movies * num_features:], (num_users, num_features))) # (943, 10)
# initializations
J = 0
# compute the cost
error = np.multiply((X * Theta.T) - Y, R) # (1682, 943)
squared_error = np.power(error, 2) # (1682, 943)
J = (1. / 2) * np.sum(squared_error)
return J
示例5: gradientReg
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import multiply [as 別名]
def gradientReg(theta, X, y, learningRate):
theta = np.matrix(theta)
X = np.matrix(X)
y = np.matrix(y)
parameters = int(theta.ravel().shape[1])
grad = np.zeros(parameters)
error = sigmoid(X * theta.T) - y
for i in range(parameters):
term = np.multiply(error, X[:,i])
if (i == 0):
grad[i] = np.sum(term) / len(X)
else:
grad[i] = (np.sum(term) / len(X)) + ((learningRate / len(X)) * theta[:,i])
return grad
示例6: image
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import multiply [as 別名]
def image(self, captcha_str):
"""
Generate a greyscale captcha image representing number string
Parameters
----------
captcha_str: str
string a characters for captcha image
Returns
-------
numpy.ndarray
Generated greyscale image in np.ndarray float type with values normalized to [0, 1]
"""
img = self.captcha.generate(captcha_str)
img = np.fromstring(img.getvalue(), dtype='uint8')
img = cv2.imdecode(img, cv2.IMREAD_GRAYSCALE)
img = cv2.resize(img, (self.h, self.w))
img = img.transpose(1, 0)
img = np.multiply(img, 1 / 255.0)
return img
示例7: forward_ocr
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import multiply [as 別名]
def forward_ocr(self, img_):
img_ = cv2.resize(img_, (80, 30))
img_ = img_.transpose(1, 0)
print(img_.shape)
img_ = img_.reshape((1, 80, 30))
print(img_.shape)
# img_ = img_.reshape((80 * 30))
img_ = np.multiply(img_, 1 / 255.0)
self.predictor.forward(data=img_, **self.init_state_dict)
prob = self.predictor.get_output(0)
label_list = []
for p in prob:
print(np.argsort(p))
max_index = np.argsort(p)[::-1][0]
label_list.append(max_index)
return self.__get_string(label_list)
示例8: get_cosine_dist
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import multiply [as 別名]
def get_cosine_dist(A, B):
B = np.reshape(B, (1, -1))
if A.shape[1] == 1:
A = np.hstack((A, np.zeros((A.shape[0], 1))))
B = np.hstack((B, np.zeros((B.shape[0], 1))))
aa = np.sum(np.multiply(A, A), axis=1).reshape(-1, 1)
bb = np.sum(np.multiply(B, B), axis=1).reshape(-1, 1)
ab = A @ B.T
# to avoid NaN for zero norm
aa[aa==0] = 1
bb[bb==0] = 1
D = np.real(np.ones((A.shape[0], B.shape[0])) - np.multiply((1/np.sqrt(np.kron(aa, bb.T))), ab))
return D
示例9: calWeights
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import multiply [as 別名]
def calWeights(self, img, kernel, y, x):
wmax = 0
sweight = 0
average = 0
for j in range(2 * self.Ds + 1 - 2 * self.ds - 1):
for i in range(2 * self.Ds + 1 - 2 * self.ds - 1):
start_y = y - self.Ds + self.ds + j
start_x = x - self.Ds + self.ds + i
neighbour_w = img[start_y - self.ds:start_y + self.ds + 1, start_x - self.ds:start_x + self.ds + 1]
center_w = img[y-self.ds:y+self.ds+1, x-self.ds:x+self.ds+1]
if j != y or i != x:
sub = np.subtract(neighbour_w, center_w)
dist = np.sum(np.multiply(kernel, np.multiply(sub, sub)))
w = np.exp(-dist/pow(self.h, 2)) # replaced by look up table
if w > wmax:
wmax = w
sweight = sweight + w
average = average + w * img[start_y, start_x]
return sweight, average, wmax
示例10: execute
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import multiply [as 別名]
def execute(self):
img_pad = self.padding()
img_pad = img_pad.astype(np.uint16)
raw_h = self.img.shape[0]
raw_w = self.img.shape[1]
bnf_img = np.empty((raw_h, raw_w), np.uint16)
rdiff = np.zeros((5,5), dtype='uint16')
for y in range(img_pad.shape[0] - 4):
for x in range(img_pad.shape[1] - 4):
for i in range(5):
for j in range(5):
rdiff[i,j] = abs(img_pad[y+i,x+j] - img_pad[y+2, x+2])
if rdiff[i,j] >= self.rthres[0]:
rdiff[i,j] = self.rw[0]
elif rdiff[i,j] < self.rthres[0] and rdiff[i,j] >= self.rthres[1]:
rdiff[i,j] = self.rw[1]
elif rdiff[i,j] < self.rthres[1] and rdiff[i,j] >= self.rthres[2]:
rdiff[i,j] = self.rw[2]
elif rdiff[i,j] < self.rthres[2]:
rdiff[i,j] = self.rw[3]
weights = np.multiply(rdiff, self.dw)
bnf_img[y,x] = np.sum(np.multiply(img_pad[y:y+5,x:x+5], weights[:,:])) / np.sum(weights)
self.img = bnf_img
return self.clipping()
示例11: roi_surf_data
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import multiply [as 別名]
def roi_surf_data(df, vertex_colname, surf, hemisphere, roi_radius):
'''
uses wb_command -surface-geodesic-rois to build rois (3D files)
then load and collasp that into 1D array
'''
## right the L and R hemisphere vertices from the table out to temptxt
with ciftify.utils.TempDir() as lil_tmpdir:
## write a temp vertex list file
vertex_list = os.path.join(lil_tmpdir, 'vertex_list.txt')
df.loc[df.hemi == hemisphere, vertex_colname].to_csv(vertex_list,sep='\n',index=False, header=False)
## from the temp text build - func masks and target masks
roi_surf = os.path.join(lil_tmpdir,'roi_surf.func.gii')
docmd(['wb_command', '-surface-geodesic-rois', surf,
str(roi_radius), vertex_list, roi_surf,
'-overlap-logic', 'EXCLUDE'])
rois_data = ciftify.niio.load_gii_data(roi_surf)
## multiply by labels and reduce to 1 vector
vlabels = df[df.hemi == hemisphere].roiidx.tolist()
rois_data = np.multiply(rois_data, vlabels)
rois_data1D = np.max(rois_data, axis=1)
return rois_data1D
示例12: __init__
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import multiply [as 別名]
def __init__(self, images, labels, fake_data=False, one_hot=False):
"""Construct a DataSet. one_hot arg is used only if fake_data is true."""
if fake_data:
self._num_examples = 10000
self.one_hot = one_hot
else:
assert images.shape[0] == labels.shape[0], (
'images.shape: %s labels.shape: %s' % (images.shape,
labels.shape))
self._num_examples = images.shape[0]
# Convert shape from [num examples, rows, columns, depth]
# to [num examples, rows*columns] (assuming depth == 1)
assert images.shape[3] == 1
images = images.reshape(images.shape[0],
images.shape[1] * images.shape[2])
# Convert from [0, 255] -> [0.0, 1.0].
images = images.astype(numpy.float32)
images = numpy.multiply(images, 1.0 / 255.0)
self._images = images
self._labels = labels
self._epochs_completed = 0
self._index_in_epoch = 0
示例13: make_edge_smooth
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import multiply [as 別名]
def make_edge_smooth(dataset_name, img_size) :
check_folder('./dataset/{}/{}'.format(dataset_name, 'trainB_smooth'))
file_list = glob('./dataset/{}/{}/*.*'.format(dataset_name, 'trainB'))
save_dir = './dataset/{}/trainB_smooth'.format(dataset_name)
kernel_size = 5
kernel = np.ones((kernel_size, kernel_size), np.uint8)
gauss = cv2.getGaussianKernel(kernel_size, 0)
gauss = gauss * gauss.transpose(1, 0)
for f in tqdm(file_list) :
file_name = os.path.basename(f)
bgr_img = cv2.imread(f)
gray_img = cv2.imread(f, 0)
bgr_img = cv2.resize(bgr_img, (img_size, img_size))
pad_img = np.pad(bgr_img, ((2, 2), (2, 2), (0, 0)), mode='reflect')
gray_img = cv2.resize(gray_img, (img_size, img_size))
edges = cv2.Canny(gray_img, 100, 200)
dilation = cv2.dilate(edges, kernel)
gauss_img = np.copy(bgr_img)
idx = np.where(dilation != 0)
for i in range(np.sum(dilation != 0)):
gauss_img[idx[0][i], idx[1][i], 0] = np.sum(
np.multiply(pad_img[idx[0][i]:idx[0][i] + kernel_size, idx[1][i]:idx[1][i] + kernel_size, 0], gauss))
gauss_img[idx[0][i], idx[1][i], 1] = np.sum(
np.multiply(pad_img[idx[0][i]:idx[0][i] + kernel_size, idx[1][i]:idx[1][i] + kernel_size, 1], gauss))
gauss_img[idx[0][i], idx[1][i], 2] = np.sum(
np.multiply(pad_img[idx[0][i]:idx[0][i] + kernel_size, idx[1][i]:idx[1][i] + kernel_size, 2], gauss))
cv2.imwrite(os.path.join(save_dir, file_name), gauss_img)
示例14: get_uv
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import multiply [as 別名]
def get_uv(self, xyz_vec):
# Extract lens parameters of interest.
fov_rad = self.lens.fov_deg * pi / 180
fov_scale = np.float32(2 * self.lens.radius_px / fov_rad)
# Normalize the input vector and rotate to match lens reference axes.
xyz_rot = get_rotation_matrix(self.lens.center_qq) * matrix_norm(xyz_vec)
# Convert to polar coordinates relative to lens boresight.
# (In lens coordinates, unit vector's X axis gives boresight angle;
# normalize Y/Z to get a planar unit vector for the bearing.)
# Note: Image +Y maps to 3D +Y, and image +X maps to 3D +Z.
theta_rad = np.arccos(xyz_rot[0,:])
proj_vec = matrix_norm(np.concatenate((xyz_rot[2,:], xyz_rot[1,:])))
# Fisheye lens maps 3D angle to focal-plane radius.
# TODO: Do we need a better model for lens distortion?
rad_px = theta_rad * fov_scale
# Convert back to focal-plane rectangular coordinates.
uv = np.multiply(rad_px, proj_vec) + self.lens.center_px
return np.asarray(uv + 0.5, dtype=int)
# Given an 2xN array of UV pixel coordinates, check if each pixel is
# within the fisheye field of view. Returns N-element boolean mask.
示例15: add_pixels
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import multiply [as 別名]
def add_pixels(self, uv_px, img1d, weight=None):
# Lookup row & column for each in-bounds coordinate.
mask = self.get_mask(uv_px)
xx = uv_px[0,mask]
yy = uv_px[1,mask]
# Update matrix according to assigned weight.
if weight is None:
img1d[mask] = self.img[yy,xx]
elif np.isscalar(weight):
img1d[mask] += self.img[yy,xx] * weight
else:
w1 = np.asmatrix(weight, dtype='float32')
w3 = w1.transpose() * np.ones((1,3))
img1d[mask] += np.multiply(self.img[yy,xx], w3[mask])
# A panorama image made from several FisheyeImage sources.
# TODO: Add support for supersampled anti-aliasing filters.