本文整理汇总了Python中numpy.newaxis方法的典型用法代码示例。如果您正苦于以下问题:Python numpy.newaxis方法的具体用法?Python numpy.newaxis怎么用?Python numpy.newaxis使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类numpy
的用法示例。
在下文中一共展示了numpy.newaxis方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: resize
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import newaxis [as 别名]
def resize(video, size, interpolation):
if interpolation == 'bilinear':
inter = cv2.INTER_LINEAR
elif interpolation == 'nearest':
inter = cv2.INTER_NEAREST
else:
raise NotImplementedError
shape = video.shape[:-3]
video = video.reshape((-1, *video.shape[-3:]))
resized_video = np.zeros((video.shape[0], size[1], size[0], video.shape[-1]))
for i in range(video.shape[0]):
img = cv2.resize(video[i], size, inter)
if len(img.shape) == 2:
img = img[:, :, np.newaxis]
resized_video[i] = img
return resized_video.reshape((*shape, size[1], size[0], video.shape[-1]))
示例2: plot_confusion_matrix
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import newaxis [as 别名]
def plot_confusion_matrix(y_true, y_pred, size=None, normalize=False):
"""plot_confusion_matrix."""
cm = confusion_matrix(y_true, y_pred)
fmt = "%d"
if normalize:
cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
fmt = "%.2f"
xticklabels = list(sorted(set(y_pred)))
yticklabels = list(sorted(set(y_true)))
if size is not None:
plt.figure(figsize=(size, size))
heatmap(cm, xlabel='Predicted label', ylabel='True label',
xticklabels=xticklabels, yticklabels=yticklabels,
cmap=plt.cm.Blues, fmt=fmt)
if normalize:
plt.title("Confusion matrix (norm.)")
else:
plt.title("Confusion matrix")
plt.gca().invert_yaxis()
示例3: test_bitmap_mask_resize
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import newaxis [as 别名]
def test_bitmap_mask_resize():
# resize with empty bitmap masks
raw_masks = dummy_raw_bitmap_masks((0, 28, 28))
bitmap_masks = BitmapMasks(raw_masks, 28, 28)
resized_masks = bitmap_masks.resize((56, 72))
assert len(resized_masks) == 0
assert resized_masks.height == 56
assert resized_masks.width == 72
# resize with bitmap masks contain 1 instances
raw_masks = np.diag(np.ones(4, dtype=np.uint8))[np.newaxis, ...]
bitmap_masks = BitmapMasks(raw_masks, 4, 4)
resized_masks = bitmap_masks.resize((8, 8))
assert len(resized_masks) == 1
assert resized_masks.height == 8
assert resized_masks.width == 8
truth = np.array([[[1, 1, 0, 0, 0, 0, 0, 0], [1, 1, 0, 0, 0, 0, 0, 0],
[0, 0, 1, 1, 0, 0, 0, 0], [0, 0, 1, 1, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 1, 0, 0], [0, 0, 0, 0, 1, 1, 0, 0],
[0, 0, 0, 0, 0, 0, 1, 1], [0, 0, 0, 0, 0, 0, 1, 1]]])
assert (resized_masks.masks == truth).all()
示例4: draw_heatmap
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import newaxis [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
示例5: _project_im_rois
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import newaxis [as 别名]
def _project_im_rois(im_rois, scales):
"""Project image RoIs into the image pyramid built by _get_image_blob.
Arguments:
im_rois (ndarray): R x 4 matrix of RoIs in original image coordinates
scales (list): scale factors as returned by _get_image_blob
Returns:
rois (ndarray): R x 4 matrix of projected RoI coordinates
levels (list): image pyramid levels used by each projected RoI
"""
im_rois = im_rois.astype(np.float, copy=False)
if len(scales) > 1:
widths = im_rois[:, 2] - im_rois[:, 0] + 1
heights = im_rois[:, 3] - im_rois[:, 1] + 1
areas = widths * heights
scaled_areas = areas[:, np.newaxis] * (scales[np.newaxis, :] ** 2)
diff_areas = np.abs(scaled_areas - 224 * 224)
levels = diff_areas.argmin(axis=1)[:, np.newaxis]
else:
levels = np.zeros((im_rois.shape[0], 1), dtype=np.int)
rois = im_rois * scales[levels]
return rois, levels
开发者ID:Sunarker,项目名称:Collaborative-Learning-for-Weakly-Supervised-Object-Detection,代码行数:26,代码来源:test.py
示例6: _radial_wvnum
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import newaxis [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]
示例7: test_dft_2d
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import newaxis [as 别名]
def test_dft_2d(self):
"""Test the discrete Fourier transform on 2D data"""
N = 16
da = xr.DataArray(np.random.rand(N,N), dims=['x','y'],
coords={'x':range(N),'y':range(N)}
)
ft = xrft.dft(da, shift=False)
npt.assert_almost_equal(ft.values, np.fft.fftn(da.values))
ft = xrft.dft(da, shift=False, window=True, detrend='constant')
dim = da.dims
window = np.hanning(N) * np.hanning(N)[:, np.newaxis]
da_prime = (da - da.mean(dim=dim)).values
npt.assert_almost_equal(ft.values, np.fft.fftn(da_prime*window))
da = xr.DataArray(np.random.rand(N,N), dims=['x','y'],
coords={'x':range(N,0,-1),'y':range(N,0,-1)}
)
assert (xrft.power_spectrum(da, shift=False,
density=True) >= 0.).all()
示例8: test_cross_phase_2d
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import newaxis [as 别名]
def test_cross_phase_2d(self, dask):
Ny, Nx = (32, 16)
x = np.linspace(0, 1, num=Nx, endpoint=False)
y = np.ones(Ny)
f = 6
phase_offset = np.pi/2
signal1 = np.cos(2*np.pi*f*x) # frequency = 1/(2*pi)
signal2 = np.cos(2*np.pi*f*x - phase_offset)
da1 = xr.DataArray(data=signal1*y[:,np.newaxis], name='a',
dims=['y','x'], coords={'y':y, 'x':x})
da2 = xr.DataArray(data=signal2*y[:,np.newaxis], name='b',
dims=['y','x'], coords={'y':y, 'x':x})
with pytest.raises(ValueError):
xrft.cross_phase(da1, da2, dim=['y','x'])
if dask:
da1 = da1.chunk({'x': 16})
da2 = da2.chunk({'x': 16})
cp = xrft.cross_phase(da1, da2, dim=['x'])
actual_phase_offset = cp.sel(freq_x=f).values
npt.assert_almost_equal(actual_phase_offset, phase_offset)
示例9: __call__
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import newaxis [as 别名]
def __call__(self, video):
"""
Args:
img (numpy array): Input image, shape (... x H x W x C), dtype uint8.
Returns:
PIL Image: Color jittered image.
"""
transforms = self.get_params(self.brightness, self.contrast, self.saturation, self.hue)
reshaped_video = video.reshape((-1, *video.shape[-3:]))
n_channels = video.shape[-1]
for i in range(reshaped_video.shape[0]):
img = reshaped_video[i]
if n_channels == 1:
img = img.squeeze(axis=2)
img = Image.fromarray(img)
for t in transforms:
img = t(img)
img = np.array(img)
if n_channels == 1:
img = img[..., np.newaxis]
reshaped_video[i] = img
video = reshaped_video.reshape(video.shape)
return video
示例10: generate_moving_mnist
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import newaxis [as 别名]
def generate_moving_mnist(self, num_digits=2):
'''
Get random trajectories for the digits and generate a video.
'''
data = np.zeros((self.n_frames_total, self.image_size_, self.image_size_), dtype=np.float32)
for n in range(num_digits):
# Trajectory
start_y, start_x = self.get_random_trajectory(self.n_frames_total)
ind = random.randint(0, self.mnist.shape[0] - 1)
digit_image = self.mnist[ind]
for i in range(self.n_frames_total):
top = start_y[i]
left = start_x[i]
bottom = top + self.digit_size_
right = left + self.digit_size_
# Draw digit
data[i, top:bottom, left:right] = np.maximum(data[i, top:bottom, left:right], digit_image)
data = data[..., np.newaxis]
return data
示例11: convert
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import newaxis [as 别名]
def convert(story):
# import pdb; pdb.set_trace()
sentence_arr, graphs, query_arr, answer_arr = story
node_id_w = graphs[2].shape[2]
edge_type_w = graphs[3].shape[3]
all_node_strengths = [np.zeros([1])]
all_node_ids = [np.zeros([1,node_id_w])]
for num_new_nodes, new_node_strengths, new_node_ids, _ in zip(*graphs):
last_strengths = all_node_strengths[-1]
last_ids = all_node_ids[-1]
cur_strengths = np.concatenate([last_strengths, new_node_strengths], 0)
cur_ids = np.concatenate([last_ids, new_node_ids], 0)
all_node_strengths.append(cur_strengths)
all_node_ids.append(cur_ids)
all_edges = graphs[3]
full_n_nodes = all_edges.shape[1]
all_node_strengths = np.stack([np.pad(x, ((0, full_n_nodes-x.shape[0])), 'constant') for x in all_node_strengths[1:]])
all_node_ids = np.stack([np.pad(x, ((0, full_n_nodes-x.shape[0]), (0, 0)), 'constant') for x in all_node_ids[1:]])
all_node_states = np.zeros([len(all_node_strengths), full_n_nodes,0])
return tuple(x[np.newaxis,...] for x in (all_node_strengths, all_node_ids, all_node_states, all_edges))
示例12: predict_on_batch
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import newaxis [as 别名]
def predict_on_batch(self, inputs):
if inputs.shape == (2,):
inputs = inputs[np.newaxis, :]
# Encode
max_len = len(max(inputs, key=len))
one_hot_ref = self.encode(inputs[:,0])
one_hot_alt = self.encode(inputs[:,1])
# Construct dummy library indicator
indicator = np.zeros((inputs.shape[0],2))
indicator[:,1] = 1
# Compute fold change for all three frames
fc_changes = []
for shift in range(3):
if shift > 0:
shifter = np.zeros((one_hot_ref.shape[0],1,4))
one_hot_ref = np.concatenate([one_hot_ref, shifter], axis=1)
one_hot_alt = np.concatenate([one_hot_alt, shifter], axis=1)
pred_ref = self.model.predict_on_batch([one_hot_ref, indicator]).reshape(-1)
pred_variant = self.model.predict_on_batch([one_hot_alt, indicator]).reshape(-1)
fc_changes.append(np.log2(pred_variant/pred_ref))
# Return
return {"mrl_fold_change":fc_changes[0],
"shift_1":fc_changes[1],
"shift_2":fc_changes[2]}
示例13: render
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import newaxis [as 别名]
def render(self, take_screenshot=False, output_type=0):
# self.render_timer.tic()
self._actual_render()
# self.render_timer.toc(log_at=1000, log_str='render timer', type='time')
np_rgb_img = None
np_d_img = None
c = 1000.
if take_screenshot:
if self.modality == 'rgb':
screenshot_rgba = np.zeros((self.height, self.width, 4), dtype=np.uint8)
glReadPixels(0, 0, self.width, self.height, GL_RGBA, GL_UNSIGNED_BYTE, screenshot_rgba)
np_rgb_img = screenshot_rgba[::-1,:,:3];
if self.modality == 'depth':
screenshot_d = np.zeros((self.height, self.width, 4), dtype=np.uint8)
glReadPixels(0, 0, self.width, self.height, GL_RGBA, GL_UNSIGNED_BYTE, screenshot_d)
np_d_img = screenshot_d[::-1,:,:3];
np_d_img = np_d_img[:,:,2]*(255.*255./c) + np_d_img[:,:,1]*(255./c) + np_d_img[:,:,0]*(1./c)
np_d_img = np_d_img.astype(np.float32)
np_d_img[np_d_img == 0] = np.NaN
np_d_img = np_d_img[:,:,np.newaxis]
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
return np_rgb_img, np_d_img
示例14: substract_mean
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import newaxis [as 别名]
def substract_mean(img, image_mean):
"""Substract image mean from data sample
image_mean is a numpy array,
either 1 * 3 or of the same size as input image
"""
if image_mean.ndim == 1:
image_mean = image_mean[:, np.newaxis, np.newaxis]
img -= image_mean
return img
示例15: evaluate
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import newaxis [as 别名]
def evaluate(self, points):
points = atleast_2d(points)
d, m = points.shape
if d != self.d:
if d == 1 and m == self.d:
# points was passed in as a row vector
points = reshape(points, (self.d, 1))
m = 1
else:
msg = "points have dimension %s, dataset has dimension %s" % (d,
self.d)
raise ValueError(msg)
result = zeros((m,), dtype=np.float)
if m >= self.n:
# there are more points than data, so loop over data
for i in range(self.n):
diff = self.dataset[:, i, newaxis] - points
tdiff = dot(self.inv_cov, diff)
energy = sum(diff*tdiff,axis=0) / 2.0
result = result + exp(-energy)
else:
# loop over points
for i in range(m):
diff = self.dataset - points[:, i, newaxis]
tdiff = dot(self.inv_cov, diff)
energy = sum(diff * tdiff, axis=0) / 2.0
result[i] = sum(exp(-energy), axis=0)
result = result / self._norm_factor
return result