我们从Python开源项目中,提取了以下23个代码示例,用于说明如何使用torch.sin()。
def __init__(self, height, width, lr = 1, aux_loss = False): super(DenseAffine3DGridGen, self).__init__() self.height, self.width = height, width self.aux_loss = aux_loss self.lr = lr self.grid = np.zeros( [self.height, self.width, 3], dtype=np.float32) self.grid[:,:,0] = np.expand_dims(np.repeat(np.expand_dims(np.arange(-1, 1, 2.0/self.height), 0), repeats = self.width, axis = 0).T, 0) self.grid[:,:,1] = np.expand_dims(np.repeat(np.expand_dims(np.arange(-1, 1, 2.0/self.width), 0), repeats = self.height, axis = 0), 0) self.grid[:,:,2] = np.ones([self.height, width]) self.grid = torch.from_numpy(self.grid.astype(np.float32)) self.theta = self.grid[:,:,0] * np.pi/2 + np.pi/2 self.phi = self.grid[:,:,1] * np.pi self.x = torch.sin(self.theta) * torch.cos(self.phi) self.y = torch.sin(self.theta) * torch.sin(self.phi) self.z = torch.cos(self.theta) self.grid3d = torch.from_numpy(np.zeros( [self.height, self.width, 4], dtype=np.float32)) self.grid3d[:,:,0] = self.x self.grid3d[:,:,1] = self.y self.grid3d[:,:,2] = self.z self.grid3d[:,:,3] = self.grid[:,:,2]
def __init__(self, height, width, lr = 1, aux_loss = False): super(DenseAffine3DGridGen_rotate, self).__init__() self.height, self.width = height, width self.aux_loss = aux_loss self.lr = lr self.grid = np.zeros( [self.height, self.width, 3], dtype=np.float32) self.grid[:,:,0] = np.expand_dims(np.repeat(np.expand_dims(np.arange(-1, 1, 2.0/self.height), 0), repeats = self.width, axis = 0).T, 0) self.grid[:,:,1] = np.expand_dims(np.repeat(np.expand_dims(np.arange(-1, 1, 2.0/self.width), 0), repeats = self.height, axis = 0), 0) self.grid[:,:,2] = np.ones([self.height, width]) self.grid = torch.from_numpy(self.grid.astype(np.float32)) self.theta = self.grid[:,:,0] * np.pi/2 + np.pi/2 self.phi = self.grid[:,:,1] * np.pi self.x = torch.sin(self.theta) * torch.cos(self.phi) self.y = torch.sin(self.theta) * torch.sin(self.phi) self.z = torch.cos(self.theta) self.grid3d = torch.from_numpy(np.zeros( [self.height, self.width, 4], dtype=np.float32)) self.grid3d[:,:,0] = self.x self.grid3d[:,:,1] = self.y self.grid3d[:,:,2] = self.z self.grid3d[:,:,3] = self.grid[:,:,2]
def __init__(self, height, width, lr = 1, aux_loss = False): super(Depth3DGridGen, self).__init__() self.height, self.width = height, width self.aux_loss = aux_loss self.lr = lr self.grid = np.zeros( [self.height, self.width, 3], dtype=np.float32) self.grid[:,:,0] = np.expand_dims(np.repeat(np.expand_dims(np.arange(-1, 1, 2.0/self.height), 0), repeats = self.width, axis = 0).T, 0) self.grid[:,:,1] = np.expand_dims(np.repeat(np.expand_dims(np.arange(-1, 1, 2.0/self.width), 0), repeats = self.height, axis = 0), 0) self.grid[:,:,2] = np.ones([self.height, width]) self.grid = torch.from_numpy(self.grid.astype(np.float32)) self.theta = self.grid[:,:,0] * np.pi/2 + np.pi/2 self.phi = self.grid[:,:,1] * np.pi self.x = torch.sin(self.theta) * torch.cos(self.phi) self.y = torch.sin(self.theta) * torch.sin(self.phi) self.z = torch.cos(self.theta) self.grid3d = torch.from_numpy(np.zeros( [self.height, self.width, 4], dtype=np.float32)) self.grid3d[:,:,0] = self.x self.grid3d[:,:,1] = self.y self.grid3d[:,:,2] = self.z self.grid3d[:,:,3] = self.grid[:,:,2]
def __init__(self, height, width, lr = 1, aux_loss = False, ray_tracing = False): super(Depth3DGridGen_with_mask, self).__init__() self.height, self.width = height, width self.aux_loss = aux_loss self.lr = lr self.ray_tracing = ray_tracing self.grid = np.zeros( [self.height, self.width, 3], dtype=np.float32) self.grid[:,:,0] = np.expand_dims(np.repeat(np.expand_dims(np.arange(-1, 1, 2.0/self.height), 0), repeats = self.width, axis = 0).T, 0) self.grid[:,:,1] = np.expand_dims(np.repeat(np.expand_dims(np.arange(-1, 1, 2.0/self.width), 0), repeats = self.height, axis = 0), 0) self.grid[:,:,2] = np.ones([self.height, width]) self.grid = torch.from_numpy(self.grid.astype(np.float32)) self.theta = self.grid[:,:,0] * np.pi/2 + np.pi/2 self.phi = self.grid[:,:,1] * np.pi self.x = torch.sin(self.theta) * torch.cos(self.phi) self.y = torch.sin(self.theta) * torch.sin(self.phi) self.z = torch.cos(self.theta) self.grid3d = torch.from_numpy(np.zeros( [self.height, self.width, 4], dtype=np.float32)) self.grid3d[:,:,0] = self.x self.grid3d[:,:,1] = self.y self.grid3d[:,:,2] = self.z self.grid3d[:,:,3] = self.grid[:,:,2]
def make_data(cuda=False): train_x = Variable(torch.linspace(0, 1, 100)) train_y = Variable(torch.sin(train_x.data * (2 * math.pi))) test_x = Variable(torch.linspace(0, 1, 51)) test_y = Variable(torch.sin(test_x.data * (2 * math.pi))) if cuda: train_x = train_x.cuda() train_y = train_y.cuda() test_x = test_x.cuda() test_y = test_y.cuda() return train_x, train_y, test_x, test_y # All tests that pass with the exact kernel should pass with the interpolated kernel.
def mubs_trace_components(left_matmul_closure, right_matmul_closure, size, num_samples, tensor_cls=torch.Tensor, use_vars=False, dim_num=None): r1_coeff = tensor_cls(size) torch.arange(0, size, out=r1_coeff) r1_coeff.unsqueeze_(1) r2_coeff = ((r1_coeff + 1) * (r1_coeff + 2) / 2) if dim_num is not None: r1 = tensor_cls(num_samples * dim_num).uniform_().mul_(size).floor().type_as(r1_coeff).unsqueeze(1).t() r2 = tensor_cls(num_samples * dim_num).uniform_().mul_(size).floor().type_as(r1_coeff).unsqueeze(1).t() else: r1 = tensor_cls(num_samples).uniform_().mul_(size).floor().type_as(r1_coeff).unsqueeze(1).t() r2 = tensor_cls(num_samples).uniform_().mul_(size).floor().type_as(r1_coeff).unsqueeze(1).t() two_pi_n = (2 * math.pi) / size real_comps = torch.cos(two_pi_n * (r1_coeff.matmul(r1) + r2_coeff.matmul(r2))) / math.sqrt(size) imag_comps = torch.sin(two_pi_n * (r1_coeff.matmul(r1) + r2_coeff.matmul(r2))) / math.sqrt(size) coeff = math.sqrt(size / num_samples) comps = torch.cat([real_comps, imag_comps], 1).mul_(coeff) if use_vars: comps = Variable(comps) if dim_num is not None: comps = comps.t().contiguous().view(dim_num, 2 * num_samples, size).transpose(1, 2).contiguous() left_res = left_matmul_closure(comps) right_res = right_matmul_closure(comps) return left_res, right_res
def sin(x): y = get_op(lambda x: torch.sin(x))(x) return y
def sin(x: T.FloatTensor) -> T.FloatTensor: """ Elementwise sine of a tensor. Args: x: A tensor. Returns: tensor: Elementwise sine. """ return torch.sin(x)
def __init__(self, dropout, dim, max_len=5000): pe = torch.arange(0, max_len).unsqueeze(1).expand(max_len, dim) div_term = 1 / torch.pow(10000, torch.arange(0, dim * 2, 2) / dim) pe = pe * div_term.expand_as(pe) pe[:, 0::2] = torch.sin(pe[:, 0::2]) pe[:, 1::2] = torch.cos(pe[:, 1::2]) pe = pe.unsqueeze(1) super(PositionalEncoding, self).__init__() self.register_buffer('pe', pe) self.dropout = nn.Dropout(p=dropout)
def add_positional_features(tensor: torch.Tensor, min_timescale: float = 1.0, max_timescale: float = 1.0e4): # pylint: disable=line-too-long """ Implements the frequency-based positional encoding described in `Attention is all you Need <https://www.semanticscholar.org/paper/Attention-Is-All-You-Need-Vaswani-Shazeer/0737da0767d77606169cbf4187b83e1ab62f6077>`_ . Adds sinusoids of different frequencies to a ``Tensor``. A sinusoid of a different frequency and phase is added to each dimension of the input ``Tensor``. This allows the attention heads to use absolute and relative positions. The number of timescales is equal to hidden_dim / 2 within the range (min_timescale, max_timescale). For each timescale, the two sinusoidal signals sin(timestep / timescale) and cos(timestep / timescale) are generated and concatenated along the hidden_dim dimension. Parameters ---------- tensor : ``torch.Tensor`` a Tensor with shape (batch_size, timesteps, hidden_dim). min_timescale : ``float``, optional (default = 1.0) The smallest timescale to use. max_timescale : ``float``, optional (default = 1.0e4) The largest timescale to use. Returns ------- The input tensor augmented with the sinusoidal frequencies. """ _, timesteps, hidden_dim = tensor.size() timestep_range = get_range_vector(timesteps, tensor.is_cuda).data.float() # We're generating both cos and sin frequencies, # so half for each. num_timescales = hidden_dim // 2 timescale_range = get_range_vector(num_timescales, tensor.is_cuda).data.float() log_timescale_increments = math.log(float(max_timescale) / float(min_timescale)) / float(num_timescales - 1) inverse_timescales = min_timescale * torch.exp(timescale_range * -log_timescale_increments) # Broadcasted multiplication - shape (timesteps, num_timescales) scaled_time = timestep_range.unsqueeze(1) * inverse_timescales.unsqueeze(0) # shape (timesteps, 2 * num_timescales) sinusoids = Variable(torch.cat([torch.sin(scaled_time), torch.cos(scaled_time)], 1)) if hidden_dim % 2 != 0: # if the number of dimensions is odd, the cos and sin # timescales had size (hidden_dim - 1) / 2, so we need # to add a row of zeros to make up the difference. sinusoids = torch.cat([sinusoids, Variable(sinusoids.data.new(timesteps, 1).fill_(0))], 1) return tensor + sinusoids.unsqueeze(0)
def forward(self, depth, trans0, trans1, rotate): self.batchgrid3d = torch.zeros(torch.Size([depth.size(0)]) + self.grid3d.size()) for i in range(depth.size(0)): self.batchgrid3d[i] = self.grid3d self.batchgrid3d = Variable(self.batchgrid3d) self.batchgrid = torch.zeros(torch.Size([depth.size(0)]) + self.grid.size()) for i in range(depth.size(0)): self.batchgrid[i] = self.grid self.batchgrid = Variable(self.batchgrid) if depth.is_cuda: self.batchgrid = self.batchgrid.cuda() self.batchgrid3d = self.batchgrid3d.cuda() x_ = self.batchgrid3d[:,:,:,0:1] * depth + trans0.view(-1,1,1,1).repeat(1, self.height, self.width, 1) y_ = self.batchgrid3d[:,:,:,1:2] * depth + trans1.view(-1,1,1,1).repeat(1, self.height, self.width, 1) z = self.batchgrid3d[:,:,:,2:3] * depth #print(x.size(), y.size(), z.size()) rotate_z = rotate.view(-1,1,1,1).repeat(1,self.height, self.width,1) * np.pi x = x_ * torch.cos(rotate_z) - y_ * torch.sin(rotate_z) y = x_ * torch.sin(rotate_z) + y_ * torch.cos(rotate_z) r = torch.sqrt(x**2 + y**2 + z**2) + 1e-5 #print(r) theta = torch.acos(z/r)/(np.pi/2) - 1 #phi = torch.atan(y/x) if depth.is_cuda: phi = torch.atan(y/(x + 1e-5)) + np.pi * x.lt(0).type(torch.cuda.FloatTensor) * (y.ge(0).type(torch.cuda.FloatTensor) - y.lt(0).type(torch.cuda.FloatTensor)) else: phi = torch.atan(y/(x + 1e-5)) + np.pi * x.lt(0).type(torch.FloatTensor) * (y.ge(0).type(torch.FloatTensor) - y.lt(0).type(torch.FloatTensor)) phi = phi/np.pi output = torch.cat([theta,phi], 3) return output
def _EUNN(self, hx, thetaA, thetaB): L = self.capacity N = self.hidden_size sinA = torch.sin(self.thetaA) cosA = torch.cos(self.thetaA) sinB = torch.sin(self.thetaB) cosB = torch.cos(self.thetaB) I = Variable(torch.ones((L/2, 1))) O = Variable(torch.zeros((L/2, 1))) diagA = torch.stack((cosA, cosA), 2) offA = torch.stack((-sinA, sinA), 2) diagB = torch.stack((cosB, cosB), 2) offB = torch.stack((-sinB, sinB), 2) diagA = diagA.view(L/2, N) offA = offA.view(L/2, N) diagB = diagB.view(L/2, N-2) offB = offB.view(L/2, N-2) diagB = torch.cat((I, diagB, I), 1) offB = torch.cat((O, offB, O), 1) batch_size = hx.size()[0] x = hx for i in range(L/2): # # A y = x.view(batch_size, N/2, 2) y = torch.stack((y[:,:,1], y[:,:,0]), 2) y = y.view(batch_size, N) x = torch.mul(x, diagA[i].expand_as(x)) y = torch.mul(y, offA[i].expand_as(x)) x = x + y # B x_top = x[:,0] x_mid = x[:,1:-1].contiguous() x_bot = x[:,-1] y = x_mid.view(batch_size, N/2-1, 2) y = torch.stack((y[:, :, 1], y[:, :, 0]), 1) y = y.view(batch_size, N-2) x_top = torch.unsqueeze(x_top, 1) x_bot = torch.unsqueeze(x_bot, 1) # print x_top.size(), y.size(), x_bot.size() y = torch.cat((x_top, y, x_bot), 1) x = x * diagB[i].expand(batch_size, N) y = y * offB[i].expand(batch_size, N) x = x + y return x
def _EUNN(self, hx, thetaA, thetaB): L = self.capacity N = self.hidden_size sinA = torch.sin(self.thetaA) cosA = torch.cos(self.thetaA) sinB = torch.sin(self.thetaB) cosB = torch.cos(self.thetaB) I = Variable(torch.ones((L//2, 1))) O = Variable(torch.zeros((L//2, 1))) diagA = torch.stack((cosA, cosA), 2) offA = torch.stack((-sinA, sinA), 2) diagB = torch.stack((cosB, cosB), 2) offB = torch.stack((-sinB, sinB), 2) diagA = diagA.view(L//2, N) offA = offA.view(L//2, N) diagB = diagB.view(L//2, N-2) offB = offB.view(L//2, N-2) diagB = torch.cat((I, diagB, I), 1) offB = torch.cat((O, offB, O), 1) batch_size = hx.size()[0] x = hx for i in range(L//2): # # A y = x.view(batch_size, N//2, 2) y = torch.stack((y[:,:,1], y[:,:,0]), 2) y = y.view(batch_size, N) x = torch.mul(x, diagA[i].expand_as(x)) y = torch.mul(y, offA[i].expand_as(x)) x = x + y # B x_top = x[:,0] x_mid = x[:,1:-1].contiguous() x_bot = x[:,-1] y = x_mid.view(batch_size, N//2-1, 2) y = torch.stack((y[:, :, 1], y[:, :, 0]), 1) y = y.view(batch_size, N-2) x_top = torch.unsqueeze(x_top, 1) x_bot = torch.unsqueeze(x_bot, 1) # print x_top.size(), y.size(), x_bot.size() y = torch.cat((x_top, y, x_bot), 1) x = x * diagB[i].expand(batch_size, N) y = y * offB[i].expand(batch_size, N) x = x + y return x