本文整理汇总了Python中numpy.squeeze方法的典型用法代码示例。如果您正苦于以下问题:Python numpy.squeeze方法的具体用法?Python numpy.squeeze怎么用?Python numpy.squeeze使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类numpy
的用法示例。
在下文中一共展示了numpy.squeeze方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: draw_heatmap
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import squeeze [as 别名]
def draw_heatmap(img, heatmap, alpha=0.5):
"""Draw a heatmap overlay over an image."""
assert len(heatmap.shape) == 2 or \
(len(heatmap.shape) == 3 and heatmap.shape[2] == 1)
assert img.dtype in [np.uint8, np.int32, np.int64]
assert heatmap.dtype in [np.float32, np.float64]
if img.shape[0:2] != heatmap.shape[0:2]:
heatmap_rs = np.clip(heatmap * 255, 0, 255).astype(np.uint8)
heatmap_rs = ia.imresize_single_image(
heatmap_rs[..., np.newaxis],
img.shape[0:2],
interpolation="nearest"
)
heatmap = np.squeeze(heatmap_rs) / 255.0
cmap = plt.get_cmap('jet')
heatmap_cmapped = cmap(heatmap)
heatmap_cmapped = np.delete(heatmap_cmapped, 3, 2)
heatmap_cmapped = heatmap_cmapped * 255
mix = (1-alpha) * img + alpha * heatmap_cmapped
mix = np.clip(mix, 0, 255).astype(np.uint8)
return mix
示例2: cleverhans_attack_wrapper
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import squeeze [as 别名]
def cleverhans_attack_wrapper(cleverhans_attack_fn, reset=True):
def attack(a):
session = tf.Session()
with session.as_default():
model = RVBCleverhansModel(a)
adversarial_image = cleverhans_attack_fn(model, session, a)
adversarial_image = np.squeeze(adversarial_image, axis=0)
if reset:
# optionally, reset to ignore other adversarials
# found during the search
a._reset()
# run predictions to make sure the returned adversarial
# is taken into account
min_, max_ = a.bounds()
adversarial_image = np.clip(adversarial_image, min_, max_)
a.predictions(adversarial_image)
return attack
示例3: __getitem__
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import squeeze [as 别名]
def __getitem__(self, idx):
if self.fasta_extractor is None:
self.fasta_extractor = FastaExtractor(self.fasta_file)
interval = self.bt[idx]
if interval.stop - interval.start != self.SEQ_WIDTH:
raise ValueError("Expected the interval to be {0} wide. Recieved stop - start = {1}".
format(self.SEQ_WIDTH, interval.stop - interval.start))
# Run the fasta extractor
seq = np.squeeze(self.fasta_extractor([interval]), axis=0)
return {
"inputs": {"dna": seq},
"metadata": {
"ranges": GenomicRanges.from_interval(interval)
}
}
示例4: apply_affine
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import squeeze [as 别名]
def apply_affine(aff, coords):
'''
apply_affine(affine, coords) yields the result of applying the given affine transformation to
the given coordinate or coordinates.
This function expects coords to be a (dims X n) matrix but if the first dimension is neither 2
nor 3, coords.T is used; i.e.:
apply_affine(affine3x3, coords2xN) ==> newcoords2xN
apply_affine(affine4x4, coords3xN) ==> newcoords3xN
apply_affine(affine3x3, coordsNx2) ==> newcoordsNx2 (for N != 2)
apply_affine(affine4x4, coordsNx3) ==> newcoordsNx3 (for N != 3)
'''
if aff is None: return coords
(coords,tr) = (np.asanyarray(coords), False)
if len(coords.shape) == 1: return np.squeeze(apply_affine(np.reshape(coords, (-1,1)), aff))
elif len(coords.shape) > 2: raise ValueError('cannot apply affine to ND-array for N > 2')
if len(coords) == 2: aff = to_affine(aff, 2)
elif len(coords) == 3: aff = to_affine(aff, 3)
else: (coords,aff,tr) = (coords.T, to_affine(aff, coords.shape[1]), True)
r = np.dot(aff, np.vstack([coords, np.ones([1,coords.shape[1]])]))[:-1]
return r.T if tr else r
示例5: visualize
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import squeeze [as 别名]
def visualize(net, preprocessed_img, orig_img, conv_layer_name):
# Returns grad-cam heatmap, guided grad-cam, guided grad-cam saliency
imggrad = get_image_grad(net, preprocessed_img)
conv_out, conv_out_grad = get_conv_out_grad(net, preprocessed_img, conv_layer_name=conv_layer_name)
cam = get_cam(imggrad, conv_out)
ggcam = get_guided_grad_cam(cam, imggrad)
img_ggcam = grad_to_image(ggcam)
img_heatmap = get_img_heatmap(orig_img, cam)
ggcam_gray = to_grayscale(ggcam)
img_ggcam_gray = np.squeeze(grad_to_image(ggcam_gray))
return img_heatmap, img_ggcam, img_ggcam_gray
示例6: decode_topk
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import squeeze [as 别名]
def decode_topk(self, sess, latest_tokens, enc_top_states, dec_init_states):
"""Return the topK results and new decoder states."""
feed = {
self._enc_top_states: enc_top_states,
self._dec_in_state:
np.squeeze(np.array(dec_init_states)),
self._abstracts:
np.transpose(np.array([latest_tokens])),
self._abstract_lens: np.ones([len(dec_init_states)], np.int32)}
results = sess.run(
[self._topk_ids, self._topk_log_probs, self._dec_out_state],
feed_dict=feed)
ids, probs, states = results[0], results[1], results[2]
new_states = [s for s in states]
return ids, probs, new_states
示例7: predict
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import squeeze [as 别名]
def predict(self, batch_inputs, batch_ruitu):
assert batch_ruitu.shape[0] == batch_inputs.shape[0], 'Shape Error'
assert batch_inputs.shape[1] == 28 and batch_inputs.shape[2] == 10 and batch_inputs.shape[3] == 9, 'Error! Obs input shape must be (None, 28,10,9)'
assert batch_ruitu.shape[1] == 37 and batch_ruitu.shape[2] == 10 and batch_ruitu.shape[3] == 29, 'Error! Ruitu input shape must be (None, 37,10, 29)'
#all_pred={}
pred_result_list = []
for i in range(10):
#print('Predict for station: 9000{}'.format(i+1))
result = self.model.predict(x=[batch_inputs[:,:,i,:], batch_ruitu[:,:,i,:]])
result = np.squeeze(result, axis=0)
#all_pred[i] = result
pred_result_list.append(result)
#pass
pred_result = np.stack(pred_result_list, axis=0)
#return all_pred, pred_result
print('Predict shape (10,37,3) means (stationID, timestep, features). Features include: t2m, rh2m and w10m')
self.pred_result = pred_result
return pred_result
示例8: set_recall
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import squeeze [as 别名]
def set_recall(predictions, labels, weights_fn=common_layers.weights_nonzero):
"""Recall of set predictions.
Args:
predictions : A Tensor of scores of shape [batch, nlabels].
labels: A Tensor of int32s giving true set elements,
of shape [batch, seq_length].
weights_fn: A function to weight the elements.
Returns:
hits: A Tensor of shape [batch, nlabels].
weights: A Tensor of shape [batch, nlabels].
"""
with tf.variable_scope("set_recall", values=[predictions, labels]):
labels = tf.squeeze(labels, [2, 3])
weights = weights_fn(labels)
labels = tf.one_hot(labels, predictions.shape[-1])
labels = tf.reduce_max(labels, axis=1)
labels = tf.cast(labels, tf.bool)
return tf.to_float(tf.equal(labels, predictions)), weights
示例9: __init__
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import squeeze [as 别名]
def __init__(self, x0, mu, epsmult = 4.0, noc = False):
#determine number of planets and validate input
nplanets = x0.size/6.
if (nplanets - np.floor(nplanets) > 0):
raise Exception('The length of x0 must be a multiple of 6.')
if (mu.size != nplanets):
raise Exception('The length of mu must be the length of x0 divided by 6')
self.nplanets = int(nplanets)
self.mu = np.squeeze(mu)
if (self.mu.size == 1):
self.mu = np.array(mu)
self.epsmult = epsmult
if not(noc) and ('EXOSIMS.util.KeplerSTM_C.CyKeplerSTM' in sys.modules):
self.havec = True
self.x0 = np.squeeze(x0)
else:
self.havec = False
self.updateState(np.squeeze(x0))
示例10: _heatmap_to_rects
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import squeeze [as 别名]
def _heatmap_to_rects(self, grid_pred, bb_img):
"""Convert a heatmap to rectangles / bounding box candidates."""
grid_pred = np.squeeze(grid_pred) # (1, H, W) => (H, W)
# remove low activations
grid_thresh = grid_pred >= self.heatmap_activation_threshold
# find connected components
grid_labeled, num_labels = morphology.label(
grid_thresh, background=0, connectivity=1, return_num=True
)
# for each connected components,
# - draw a bounding box around it,
# - shrink the bounding box to optimal size
# - estimate a score/confidence value
bbs = []
for label in range(1, num_labels+1):
(yy, xx) = np.nonzero(grid_labeled == label)
min_y, max_y = np.min(yy), np.max(yy)
min_x, max_x = np.min(xx), np.max(xx)
rect = RectangleOnImage(x1=min_x, x2=max_x+1, y1=min_y, y2=max_y+1, shape=grid_labeled)
activation = self._rect_to_score(rect, grid_pred)
rect_shrunk, activation_shrunk = self._shrink(grid_pred, rect)
rect_rs_shrunk = rect_shrunk.on(bb_img)
bbs.append((rect_rs_shrunk, activation_shrunk))
return bbs
示例11: generate_video_image
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import squeeze [as 别名]
def generate_video_image(batch_idx, examples, model):
"""Generate frames for a video of the training progress.
Each frame contains N examples shown in a grid. Each example shows
the input image and the main heatmap predicted by the model."""
start_time = time.time()
#print("A", time.time() - start_time)
model.eval()
# fw through network
inputs, outputs_gt = examples_to_batch(examples, iaa.Noop())
inputs_torch = torch.from_numpy(inputs)
inputs_torch = Variable(inputs_torch, volatile=True)
if GPU >= 0:
inputs_torch = inputs_torch.cuda(GPU)
outputs_pred_torch = model(inputs_torch)
#print("B", time.time() - start_time)
outputs_pred = outputs_pred_torch.cpu().data.numpy()
inputs = (inputs * 255).astype(np.uint8).transpose(0, 2, 3, 1)
#print("C", time.time() - start_time)
heatmaps = []
for i in range(inputs.shape[0]):
hm_drawn = draw_heatmap(inputs[i], np.squeeze(outputs_pred[i][0]), alpha=0.5)
heatmaps.append(hm_drawn)
#print("D", time.time() - start_time)
grid = ia.draw_grid(heatmaps, cols=11, rows=6).astype(np.uint8)
#grid_rs = misc.imresize(grid, (720-32, 1280-32))
# pad by 42 for the text and to get the image to 720p aspect ratio
grid_pad = np.pad(grid, ((0, 42), (0, 0), (0, 0)), mode="constant")
grid_pad_text = ia.draw_text(
grid_pad,
x=grid_pad.shape[1]-220,
y=grid_pad.shape[0]-35,
text="Batch %05d" % (batch_idx,),
color=[255, 255, 255]
)
#print("E", time.time() - start_time)
return grid_pad_text
示例12: Rmtx_ri
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import squeeze [as 别名]
def Rmtx_ri(coef_ri, K, D, L):
coef_ri = np.squeeze(coef_ri)
coef_r = coef_ri[:K + 1]
coef_i = coef_ri[K + 1:]
R_r = linalg.toeplitz(np.concatenate((np.array([coef_r[-1]]),
np.zeros(L - K - 1))),
np.concatenate((coef_r[::-1],
np.zeros(L - K - 1)))
)
R_i = linalg.toeplitz(np.concatenate((np.array([coef_i[-1]]),
np.zeros(L - K - 1))),
np.concatenate((coef_i[::-1],
np.zeros(L - K - 1)))
)
return np.dot(np.vstack((np.hstack((R_r, -R_i)), np.hstack((R_i, R_r)))), D)
示例13: _logits_op
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import squeeze [as 别名]
def _logits_op(self, x, name=None):
with tf.name_scope(name, "logits", [x]) as name:
num_classes = self.adversarial.num_classes()
def _backward_py(gradient_y, x):
x = np.squeeze(x, axis=0)
gradient_y = np.squeeze(gradient_y, axis=0)
gradient_x = self.adversarial.backward(gradient_y, x)
gradient_x = gradient_x.astype(np.float32)
return gradient_x[np.newaxis]
def _backward_tf(op, grad):
images = op.inputs[0]
gradient_x = tf.py_func(
_backward_py, [grad, images], tf.float32)
gradient_x.set_shape(images.shape)
return gradient_x
def _forward_py(x):
predictions = self.adversarial.batch_predictions(
x, strict=False)[0]
predictions = predictions.astype(np.float32)
return predictions
op = py_func_grad(
_forward_py,
[x],
[tf.float32],
name=name,
grad=_backward_tf)
logits = op[0]
logits.set_shape((x.shape[0], num_classes))
return logits
示例14: pair_visual
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import squeeze [as 别名]
def pair_visual(original, adversarial, figure=None):
"""
This function displays two images: the original and the adversarial sample
:param original: the original input
:param adversarial: the input after perterbations have been applied
:param figure: if we've already displayed images, use the same plot
:return: the matplot figure to reuse for future samples
"""
import matplotlib.pyplot as plt
# Squeeze the image to remove single-dimensional entries from array shape
original = np.squeeze(original)
adversarial = np.squeeze(adversarial)
# Ensure our inputs are of proper shape
assert(len(original.shape) == 2 or len(original.shape) == 3)
# To avoid creating figures per input sample, reuse the sample plot
if figure is None:
plt.ion()
figure = plt.figure()
figure.canvas.set_window_title('Cleverhans: Pair Visualization')
# Add the images to the plot
perterbations = adversarial - original
for index, image in enumerate((original, perterbations, adversarial)):
figure.add_subplot(1, 3, index + 1)
plt.axis('off')
# If the image is 2D, then we have 1 color channel
if len(image.shape) == 2:
plt.imshow(image, cmap='gray')
else:
plt.imshow(image)
# Give the plot some time to update
plt.pause(0.01)
# Draw the plot and return
plt.show()
return figure
示例15: __getitem__
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import squeeze [as 别名]
def __getitem__(self, idx):
if self.seq_extractor is None:
self.seq_extractor = FastaExtractor(self.fasta_file)
self.dist_extractor = DistToClosestLandmarkExtractor(gtf_file=self.gtf,
landmarks=ALL_LANDMARKS)
interval = self.bt[idx]
if interval.stop - interval.start != self.SEQ_WIDTH:
raise ValueError("Expected the interval to be {0} wide. Recieved stop - start = {1}".
format(self.SEQ_WIDTH, interval.stop - interval.start))
out = {}
out['inputs'] = {}
# input - sequence
out['inputs']['seq'] = np.squeeze(self.seq_extractor([interval]), axis=0)
# input - distance
dist_dict = self.dist_transformer.transform(self.dist_extractor([interval]))
dist_dict = {k: np.squeeze(v, axis=0) for k, v in dist_dict.items()} # squeeze the batch axis
out['inputs'] = {**out['inputs'], **dist_dict}
# targets
if self.target_dataset is not None:
out["targets"] = np.array([self.target_dataset[idx]])
# metadata
out['metadata'] = {}
out['metadata']['ranges'] = GenomicRanges.from_interval(interval)
return out