python linspace函数_Python torch.linspace方法代碼示例

本文整理匯總了Python中torch.linspace方法的典型用法代碼示例。如果您正苦於以下問題:Python torch.linspace方法的具體用法?Python torch.linspace怎麽用?Python torch.linspace使用的例子?那麽恭喜您, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在模塊torch的用法示例。

在下文中一共展示了torch.linspace方法的27個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於我們的係統推薦出更棒的Python代碼示例。

示例1: _fade_in

​點讚 6

# 需要導入模塊: import torch [as 別名]

# 或者: from torch import linspace [as 別名]

def _fade_in(self, waveform_length: int) -> Tensor:

fade = torch.linspace(0, 1, self.fade_in_len)

ones = torch.ones(waveform_length - self.fade_in_len)

if self.fade_shape == "linear":

fade = fade

if self.fade_shape == "exponential":

fade = torch.pow(2, (fade - 1)) * fade

if self.fade_shape == "logarithmic":

fade = torch.log10(.1 + fade) + 1

if self.fade_shape == "quarter_sine":

fade = torch.sin(fade * math.pi / 2)

if self.fade_shape == "half_sine":

fade = torch.sin(fade * math.pi - math.pi / 2) / 2 + 0.5

return torch.cat((fade, ones)).clamp_(0, 1)

開發者ID:pytorch,項目名稱:audio,代碼行數:22,

示例2: _fade_out

​點讚 6

# 需要導入模塊: import torch [as 別名]

# 或者: from torch import linspace [as 別名]

def _fade_out(self, waveform_length: int) -> Tensor:

fade = torch.linspace(0, 1, self.fade_out_len)

ones = torch.ones(waveform_length - self.fade_out_len)

if self.fade_shape == "linear":

fade = - fade + 1

if self.fade_shape == "exponential":

fade = torch.pow(2, - fade) * (1 - fade)

if self.fade_shape == "logarithmic":

fade = torch.log10(1.1 - fade) + 1

if self.fade_shape == "quarter_sine":

fade = torch.sin(fade * math.pi / 2 + math.pi / 2)

if self.fade_shape == "half_sine":

fade = torch.sin(fade * math.pi + math.pi / 2) / 2 + 0.5

return torch.cat((ones, fade)).clamp_(0, 1)

開發者ID:pytorch,項目名稱:audio,代碼行數:22,

示例3: backwarp

​點讚 6

# 需要導入模塊: import torch [as 別名]

# 或者: from torch import linspace [as 別名]

def backwarp(tenInput, tenFlow):

if str(tenFlow.size()) not in backwarp_tenGrid:

tenHorizontal = torch.linspace(-1.0, 1.0, tenFlow.shape[3]).view(1, 1, 1, tenFlow.shape[3]).expand(tenFlow.shape[0], -1, tenFlow.shape[2], -1)

tenVertical = torch.linspace(-1.0, 1.0, tenFlow.shape[2]).view(1, 1, tenFlow.shape[2], 1).expand(tenFlow.shape[0], -1, -1, tenFlow.shape[3])

backwarp_tenGrid[str(tenFlow.size())] = torch.cat([ tenHorizontal, tenVertical ], 1).cuda()

# end

if str(tenFlow.size()) not in backwarp_tenPartial:

backwarp_tenPartial[str(tenFlow.size())] = tenFlow.new_ones([ tenFlow.shape[0], 1, tenFlow.shape[2], tenFlow.shape[3] ])

# end

tenFlow = torch.cat([ tenFlow[:, 0:1, :, :] / ((tenInput.shape[3] - 1.0) / 2.0), tenFlow[:, 1:2, :, :] / ((tenInput.shape[2] - 1.0) / 2.0) ], 1)

tenInput = torch.cat([ tenInput, backwarp_tenPartial[str(tenFlow.size())] ], 1)

tenOutput = torch.nn.functional.grid_sample(input=tenInput, grid=(backwarp_tenGrid[str(tenFlow.size())] + tenFlow).permute(0, 2, 3, 1), mode='bilinear', padding_mode='zeros', align_corners=True)

tenMask = tenOutput[:, -1:, :, :]; tenMask[tenMask > 0.999] = 1.0; tenMask[tenMask < 1.0] = 0.0

return tenOutput[:, :-1, :, :] * tenMask

# end

##########################################################

開發者ID:sniklaus,項目名稱:pytorch-pwc,代碼行數:25,

示例4: test_geodesic_segment_length_property

​點讚 6

# 需要導入模塊: import torch [as 別名]

# 或者: from torch import linspace [as 別名]

def test_geodesic_segment_length_property(a, b, manifold, dtype):

extra_dims = len(a.shape)

segments = 12

t = torch.linspace(0, 1, segments + 1, dtype=dtype).view(

(segments + 1,) + (1,) * extra_dims

)

gamma_ab_t = manifold.geodesic(t, a, b)

gamma_ab_t0 = gamma_ab_t[:-1]

gamma_ab_t1 = gamma_ab_t[1:]

dist_ab_t0mt1 = manifold.dist(gamma_ab_t0, gamma_ab_t1, keepdim=True)

speed = manifold.dist(a, b, keepdim=True).unsqueeze(0).expand_as(dist_ab_t0mt1)

# we have exactly 12 line segments

tolerance = {

torch.float32: dict(rtol=1e-5, atol=5e-3),

torch.float64: dict(rtol=1e-5, atol=5e-3),

}

length = speed / segments

np.testing.assert_allclose(

dist_ab_t0mt1.detach(), length.detach(), **tolerance[dtype]

)

(length + dist_ab_t0mt1).sum().backward()

assert torch.isfinite(a.grad).all()

assert torch.isfinite(b.grad).all()

assert torch.isfinite(manifold.k.grad).all()

開發者ID:geoopt,項目名稱:geoopt,代碼行數:26,

示例5: test_geodesic_segement_unit_property

​點讚 6

# 需要導入模塊: import torch [as 別名]

# 或者: from torch import linspace [as 別名]

def test_geodesic_segement_unit_property(a, b, manifold, dtype):

extra_dims = len(a.shape)

segments = 12

t = torch.linspace(0, 1, segments + 1, dtype=dtype).view(

(segments + 1,) + (1,) * extra_dims

)

gamma_ab_t = manifold.geodesic_unit(t, a, b)

gamma_ab_t0 = gamma_ab_t[:1]

gamma_ab_t1 = gamma_ab_t

dist_ab_t0mt1 = manifold.dist(gamma_ab_t0, gamma_ab_t1, keepdim=True)

true_distance_travelled = t.expand_as(dist_ab_t0mt1)

# we have exactly 12 line segments

tolerance = {

torch.float32: dict(atol=2e-4, rtol=5e-5),

torch.float64: dict(atol=1e-10),

}

np.testing.assert_allclose(

dist_ab_t0mt1.detach(), true_distance_travelled.detach(), **tolerance[dtype]

)

(true_distance_travelled + dist_ab_t0mt1).sum().backward()

assert torch.isfinite(a.grad).all()

assert torch.isfinite(b.grad).all()

assert torch.isfinite(manifold.k.grad).all()

開發者ID:geoopt,項目名稱:geoopt,代碼行數:25,

示例6: imwrap_BCHW0

​點讚 6

# 需要導入模塊: import torch [as 別名]

# 或者: from torch import linspace [as 別名]

def imwrap_BCHW0(im_src, disp):

# imwrap

bn, c, h, w = im_src.shape

row = torch.linspace(-1, 1, w)

col = torch.linspace(-1, 1, h)

grid = torch.zeros(bn, h, w, 2)

for n in range(bn):

for i in range(h):

grid[n, i, :, 0] = row

for i in range(w):

grid[n, :, i, 1] = col

grid = Variable(grid, requires_grad=True).type_as(im_src)

grid[:, :, :, 0] = grid[:, :, :, 0] - disp.squeeze(1)*2/w

#print disp[-1, -1, -1], grid[-1, -1, -1, 0]

im_src.clamp(min=1e-6)

im_wrap = F.grid_sample(im_src, grid)

return im_wrap

開發者ID:wyf2017,項目名稱:DSMnet,代碼行數:19,

示例7: _init_buffers

​點讚 6

# 需要導入模塊: import torch [as 別名]

# 或者: from torch import linspace [as 別名]

def _init_buffers(self):

m_min = 0. if self.f_min == 0 else 2595 * np.log10(1. + (self.f_min / 700))

m_max = 2595 * np.log10(1. + (self.f_max / 700))

m_pts = torch.linspace(m_min, m_max, self.n_mels + 2)

f_pts = (700 * (10**(m_pts / 2595) - 1))

bins = torch.floor(((self.n_fft - 1) * 2) * f_pts / self.sr).long()

fb = torch.zeros(self.n_fft, self.n_mels)

for m in range(1, self.n_mels + 1):

f_m_minus = bins[m - 1].item()

f_m = bins[m].item()

f_m_plus = bins[m + 1].item()

if f_m_minus != f_m:

fb[f_m_minus:f_m, m - 1] = (torch.arange(f_m_minus, f_m) - f_m_minus) / (f_m - f_m_minus)

if f_m != f_m_plus:

fb[f_m:f_m_plus, m - 1] = (f_m_plus - torch.arange(f_m, f_m_plus)) / (f_m_plus - f_m)

self.register_buffer("fb", fb)

開發者ID:daemon,項目名稱:pytorch-pcen,代碼行數:22,

示例8: __init__

​點讚 6

# 需要導入模塊: import torch [as 別名]

# 或者: from torch import linspace [as 別名]

def __init__(self, max_disp, start_disp=0, dilation=1, alpha=1.0, normalize=True):

super(FasterSoftArgmin, self).__init__()

self.max_disp = max_disp

self.start_disp = start_disp

self.dilation = dilation

self.end_disp = start_disp + max_disp - 1

self.disp_sample_number = (max_disp + dilation - 1) // dilation

self.alpha = alpha

self.normalize = normalize

# compute disparity index: (1 ,1, disp_sample_number, 1, 1)

disp_sample = torch.linspace(

self.start_disp, self.end_disp, self.disp_sample_number

)

disp_sample = disp_sample.repeat(1, 1, 1, 1, 1).permute(0, 1, 4, 2, 3).contiguous()

self.disp_regression = nn.Conv3d(1, 1, (self.disp_sample_number, 1, 1), 1, 0, bias=False)

self.disp_regression.weight.data = disp_sample

self.disp_regression.weight.requires_grad = False

開發者ID:DeepMotionAIResearch,項目名稱:DenseMatchingBenchmark,代碼行數:23,

示例9: test_speed

​點讚 6

# 需要導入模塊: import torch [as 別名]

# 或者: from torch import linspace [as 別名]

def test_speed(self):

max_disp = 192

scale = 4

start_disp = 0

dilation = 1

SH, SW = 540, 960

B, C, H, W = 1, 32, SH//scale, SW//scale

reference_fm = torch.rand(B, C, H, W).to(self.device)

target_fm = torch.rand(B, C, H, W).to(self.device)

self.timeTemplate(cat_fms, 'CAT_FMS', reference_fm, target_fm, max_disp//scale, start_disp, dilation)

self.timeTemplate(fast_cat_fms, 'FAST_CAT_FMS', reference_fm, target_fm, max_disp//scale, start_disp, dilation)

print('Test fast_cat_fms with disparity samples')

d = (max_disp + dilation - 1) // dilation

end_disp = start_disp + max_disp - 1

# generate disparity samples

disp_samples = torch.linspace(start_disp, end_disp, d).repeat(1, H, W, 1). \

permute(0, 3, 1, 2).contiguous().to(self.device)

self.timeTemplate(fast_cat_fms, 'FAST_CAT_FMS', reference_fm, target_fm, max_disp//scale, start_disp, dilation, disp_samples)

開發者ID:DeepMotionAIResearch,項目名稱:DenseMatchingBenchmark,代碼行數:27,

示例10: _sample_ortho_batch

​點讚 6

# 需要導入模塊: import torch [as 別名]

# 或者: from torch import linspace [as 別名]

def _sample_ortho_batch(self, mu, dim):

"""

:param mu: Variable, [batch size, latent dim]

:param dim: scala. =latent dim

:return:

"""

_batch_sz, _lat_dim = mu.size()

assert _lat_dim == dim

squeezed_mu = mu.unsqueeze(1)

v = GVar(torch.randn(_batch_sz, dim, 1)) # TODO random

# v = GVar(torch.linspace(-1, 1, steps=dim))

# v = v.expand(_batch_sz, dim).unsqueeze(2)

rescale_val = torch.bmm(squeezed_mu, v).squeeze(2)

proj_mu_v = mu * rescale_val

ortho = v.squeeze() - proj_mu_v

ortho_norm = torch.norm(ortho, p=2, dim=1, keepdim=True)

y = ortho / ortho_norm

return y

開發者ID:jiacheng-xu,項目名稱:vmf_vae_nlp,代碼行數:24,

示例11: _sample_orthonormal_to

​點讚 6

# 需要導入模塊: import torch [as 別名]

# 或者: from torch import linspace [as 別名]

def _sample_orthonormal_to(self, mu, dim):

"""Sample point on sphere orthogonal to mu.

"""

v = GVar(torch.randn(dim)) # TODO random

# v = GVar(torch.linspace(-1,1,steps=dim))

rescale_value = mu.dot(v) / mu.norm()

proj_mu_v = mu * rescale_value.expand(dim)

ortho = v - proj_mu_v

ortho_norm = torch.norm(ortho)

return ortho / ortho_norm.expand_as(ortho)

#

# a = torch.tensor(10)

# b = torch.ones(1, dtype=torch.float, requires_grad=True)

#

# y = bessel(a, b)

# loss = 1 - y

# print(y)

# loss.backward()

# print(a)

開發者ID:jiacheng-xu,項目名稱:vmf_vae_nlp,代碼行數:25,

示例12: _sample_orthonormal_to

​點讚 6

# 需要導入模塊: import torch [as 別名]

# 或者: from torch import linspace [as 別名]

def _sample_orthonormal_to(self, mu, dim):

"""Sample point on sphere orthogonal to mu.

"""

v = GVar(torch.randn(dim)) # TODO random

# v = GVar(torch.linspace(-1,1,steps=dim))

rescale_value = mu.dot(v) / mu.norm()

proj_mu_v = mu * rescale_value.expand(dim)

ortho = v - proj_mu_v

ortho_norm = torch.norm(ortho)

return ortho / ortho_norm.expand_as(ortho)

# vmf = vMF_fast(50, 100, 100)

# batchsz = 100

#

# mu = torch.FloatTensor(np.random.uniform(0, 1, 20 * batchsz))

# mu = mu.view(batchsz, -1)

# mu = mu / torch.norm(mu, p=2, dim=1, keepdim=True)

# vmf.sample_cell(mu, None, 100)

# x = vMF(10,lat_dim=50,kappa=50)

開發者ID:jiacheng-xu,項目名稱:vmf_vae_nlp,代碼行數:23,

示例13: forward

​點讚 6

# 需要導入模塊: import torch [as 別名]

# 或者: from torch import linspace [as 別名]

def forward(self, image, flow):

flow_for_grip = torch.zeros_like(flow)

flow_for_grip[:,0,:,:] = flow[:,0,:,:] / ((flow.size(3) - 1.0) / 2.0)

flow_for_grip[:,1,:,:] = flow[:,1,:,:] / ((flow.size(2) - 1.0) / 2.0)

torchHorizontal = torch.linspace(

-1.0, 1.0, image.size(3)).view(

1, 1, 1, image.size(3)).expand(

image.size(0), 1, image.size(2), image.size(3))

torchVertical = torch.linspace(

-1.0, 1.0, image.size(2)).view(

1, 1, image.size(2), 1).expand(

image.size(0), 1, image.size(2), image.size(3))

grid = torch.cat([torchHorizontal, torchVertical], 1).cuda()

grid = (grid + flow_for_grip).permute(0, 2, 3, 1)

return torch.nn.functional.grid_sample(image, grid)

開發者ID:XiaohangZhan,項目名稱:conditional-motion-propagation,代碼行數:19,

示例14: __init__

​點讚 6

# 需要導入模塊: import torch [as 別名]

# 或者: from torch import linspace [as 別名]

def __init__(self, N_filt,Filt_dim,fs, stride=1, padding=0, is_cuda=False):

super(SincLayer,self).__init__()

# Mel Initialization of the filterbanks

low_freq_mel = 80

high_freq_mel = (2595 * np.log10(1 + (fs / 2) / 700)) # Convert Hz to Mel

mel_points = np.linspace(low_freq_mel, high_freq_mel, N_filt) # Equally spaced in Mel scale

f_cos = (700 * (10**(mel_points / 2595) - 1)) # Convert Mel to Hz

b1=np.roll(f_cos,1)

b2=np.roll(f_cos,-1)

b1[0]=30

b2[-1]=(fs/2)-100

self.freq_scale=fs*1.0

self.filt_b1 = torch.nn.Parameter(torch.from_numpy(b1/self.freq_scale))

self.filt_band = torch.nn.Parameter(torch.from_numpy((b2-b1)/self.freq_scale))

self.N_filt=N_filt

self.Filt_dim=Filt_dim

self.fs=fs

self.stride=stride

self.padding=padding

self.is_cuda = is_cuda

開發者ID:lorenlugosch,項目名稱:end-to-end-SLU,代碼行數:25,

示例15: uniform_grid

​點讚 6

# 需要導入模塊: import torch [as 別名]

# 或者: from torch import linspace [as 別名]

def uniform_grid(shape):

'''Uniformly places control points aranged in grid accross normalized image coordinates.

Params

------

shape : tuple

HxW defining the number of control points in height and width dimension

Returns

-------

points: HxWx2 tensor

Control points over [0,1] normalized image range.

'''

H,W = shape[:2]

c = torch.zeros(H, W, 2)

c[..., 0] = torch.linspace(0, 1, W)

c[..., 1] = torch.linspace(0, 1, H).unsqueeze(-1)

return c

開發者ID:arnabgho,項目名稱:iSketchNFill,代碼行數:20,

示例16: forward

​點讚 6

# 需要導入模塊: import torch [as 別名]

# 或者: from torch import linspace [as 別名]

def forward(self, feat, coord_st, coord_ed):

_, ch, h, w = feat.size()

num_st, num_ed = coord_st.size(0), coord_ed.size(0)

assert coord_st.size(1) == 3 and coord_ed.size(1) == 3

assert (coord_st[:, 0] == coord_st[0, 0]).all() and (coord_ed[:, 0] == coord_st[0, 0]).all()

bs = coord_st[0, 0].item()

# construct bounding boxes from junction points

with torch.no_grad():

coord_st = coord_st[:, 1:] * self.scale

coord_ed = coord_ed[:, 1:] * self.scale

coord_st = coord_st.unsqueeze(1).expand(num_st, num_ed, 2)

coord_ed = coord_ed.unsqueeze(0).expand(num_st, num_ed, 2)

arr_st2ed = coord_ed - coord_st

sample_grid = torch.linspace(0, 1, steps=self.align_size).to(feat).view(1, 1, self.align_size).expand(num_st, num_ed, self.align_size)

sample_grid = torch.einsum("ijd,ijs->ijsd", (arr_st2ed, sample_grid)) + coord_st.view(num_st, num_ed, 1, 2).expand(num_st, num_ed, self.align_size, 2)

sample_grid = sample_grid.view(num_st, num_ed, self.align_size, 2)

sample_grid[..., 0] = sample_grid[..., 0] / (w - 1) * 2 - 1

sample_grid[..., 1] = sample_grid[..., 1] / (h - 1) * 2 - 1

output = F.grid_sample(feat[int(bs)].view(1, ch, h, w).expand(num_st, ch, h, w), sample_grid)

assert output.size() == (num_st, ch, num_ed, self.align_size)

output = output.permute(0, 2, 1, 3).contiguous()

return output

開發者ID:svip-lab,項目名稱:PPGNet,代碼行數:26,

示例17: construct_problem

​點讚 6

# 需要導入模塊: import torch [as 別名]

# 或者: from torch import linspace [as 別名]

def construct_problem(device, npts=10, ode='constant', reverse=False):

f = PROBLEMS[ode]().to(device)

t_points = torch.linspace(1, 8, npts).to(device).requires_grad_(True)

sol = f.y_exact(t_points)

def _flip(x, dim):

indices = [slice(None)] * x.dim()

indices[dim] = torch.arange(x.size(dim) - 1, -1, -1, dtype=torch.long, device=x.device)

return x[tuple(indices)]

if reverse:

t_points = _flip(t_points, 0).clone().detach()

sol = _flip(sol, 0).clone().detach()

return f, sol[0].detach(), t_points, sol

開發者ID:rtqichen,項目名稱:torchdiffeq,代碼行數:19,

示例18: problem

​點讚 6

# 需要導入模塊: import torch [as 別名]

# 或者: from torch import linspace [as 別名]

def problem(self):

class Odefunc(torch.nn.Module):

def __init__(self):

super(Odefunc, self).__init__()

self.A = torch.nn.Parameter(torch.tensor([[-0.1, 2.0], [-2.0, -0.1]]))

self.unused_module = torch.nn.Linear(2, 5)

def forward(self, t, y):

return torch.mm(y**3, self.A)

y0 = torch.tensor([[2., 0.]]).to(TEST_DEVICE).requires_grad_(True)

t_points = torch.linspace(0., 25., 10).to(TEST_DEVICE).requires_grad_(True)

func = Odefunc().to(TEST_DEVICE)

return func, y0, t_points

開發者ID:rtqichen,項目名稱:torchdiffeq,代碼行數:18,

示例19: __init__

​點讚 5

# 需要導入模塊: import torch [as 別名]

# 或者: from torch import linspace [as 別名]

def __init__(self, reg_max=16):

super(Integral, self).__init__()

self.reg_max = reg_max

self.register_buffer('project',

torch.linspace(0, self.reg_max, self.reg_max + 1))

開發者ID:open-mmlab,項目名稱:mmdetection,代碼行數:7,

示例20: gen_grid_from_reg

​點讚 5

# 需要導入模塊: import torch [as 別名]

# 或者: from torch import linspace [as 別名]

def gen_grid_from_reg(self, reg, previous_boxes):

"""Base on the previous bboxes and regression values, we compute the

regressed bboxes and generate the grids on the bboxes.

:param reg: the regression value to previous bboxes.

:param previous_boxes: previous bboxes.

:return: generate grids on the regressed bboxes.

"""

b, _, h, w = reg.shape

bxy = (previous_boxes[:, :2, ...] + previous_boxes[:, 2:, ...]) / 2.

bwh = (previous_boxes[:, 2:, ...] -

previous_boxes[:, :2, ...]).clamp(min=1e-6)

grid_topleft = bxy + bwh * reg[:, :2, ...] - 0.5 * bwh * torch.exp(

reg[:, 2:, ...])

grid_wh = bwh * torch.exp(reg[:, 2:, ...])

grid_left = grid_topleft[:, [0], ...]

grid_top = grid_topleft[:, [1], ...]

grid_width = grid_wh[:, [0], ...]

grid_height = grid_wh[:, [1], ...]

intervel = torch.linspace(0., 1., self.dcn_kernel).view(

1, self.dcn_kernel, 1, 1).type_as(reg)

grid_x = grid_left + grid_width * intervel

grid_x = grid_x.unsqueeze(1).repeat(1, self.dcn_kernel, 1, 1, 1)

grid_x = grid_x.view(b, -1, h, w)

grid_y = grid_top + grid_height * intervel

grid_y = grid_y.unsqueeze(2).repeat(1, 1, self.dcn_kernel, 1, 1)

grid_y = grid_y.view(b, -1, h, w)

grid_yx = torch.stack([grid_y, grid_x], dim=2)

grid_yx = grid_yx.view(b, -1, h, w)

regressed_bbox = torch.cat([

grid_left, grid_top, grid_left + grid_width, grid_top + grid_height

], 1)

return grid_yx, regressed_bbox

開發者ID:open-mmlab,項目名稱:mmdetection,代碼行數:35,

示例21: __init__

​點讚 5

# 需要導入模塊: import torch [as 別名]

# 或者: from torch import linspace [as 別名]

def __init__(self,

hop_length: Optional[int] = None,

n_freq: int = 201,

fixed_rate: Optional[float] = None) -> None:

super(TimeStretch, self).__init__()

self.fixed_rate = fixed_rate

n_fft = (n_freq - 1) * 2

hop_length = hop_length if hop_length is not None else n_fft // 2

self.register_buffer('phase_advance', torch.linspace(0, math.pi * hop_length, n_freq)[..., None])

開發者ID:pytorch,項目名稱:audio,代碼行數:13,

示例22: test_phase_vocoder

​點讚 5

# 需要導入模塊: import torch [as 別名]

# 或者: from torch import linspace [as 別名]

def test_phase_vocoder(complex_specgrams, rate, hop_length):

# Due to cummulative sum, numerical error in using torch.float32 will

# result in bottom right values of the stretched sectrogram to not

# match with librosa.

complex_specgrams = complex_specgrams.type(torch.float64)

phase_advance = torch.linspace(0, np.pi * hop_length, complex_specgrams.shape[-3], dtype=torch.float64)[..., None]

complex_specgrams_stretch = F.phase_vocoder(complex_specgrams, rate=rate, phase_advance=phase_advance)

# == Test shape

expected_size = list(complex_specgrams.size())

expected_size[-2] = int(np.ceil(expected_size[-2] / rate))

assert complex_specgrams.dim() == complex_specgrams_stretch.dim()

assert complex_specgrams_stretch.size() == torch.Size(expected_size)

# == Test values

index = [0] * (complex_specgrams.dim() - 3) + [slice(None)] * 3

mono_complex_specgram = complex_specgrams[index].numpy()

mono_complex_specgram = mono_complex_specgram[..., 0] + \

mono_complex_specgram[..., 1] * 1j

expected_complex_stretch = librosa.phase_vocoder(mono_complex_specgram,

rate=rate,

hop_length=hop_length)

complex_stretch = complex_specgrams_stretch[index].numpy()

complex_stretch = complex_stretch[..., 0] + 1j * complex_stretch[..., 1]

assert np.allclose(complex_stretch, expected_complex_stretch, atol=1e-5)

開發者ID:pytorch,項目名稱:audio,代碼行數:32,

示例23: get_sinusoid

​點讚 5

# 需要導入模塊: import torch [as 別名]

# 或者: from torch import linspace [as 別名]

def get_sinusoid(

*,

frequency: float = 300,

sample_rate: int = 16000,

duration: float = 1, # seconds

n_channels: int = 1,

dtype: Union[str, torch.dtype] = "float32",

device: Union[str, torch.device] = "cpu",

):

"""Generate pseudo audio data with sine wave.

Args:

frequency: Frequency of sine wave

sample_rate: Sampling rate

duration: Length of the resulting Tensor in seconds.

n_channels: Number of channels

dtype: Torch dtype

device: device

Returns:

Tensor: shape of (n_channels, sample_rate * duration)

"""

if isinstance(dtype, str):

dtype = getattr(torch, dtype)

pie2 = 2 * 3.141592653589793

end = pie2 * frequency * duration

theta = torch.linspace(0, end, sample_rate * duration, dtype=dtype, device=device)

return torch.sin(theta, out=None).repeat([n_channels, 1])

開發者ID:pytorch,項目名稱:audio,代碼行數:30,

示例24: new_levels

​點讚 5

# 需要導入模塊: import torch [as 別名]

# 或者: from torch import linspace [as 別名]

def new_levels(L, initial_levels):

lo, hi = initial_levels

levels = torch.linspace(lo, hi, L)

return torch.tensor(levels, requires_grad=False)

開發者ID:fab-jul,項目名稱:L3C-PyTorch,代碼行數:6,

示例25: __init__

​點讚 5

# 需要導入模塊: import torch [as 別名]

# 或者: from torch import linspace [as 別名]

def __init__(self, config_ms, scale):

super(EDSRLikeEnc, self).__init__()

self.scale = scale

self.config_ms = config_ms

Cf = config_ms.Cf

kernel_size = config_ms.kernel_size

C, self.L = config_ms.q.C, config_ms.q.L

n_resblock = config_ms.enc.num_blocks

# Downsampling

self.down = conv(Cf, Cf, kernel_size=5, stride=2)

# Body

m_body = [

edsr.ResBlock(conv, Cf, kernel_size, act=nn.ReLU(True))

for _ in range(n_resblock)

]

m_body.append(conv(Cf, Cf, kernel_size))

self.body = nn.Sequential(*m_body)

# to Quantizer

to_q = [conv(Cf, C, 1)]

if self.training:

to_q.append(

# start scale from 1, as 0 is RGB

vis.histogram_plot.HistogramPlot('train', 'histo/enc_{}_after_1x1'.format(scale+1), buffer_size=10,

num_inputs_to_buffer=1, per_channel=False))

self.to_q = nn.Sequential(*to_q)

# We assume q.L levels, evenly distributed between q.levels_range[0] and q.levels_range[1]

# In theory, the levels could be learned. But in this code, they are assumed to be fixed.

levels_first, levels_last = config_ms.q.levels_range

# Wrapping this in a nn.Parameter ensures it is copied to gpu when .to('cuda') is called

self.levels = nn.Parameter(torch.linspace(levels_first, levels_last, self.L), requires_grad=False)

self._extra_repr = 'Levels={}'.format(','.join(map('{:.1f}'.format, list(self.levels))))

self.q = Quantizer(self.levels, config_ms.q.sigma)

開發者ID:fab-jul,項目名稱:L3C-PyTorch,代碼行數:40,

示例26: __init__

​點讚 5

# 需要導入模塊: import torch [as 別名]

# 或者: from torch import linspace [as 別名]

def __init__(self, l, total_C, dmll: DiscretizedMixLogisticLoss):

"""

:param l: predicted distribution, i.e., NKpHW, see DiscretizedMixLogisticLoss

:param total_C:

:param dmll:

"""

self.l = l

self.dmll = dmll

# Lp = L+1

self.targets = torch.linspace(dmll.x_min - dmll.bin_width / 2,

dmll.x_max + dmll.bin_width / 2,

dmll.L + 1, dtype=torch.float32, device=l.device)

self.total_C = total_C

self.c_cur = 0

開發者ID:fab-jul,項目名稱:L3C-PyTorch,代碼行數:17,

示例27: get_timecode

​點讚 5

# 需要導入模塊: import torch [as 別名]

# 或者: from torch import linspace [as 別名]

def get_timecode(dim,t,tframe,size=None,maxlen=10000,collapse=False):

if size is None: size=tframe

n=t.float().view(-1,1,1)+torch.linspace(0,tframe-1,steps=size).view(1,1,-1).to(t.device)

f=(10**(torch.arange(1,dim+1).float()/dim)).view(1,-1,1).to(t.device)

tc=torch.sin(TWOPI*f*n/maxlen)

if collapse:

tc=tc.mean(1).unsqueeze(1)

return tc

開發者ID:joansj,項目名稱:blow,代碼行數:10,

注:本文中的torch.linspace方法示例整理自Github/MSDocs等源碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。

你可能感兴趣的:(python,linspace函数)