本文整理汇总了Python中numpy.swapaxes方法的典型用法代码示例。如果您正苦于以下问题:Python numpy.swapaxes方法的具体用法?Python numpy.swapaxes怎么用?Python numpy.swapaxes使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类numpy
的用法示例。
在下文中一共展示了numpy.swapaxes方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: update
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import swapaxes [as 别名]
def update(self, xPhys, u, title=None):
"""Plot to screen"""
self.im.set_array(-xPhys.reshape((self.nelx, self.nely)).T)
stress = self.stress_calculator.calculate_stress(xPhys, u, self.nu)
# self.stress_calculator.calculate_fdiff_stress(xPhys, u, self.nu)
self.myColorMap.set_norm(colors.Normalize(vmin=0, vmax=max(stress)))
stress_rgba = self.myColorMap.to_rgba(stress)
stress_rgba[:, :, 3] = xPhys.reshape(-1, 1)
self.stress_im.set_array(np.swapaxes(
stress_rgba.reshape((self.nelx, self.nely, 4)), 0, 1))
self.fig.canvas.draw()
self.fig.canvas.flush_events()
if title is not None:
plt.title(title)
else:
plt.xlabel("Max stress = {:.2f}".format(max(stress)[0]))
plt.pause(0.01)
示例2: get_data
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import swapaxes [as 别名]
def get_data(img_path):
"""get the (1, 3, h, w) np.array data for the supplied image
Args:
img_path (string): the input image path
Returns:
np.array: image data in a (1, 3, h, w) shape
"""
mean = np.array([123.68, 116.779, 103.939]) # (R,G,B)
img = Image.open(img_path)
img = np.array(img, dtype=np.float32)
reshaped_mean = mean.reshape(1, 1, 3)
img = img - reshaped_mean
img = np.swapaxes(img, 0, 2)
img = np.swapaxes(img, 1, 2)
img = np.expand_dims(img, axis=0)
return img
示例3: PreprocessContentImage
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import swapaxes [as 别名]
def PreprocessContentImage(path, long_edge):
img = io.imread(path)
logging.info("load the content image, size = %s", img.shape[:2])
factor = float(long_edge) / max(img.shape[:2])
new_size = (int(img.shape[0] * factor), int(img.shape[1] * factor))
resized_img = transform.resize(img, new_size)
sample = np.asarray(resized_img) * 256
# swap axes to make image from (224, 224, 3) to (3, 224, 224)
sample = np.swapaxes(sample, 0, 2)
sample = np.swapaxes(sample, 1, 2)
# sub mean
sample[0, :] -= 123.68
sample[1, :] -= 116.779
sample[2, :] -= 103.939
logging.info("resize the content image to %s", new_size)
return np.resize(sample, (1, 3, sample.shape[1], sample.shape[2]))
示例4: PreprocessImage
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import swapaxes [as 别名]
def PreprocessImage(path, show_img=False):
# load image
img = io.imread(path)
print("Original Image Shape: ", img.shape)
# we crop image from center
short_egde = min(img.shape[:2])
yy = int((img.shape[0] - short_egde) / 2)
xx = int((img.shape[1] - short_egde) / 2)
crop_img = img[yy : yy + short_egde, xx : xx + short_egde]
# resize to 224, 224
resized_img = transform.resize(crop_img, (224, 224))
# convert to numpy.ndarray
sample = np.asarray(resized_img) * 255
# swap axes to make image from (224, 224, 3) to (3, 224, 224)
sample = np.swapaxes(sample, 0, 2)
sample = np.swapaxes(sample, 1, 2)
# sub mean
return sample
# Get preprocessed batch (single image batch)
示例5: linear_ensemble_strategy
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import swapaxes [as 别名]
def linear_ensemble_strategy(self, pred_mean, pred_var, ruitu_inputs, feature_name,\
timestep_to_ensemble=21, alpha=1):
'''
This stratergy aims to calculate linear weighted at specific timestep (timestep_to_ensemble) between prediction and ruitu as formula:
(alpha)*pred_mean + (1-alpha)*ruitu_inputs
pred_mean: (10, 37, 3)
pred_var: (10, 37, 3)
ruitu_inputs: (37,10,29). Need Swamp to(10,37,29) FIRSTLY!!
timestep_to_ensemble: int32 (From 0 to 36)
'''
assert 0<= alpha <=1, 'Please ensure 0<= alpha <=1 !'
assert pred_mean.shape == (10, 37, 3), 'Error! This funtion ONLY works for \
one data sample with shape (10, 37, 3). Any data shape (None, 10, 37, 3) will leads this error!'
#pred_std = np.sqrt(np.exp(pred_var))
ruitu_inputs = np.swapaxes(ruitu_inputs,0,1)
print('alpha:',alpha)
pred_mean[:,timestep_to_ensemble:,self.obs_and_output_feature_index_map[feature_name]] = \
(alpha)*pred_mean[:,timestep_to_ensemble:,self.obs_and_output_feature_index_map[feature_name]] + \
(1-alpha)*ruitu_inputs[:,timestep_to_ensemble:, self.ruitu_feature_index_map[feature_name]]
print('Corrected pred_mean shape:', pred_mean.shape)
return pred_mean
示例6: plot_ball_and_alpha
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import swapaxes [as 别名]
def plot_ball_and_alpha(alpha, trajectory, filename, cmap='Blues'):
f, ax = plt.subplots(nrows=1, ncols=2, figsize=[12, 6])
collection = construct_ball_trajectory(trajectory, r=1., cmap=cmap)
x_min, y_min = np.min(trajectory, axis=0)
x_max, y_max = np.max(trajectory, axis=0)
ax[0].add_collection(collection)
ax[0].set_xlim([x_min, x_max])
ax[0].set_ylim([y_min, y_max])
# ax[0].set_xticks([])
# ax[0].set_yticks([])
ax[0].axis("equal")
for line in np.swapaxes(alpha, 1, 0):
ax[1].plot(line, linestyle='-')
plt.savefig(filename, format='png', bbox_inches='tight', dpi=80)
plt.close()
示例7: save_movies_to_frame
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import swapaxes [as 别名]
def save_movies_to_frame(images, filename, cmap='Blues'):
# Binarize images
# images[images > 0] = 1.
# Grid images
images = np.swapaxes(images, 1, 0)
images = np.array([combine_multiple_img(image) for image in images])
# Collect to single image
image = movie_to_frame(images)
f = plt.figure(figsize=[12, 12])
plt.imshow(image, cmap=plt.cm.get_cmap(cmap), interpolation='none', vmin=0, vmax=1)
plt.axis('image')
plt.savefig(filename, format='png', bbox_inches='tight', dpi=80)
plt.close(f)
示例8: tensor_cnn_frame
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import swapaxes [as 别名]
def tensor_cnn_frame(mat, M):
"""Construct a tensor of shape (C x H x W) given an utterance matrix
for CNN
"""
slice_mat = []
for index in np.arange(len(mat)):
if index < M:
to_left = np.tile(mat[index], M).reshape((M,-1))
rest = mat[index:index+M+1]
context = np.vstack((to_left, rest))
elif index >= len(mat)-M:
to_right = np.tile(mat[index], M).reshape((M,-1))
rest = mat[index-M:index+1]
context = np.vstack((rest, to_right))
else:
context = mat[index-M:index+M+1]
slice_mat.append(context)
slice_mat = np.array(slice_mat)
slice_mat = np.expand_dims(slice_mat, axis=1)
slice_mat = np.swapaxes(slice_mat, 2, 3)
return slice_mat
示例9: tensor_cnngru
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import swapaxes [as 别名]
def tensor_cnngru(mat):
"""Construct an utterance tensor for a given utterance matrix mat
for CNN+GRU
"""
mat = np.swapaxes(mat, 0, 1)
div = int(mat.shape[1]/400)
if div == 0: # short utt
tensor_mat = mat
while True:
shape = tensor_mat.shape[1]
if shape + mat.shape[1] < 400:
tensor_mat = np.hstack((tensor_mat,mat))
else:
tensor_mat = np.hstack((tensor_mat,mat[:,:400-shape]))
break
elif div == 1: # truncate to 1
tensor_mat = mat[:,:400]
else:
# TO DO: cut into 2
tensor_mat = mat[:,:400]
tensor_mat = np.expand_dims(tensor_mat, axis=2)
print(tensor_mat.shape)
return tensor_mat
示例10: doperation
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import swapaxes [as 别名]
def doperation(self, opLabel, flat=False, wrtFilter=None):
""" Return the derivative of a length-1 (single-gate) sequence """
dim = self.dim
gate = self.sos.get_operation(opLabel)
op_wrtFilter, gpindices = self._process_wrtFilter(wrtFilter, gate)
# Allocate memory for the final result
num_deriv_cols = self.Np if (wrtFilter is None) else len(wrtFilter)
flattened_dprod = _np.zeros((dim**2, num_deriv_cols), 'd')
_fas(flattened_dprod, [None, gpindices],
gate.deriv_wrt_params(op_wrtFilter)) # (dim**2, nParams[opLabel])
if _slct.length(gpindices) > 0: # works for arrays too
# Compute the derivative of the entire operation sequence with respect to the
# gate's parameters and fill appropriate columns of flattened_dprod.
#gate = self.sos.get_operation[opLabel] UNNEEDED (I think)
_fas(flattened_dprod, [None, gpindices],
gate.deriv_wrt_params(op_wrtFilter)) # (dim**2, nParams in wrtFilter for opLabel)
if flat:
return flattened_dprod
else:
# axes = (gate_ij, prod_row, prod_col)
return _np.swapaxes(flattened_dprod, 0, 1).reshape((num_deriv_cols, dim, dim))
示例11: setup
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import swapaxes [as 别名]
def setup(self):
self.data = [
# Array scalars
(np.array(3.), None),
(np.array(3), 'f8'),
# 1D arrays
(np.arange(6, dtype='f4'), None),
(np.arange(6), 'c16'),
# 2D C-layout arrays
(np.arange(6).reshape(2, 3), None),
(np.arange(6).reshape(3, 2), 'i1'),
# 2D F-layout arrays
(np.arange(6).reshape((2, 3), order='F'), None),
(np.arange(6).reshape((3, 2), order='F'), 'i1'),
# 3D C-layout arrays
(np.arange(24).reshape(2, 3, 4), None),
(np.arange(24).reshape(4, 3, 2), 'f4'),
# 3D F-layout arrays
(np.arange(24).reshape((2, 3, 4), order='F'), None),
(np.arange(24).reshape((4, 3, 2), order='F'), 'f4'),
# 3D non-C/F-layout arrays
(np.arange(24).reshape(2, 3, 4).swapaxes(0, 1), None),
(np.arange(24).reshape(4, 3, 2).swapaxes(0, 1), '?'),
]
示例12: iswapaxes
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import swapaxes [as 别名]
def iswapaxes(self, axis1, axis2):
"""Similar as ``np.swapaxes``; in place."""
axis1 = self.get_leg_index(axis1)
axis2 = self.get_leg_index(axis2)
if axis1 == axis2:
return self # nothing to do
swap = np.arange(self.rank, dtype=np.intp)
swap[axis1], swap[axis2] = axis2, axis1
legs = self.legs
legs[axis1], legs[axis2] = legs[axis2], legs[axis1]
labels = self._labels
labels[axis1], labels[axis2] = labels[axis2], labels[axis1]
self._set_shape()
self._qdata = self._qdata[:, swap]
self._qdata_sorted = False
self._data = [t.swapaxes(axis1, axis2) for t in self._data]
return self
示例13: _rmatvec_forward
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import swapaxes [as 别名]
def _rmatvec_forward(self, x):
if not self.reshape:
x = x.squeeze()
y = np.zeros(self.N, self.dtype)
y[:-1] -= x[:-1] / self.sampling
y[1:] += x[:-1] / self.sampling
else:
x = np.reshape(x, self.dims)
if self.dir > 0: # need to bring the dim. to derive to first dim.
x = np.swapaxes(x, self.dir, 0)
y = np.zeros(x.shape, self.dtype)
y[:-1] -= x[:-1] / self.sampling
y[1:] += x[:-1] / self.sampling
if self.dir > 0:
y = np.swapaxes(y, 0, self.dir)
y = y.ravel()
return y
示例14: _matvec_centered
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import swapaxes [as 别名]
def _matvec_centered(self, x):
if not self.reshape:
x = x.squeeze()
y = np.zeros(self.N, self.dtype)
y[1:-1] = (0.5 * x[2:] - 0.5 * x[0:-2]) / self.sampling
if self.edge:
y[0] = (x[1] - x[0]) / self.sampling
y[-1] = (x[-1] - x[-2]) / self.sampling
else:
x = np.reshape(x, self.dims)
if self.dir > 0: # need to bring the dim. to derive to first dim.
x = np.swapaxes(x, self.dir, 0)
y = np.zeros(x.shape, self.dtype)
y[1:-1] = (0.5 * x[2:] - 0.5 * x[0:-2]) / self.sampling
if self.edge:
y[0] = (x[1] - x[0]) / self.sampling
y[-1] = (x[-1] - x[-2]) / self.sampling
if self.dir > 0:
y = np.swapaxes(y, 0, self.dir)
y = y.ravel()
return y
示例15: _rmatvec_backward
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import swapaxes [as 别名]
def _rmatvec_backward(self, x):
if not self.reshape:
x = x.squeeze()
y = np.zeros(self.N, self.dtype)
y[:-1] -= x[1:] / self.sampling
y[1:] += x[1:] / self.sampling
else:
x = np.reshape(x, self.dims)
if self.dir > 0: # need to bring the dim. to derive to first dim.
x = np.swapaxes(x, self.dir, 0)
y = np.zeros(x.shape, self.dtype)
y[:-1] -= x[1:] / self.sampling
y[1:] += x[1:] / self.sampling
if self.dir > 0:
y = np.swapaxes(y, 0, self.dir)
y = y.ravel()
return y