本文整理汇总了Python中numpy.reshape方法的典型用法代码示例。如果您正苦于以下问题:Python numpy.reshape方法的具体用法?Python numpy.reshape怎么用?Python numpy.reshape使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类numpy
的用法示例。
在下文中一共展示了numpy.reshape方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: set_values
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import reshape [as 别名]
def set_values(name, param, pretrained):
#{{{
"""
Initialize a network parameter with pretrained values.
We check that sizes are compatible.
"""
param_value = param.get_value()
if pretrained.size != param_value.size:
raise Exception(
"Size mismatch for parameter %s. Expected %i, found %i."
% (name, param_value.size, pretrained.size)
)
param.set_value(np.reshape(
pretrained, param_value.shape
).astype(np.float32))
#}}}
示例2: mtx_freq2visi
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import reshape [as 别名]
def mtx_freq2visi(M, p_mic_x, p_mic_y):
"""
build the matrix that maps the Fourier series to the visibility
:param M: the Fourier series expansion is limited from -M to M
:param p_mic_x: a vector that constains microphones x coordinates
:param p_mic_y: a vector that constains microphones y coordinates
:return:
"""
num_mic = p_mic_x.size
ms = np.reshape(np.arange(-M, M + 1, step=1), (1, -1), order='F')
G = np.zeros((num_mic * (num_mic - 1), 2 * M + 1), dtype=complex, order='C')
count_G = 0
for q in range(num_mic):
p_x_outer = p_mic_x[q]
p_y_outer = p_mic_y[q]
for qp in range(num_mic):
if not q == qp:
p_x_qqp = p_x_outer - p_mic_x[qp]
p_y_qqp = p_y_outer - p_mic_y[qp]
norm_p_qqp = np.sqrt(p_x_qqp ** 2 + p_y_qqp ** 2)
phi_qqp = np.arctan2(p_y_qqp, p_x_qqp)
G[count_G, :] = (-1j) ** ms * sp.special.jv(ms, norm_p_qqp) * \
np.exp(1j * ms * phi_qqp)
count_G += 1
return G
示例3: mtx_updated_G
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import reshape [as 别名]
def mtx_updated_G(phi_recon, M, mtx_amp2visi_ri, mtx_fri2visi_ri):
"""
Update the linear transformation matrix that links the FRI sequence to the
visibilities by using the reconstructed Dirac locations.
:param phi_recon: the reconstructed Dirac locations (azimuths)
:param M: the Fourier series expansion is between -M to M
:param p_mic_x: a vector that contains microphones' x-coordinates
:param p_mic_y: a vector that contains microphones' y-coordinates
:param mtx_freq2visi: the linear mapping from Fourier series to visibilities
:return:
"""
L = 2 * M + 1
ms_half = np.reshape(np.arange(-M, 1, step=1), (-1, 1), order='F')
phi_recon = np.reshape(phi_recon, (1, -1), order='F')
mtx_amp2freq = np.exp(-1j * ms_half * phi_recon) # size: (M + 1) x K
mtx_amp2freq_ri = np.vstack((mtx_amp2freq.real, mtx_amp2freq.imag[:-1, :])) # size: (2M + 1) x K
mtx_fri2amp_ri = linalg.lstsq(mtx_amp2freq_ri, np.eye(L))[0]
# projection mtx_freq2visi to the null space of mtx_fri2amp
mtx_null_proj = np.eye(L) - np.dot(mtx_fri2amp_ri.T,
linalg.lstsq(mtx_fri2amp_ri.T, np.eye(L))[0])
G_updated = np.dot(mtx_amp2visi_ri, mtx_fri2amp_ri) + \
np.dot(mtx_fri2visi_ri, mtx_null_proj)
return G_updated
示例4: __getitem__
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import reshape [as 别名]
def __getitem__(self, index):
img=self.adv_flat[self.sample_num,:]
if(self.shuff == False):
# shuff is true for non-pgd attacks
img = torch.from_numpy(np.reshape(img,(3,32,32)))
else:
img = torch.from_numpy(img).type(torch.FloatTensor)
target = np.argmax(self.adv_dict["adv_labels"],axis=1)[self.sample_num]
# doing this so that it is consistent with all other datasets
# to return a PIL Image
if self.transform is not None:
img = self.transform(img)
if self.target_transform is not None:
target = self.target_transform(target)
self.sample_num = self.sample_num + 1
return img, target
示例5: __getitem__
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import reshape [as 别名]
def __getitem__(self, index):
img=self.adv_flat[self.sample_num,:]
if(self.transp == False):
# shuff is true for non-pgd attacks
img = torch.from_numpy(np.reshape(img,(28,28)))
else:
img = torch.from_numpy(img).type(torch.FloatTensor)
target = np.argmax(self.adv_dict["adv_labels"],axis=1)[self.sample_num]
# doing this so that it is consistent with all other datasets
# to return a PIL Image
if self.transform is not None:
img = self.transform(img)
if self.target_transform is not None:
target = self.target_transform(target)
self.sample_num = self.sample_num + 1
return img, target
示例6: train_lr_rfeinman
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import reshape [as 别名]
def train_lr_rfeinman(densities_pos, densities_neg, uncerts_pos, uncerts_neg):
"""
TODO
:param densities_pos:
:param densities_neg:
:param uncerts_pos:
:param uncerts_neg:
:return:
"""
values_neg = np.concatenate(
(densities_neg.reshape((1, -1)),
uncerts_neg.reshape((1, -1))),
axis=0).transpose([1, 0])
values_pos = np.concatenate(
(densities_pos.reshape((1, -1)),
uncerts_pos.reshape((1, -1))),
axis=0).transpose([1, 0])
values = np.concatenate((values_neg, values_pos))
labels = np.concatenate(
(np.zeros_like(densities_neg), np.ones_like(densities_pos)))
lr = LogisticRegressionCV(n_jobs=-1).fit(values, labels)
return values, labels, lr
示例7: auto_inverse
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import reshape [as 别名]
def auto_inverse(self, whole_spectrum):
whole_spectrum = np.copy(whole_spectrum).astype(complex)
whole_spectrum[whole_spectrum < 1] = 1
overwrap = self.buffer_size * 2
height = whole_spectrum.shape[0]
parallel_dif = (height-overwrap) // self.parallel
if height < self.parallel*overwrap:
raise Exception('voice length is too small to use gpu, or parallel number is too big')
spec = [self.inverse(whole_spectrum[range(i, i+parallel_dif*self.parallel, parallel_dif), :]) for i in tqdm.tqdm(range(parallel_dif+overwrap))]
spec = spec[overwrap:]
spec = np.concatenate(spec, axis=1)
spec = spec.reshape(-1, self.wave_len)
#Below code don't consider wave_len and wave_dif, I'll fix.
wave = np.fft.ifft(spec, axis=1).real
pad = np.zeros((wave.shape[0], 2), dtype=float)
wave = np.concatenate([wave, pad], axis=1)
dst = np.zeros((wave.shape[0]+3)*self.wave_dif, dtype=float)
for i in range(4):
w = wave[range(i, wave.shape[0], 4),:]
w = w.reshape(-1)
dst[i*self.wave_dif:i*self.wave_dif+len(w)] += w
return dst*0.5
示例8: wave2input_image
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import reshape [as 别名]
def wave2input_image(wave, window, pos=0, pad=0):
wave_image = np.hstack([wave[pos+i*sride:pos+(i+pad*2)*sride+dif].reshape(height+pad*2, sride) for i in range(256//sride)])[:,:254]
wave_image *= window
spectrum_image = np.fft.fft(wave_image, axis=1)
input_image = np.abs(spectrum_image[:,:128].reshape(1, height+pad*2, 128), dtype=np.float32)
np.clip(input_image, 1000, None, out=input_image)
np.log(input_image, out=input_image)
input_image += bias
input_image /= scale
if np.max(input_image) > 0.95:
print('input image max bigger than 0.95', np.max(input_image))
if np.min(input_image) < 0.05:
print('input image min smaller than 0.05', np.min(input_image))
return input_image
示例9: plot_n_image
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import reshape [as 别名]
def plot_n_image(X, n):
""" plot first n images
n has to be a square number
"""
pic_size = int(np.sqrt(X.shape[1]))
grid_size = int(np.sqrt(n))
first_n_images = X[:n, :]
fig, ax_array = plt.subplots(nrows=grid_size, ncols=grid_size,
sharey=True, sharex=True, figsize=(8, 8))
for r in range(grid_size):
for c in range(grid_size):
ax_array[r, c].imshow(first_n_images[grid_size * r + c].reshape((pic_size, pic_size)))
plt.xticks(np.array([]))
plt.yticks(np.array([]))
示例10: parse_dataobj
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import reshape [as 别名]
def parse_dataobj(self, dataobj, hdat={}):
# first, see if we have a specified shape/size
ish = next((hdat[k] for k in ('image_size', 'image_shape', 'shape') if k in hdat), None)
if ish is Ellipsis: ish = None
# make a numpy array of the appropriate dtype
dtype = self.parse_type(hdat, dataobj=dataobj)
try: dataobj = dataobj.dataobj
except Exception: pass
if dataobj is not None: arr = np.asarray(dataobj).astype(dtype)
elif ish: arr = np.zeros(ish, dtype=dtype)
else: arr = np.zeros([1,1,1,0], dtype=dtype)
# reshape to the requested shape if need-be
if ish and ish != arr.shape: arr = np.reshape(arr, ish)
# then reshape to a valid (4D) shape
sh = arr.shape
if len(sh) == 2: arr = np.reshape(arr, (sh[0], 1, 1, sh[1]))
elif len(sh) == 1: arr = np.reshape(arr, (sh[0], 1, 1))
elif len(sh) == 3: arr = np.reshape(arr, sh)
elif len(sh) != 4: raise ValueError('Cannot convert n-dimensional array to image if n > 4')
# and return
return arr
示例11: image_reslice
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import reshape [as 别名]
def image_reslice(image, spec, method=None, fill=0, dtype=None, weights=None, image_type=None):
'''
image_reslice(image, spec) yields a duplicate of the given image resliced to have the voxels
indicated by the given image spec. Note that spec may be an image itself.
Optional arguments that can be passed to image_interpolate() (asside from affine) are allowed
here and are passed through.
'''
if image_type is None and is_image(image): image_type = to_image_type(image)
spec = to_image_spec(spec)
image = to_image(image)
# we make a big mesh and interpolate at these points...
imsh = spec['image_shape']
(args, kw) = ([np.arange(n) for n in imsh[:3]], {'indexing': 'ij'})
ijk = np.asarray([u.flatten() for u in np.meshgrid(*args, **kw)])
ijk = np.dot(spec['affine'], np.vstack([ijk, np.ones([1,ijk.shape[1]])]))[:3]
# interpolate here...
u = image_interpolate(image, ijk, method=method, fill=fill, dtype=dtype, weights=weights)
return to_image((np.reshape(u, imsh), spec), image_type=image_type)
示例12: point_on_segment
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import reshape [as 别名]
def point_on_segment(ac, b, atol=1e-8):
'''
point_on_segment((a,b), c) yields True if point x is on segment (a,b) and False otherwise. Note
that this differs from point_in_segment in that a point that if c is equal to a or b it is
considered 'on' but not 'in' the segment.
The option atol can be given and is used only to test for difference from 0; by default it is
1e-8.
'''
(a,c) = ac
abc = [np.asarray(u) for u in (a,b,c)]
if any(len(u.shape) > 1 for u in abc): (a,b,c) = [np.reshape(u,(len(u),-1)) for u in abc]
else: (a,b,c) = abc
vab = b - a
vbc = c - b
vac = c - a
dab = np.sqrt(np.sum(vab**2, axis=0))
dbc = np.sqrt(np.sum(vbc**2, axis=0))
dac = np.sqrt(np.sum(vac**2, axis=0))
return np.isclose(dab + dbc - dac, 0, atol=atol)
示例13: point_in_segment
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import reshape [as 别名]
def point_in_segment(ac, b, atol=1e-8):
'''
point_in_segment((a,b), c) yields True if point x is in segment (a,b) and False otherwise. Note
that this differs from point_on_segment in that a point that if c is equal to a or b it is
considered 'on' but not 'in' the segment.
The option atol can be given and is used only to test for difference from 0; by default it is
1e-8.
'''
(a,c) = ac
abc = [np.asarray(u) for u in (a,b,c)]
if any(len(u.shape) > 1 for u in abc): (a,b,c) = [np.reshape(u,(len(u),-1)) for u in abc]
else: (a,b,c) = abc
vab = b - a
vbc = c - b
vac = c - a
dab = np.sqrt(np.sum(vab**2, axis=0))
dbc = np.sqrt(np.sum(vbc**2, axis=0))
dac = np.sqrt(np.sum(vac**2, axis=0))
return (np.isclose(dab + dbc - dac, 0, atol=atol) &
~np.isclose(dac - dab, 0, atol=atol) &
~np.isclose(dac - dbc, 0, atol=atol))
示例14: row_norms
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import reshape [as 别名]
def row_norms(ii, f=Ellipsis, squared=False):
'''
row_norms(ii) yields a potential function h(x) that calculates the vector norms of the rows of
the matrix formed by [x[i] for i in ii] (ii is a matrix of parameter indices).
row_norms(ii, f) yield a potential function h(x) equivalent to compose(row_norms(ii), f).
'''
try:
(n,m) = ii
# matrix shape given
ii = np.reshape(np.arange(n*m), (n,m))
except Exception: ii = np.asarray(ii)
f = to_potential(f)
if is_const_potential(f):
q = flattest(f.c)
q = np.sum([q[i]**2 for i in ii.T], axis=0)
return PotentialConstant(q if squared else np.sqrt(q))
F = reduce(lambda a,b: a + b, [part(Ellipsis, col)**2 for col in ii.T])
F = compose(F, f)
if not squared: F = sqrt(F)
return F
示例15: col_norms
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import reshape [as 别名]
def col_norms(ii, f=Ellipsis, squared=False):
'''
col_norms(ii) yields a potential function h(x) that calculates the vector norms of the columns
of the matrix formed by [x[i] for i in ii] (ii is a matrix of parameter indices).
col_norms(ii, f) yield a potential function h(x) equivalent to compose(col_norms(ii), f).
'''
try:
(n,m) = ii
# matrix shape given
ii = np.reshape(np.arange(n*m), (n,m))
except Exception: ii = np.asarray(ii)
f = to_potential(f)
if is_const_potential(f):
q = flattest(f.c)
q = np.sum([q[i]**2 for i in ii], axis=0)
return PotentialConstant(q if squared else np.sqrt(q))
F = reduce(lambda a,b: a + b, [part(Ellipsis, col)**2 for col in ii])
F = compose(F, f)
if not squared: F = sqrt(F)
return F