def _J(self, theta):
"""
Implements the order dependent family of functions defined in equations
4 to 7 in the reference paper.
"""
if self.order == 0:
return np.pi - theta
elif self.order == 1:
return tf.sin(theta) + (np.pi - theta) * tf.cos(theta)
elif self.order == 2:
return 3. * tf.sin(theta) * tf.cos(theta) + \
(np.pi - theta) * (1. + 2. * tf.cos(theta) ** 2)
python类sin()的实例源码
def K(self, X, X2=None, presliced=False):
if not presliced:
X, X2 = self._slice(X, X2)
if X2 is None:
X2 = X
# Introduce dummy dimension so we can use broadcasting
f = tf.expand_dims(X, 1) # now N x 1 x D
f2 = tf.expand_dims(X2, 0) # now 1 x M x D
r = np.pi * (f - f2) / self.period
r = tf.reduce_sum(tf.square(tf.sin(r) / self.lengthscales), 2)
return self.variance * tf.exp(-0.5 * r)
def setUp(self):
super(CoreUnaryOpsTest, self).setUp()
self.ops = [
('abs', operator.abs, tf.abs, core.abs_function),
('neg', operator.neg, tf.neg, core.neg),
# TODO(shoyer): add unary + to core TensorFlow
('pos', None, None, None),
('sign', None, tf.sign, core.sign),
('reciprocal', None, tf.reciprocal, core.reciprocal),
('square', None, tf.square, core.square),
('round', None, tf.round, core.round_function),
('sqrt', None, tf.sqrt, core.sqrt),
('rsqrt', None, tf.rsqrt, core.rsqrt),
('log', None, tf.log, core.log),
('exp', None, tf.exp, core.exp),
('log', None, tf.log, core.log),
('ceil', None, tf.ceil, core.ceil),
('floor', None, tf.floor, core.floor),
('cos', None, tf.cos, core.cos),
('sin', None, tf.sin, core.sin),
('tan', None, tf.tan, core.tan),
('acos', None, tf.acos, core.acos),
('asin', None, tf.asin, core.asin),
('atan', None, tf.atan, core.atan),
('lgamma', None, tf.lgamma, core.lgamma),
('digamma', None, tf.digamma, core.digamma),
('erf', None, tf.erf, core.erf),
('erfc', None, tf.erfc, core.erfc),
('lgamma', None, tf.lgamma, core.lgamma),
]
total_size = np.prod([v.size for v in self.original_lt.axes.values()])
self.test_lt = core.LabeledTensor(
tf.cast(self.original_lt, tf.float32) / total_size,
self.original_lt.axes)
def func_to_approx(x):
return tf.sin(x)
def sin(x):
'''Computes sin of x element-wise.
'''
return tf.sin(x)
def get_unit_variable_c( name, scope, shape ):
theta = tf.get_variable(name, shape=shape, initializer = tf.random_uniform_initializer(-pi,pi) )
return tf.complex( tf.cos(theta), tf.sin(theta) )
def sin_and_cos(x, name="ignored"):
return tf.concat(len(x.get_shape()) - 1, [tf.sin(x), tf.cos(x)])
def _get_rot_mat_x_hom(angle):
""" Returns a 3D rotation matrix in homogeneous coords. """
one_vec = tf.ones_like(angle)
zero_vec = one_vec*0.0
trafo_matrix = _stitch_mat_from_vecs([one_vec, zero_vec, zero_vec, zero_vec,
zero_vec, tf.cos(angle), -tf.sin(angle), zero_vec,
zero_vec, tf.sin(angle), tf.cos(angle), zero_vec,
zero_vec, zero_vec, zero_vec, one_vec])
return trafo_matrix
def _get_rot_mat_y_hom(angle):
""" Returns a 3D rotation matrix in homogeneous coords. """
one_vec = tf.ones_like(angle)
zero_vec = one_vec*0.0
trafo_matrix = _stitch_mat_from_vecs([tf.cos(angle), zero_vec, tf.sin(angle), zero_vec,
zero_vec, one_vec, zero_vec, zero_vec,
-tf.sin(angle), zero_vec, tf.cos(angle), zero_vec,
zero_vec, zero_vec, zero_vec, one_vec])
return trafo_matrix
def _get_rot_mat_z_hom(angle):
""" Returns a 3D rotation matrix in homogeneous coords. """
one_vec = tf.ones_like(angle)
zero_vec = one_vec*0.0
trafo_matrix = _stitch_mat_from_vecs([tf.cos(angle), -tf.sin(angle), zero_vec, zero_vec,
tf.sin(angle), tf.cos(angle), zero_vec, zero_vec,
zero_vec, zero_vec, one_vec, zero_vec,
zero_vec, zero_vec, zero_vec, one_vec])
return trafo_matrix
def _get_rot_mat_y(angle):
""" Returns a 3D rotation matrix. """
one_vec = tf.ones_like(angle)
zero_vec = one_vec*0.0
trafo_matrix = _stitch_mat_from_vecs([tf.cos(angle), zero_vec, -tf.sin(angle),
zero_vec, one_vec, zero_vec,
tf.sin(angle), zero_vec, tf.cos(angle)])
return trafo_matrix
def _get_rot_mat_z(angle):
""" Returns a 3D rotation matrix. """
one_vec = tf.ones_like(angle)
zero_vec = one_vec*0.0
trafo_matrix = _stitch_mat_from_vecs([tf.cos(angle), tf.sin(angle), zero_vec,
-tf.sin(angle), tf.cos(angle), zero_vec,
zero_vec, zero_vec, one_vec])
return trafo_matrix
def buildRotations(n, rand_or_identity,num_rots=None):
print("num_rots: %d" %num_rots)
num_rots = num_rots or (n-1)
n_prime = int(n*(n-1)//2*num_rots/(n-1))
outputs = []
with vs.variable_scope("Build_Rotations"):
(indices, values_idxs) = rotationPreprocess(n, num_rots)
if rand_or_identity:
print("Initialization: Random")
thetas = vs.get_variable(initializer=tf.random_uniform([n_prime, 1], 0, 2*math.pi),
name="Thetas_RandInit", dtype=tf.float32)
else:
print("Initialization: Identity")
thetas = vs.get_variable(initializer=tf.zeros([n_prime, 1]),
name="Thetas_OnesInit", dtype=tf.float32)
cos = tf.cos(thetas)
sin = tf.sin(thetas)
nsin = tf.neg(sin)
thetas_concat = tf.concat(0, [cos,sin,nsin])
gathered_values = tf.squeeze(tf.gather(thetas_concat, values_idxs))
shape = tf.constant([n, n], dtype=tf.int64)
splt_values = tf.split(0, num_rots, gathered_values)
splt_indices = tf.split(0, num_rots, indices)
shape = tf.constant([n,n], dtype=tf.int64)
for i in range(num_rots):
curr_indices = splt_indices[i]
curr_values = splt_values[i]
sparse_rot = tf.SparseTensor(indices=curr_indices, values=curr_values, shape=shape)
outputs.append(sparse_rot)
print("buildRotations output length: %d" % len(outputs))
return outputs
def rotationTransform(X, n, scope, num_rots=None):
num_rots = num_rots or (n-1)
n_prime = int(n*(n-1)//2*num_rots/(n-1))
outputs = []
with vs.variable_scope(scope or "RotationTransform"):
for i, (name, x) in enumerate(X):
(indices, values_idxs) = rotationPreprocess(n, num_rots)
thetas = vs.get_variable(initializer=tf.random_uniform([n_prime, 1], 0, 2*math.pi),
name="Thetas"+str(i)+name, dtype=tf.float32)
cos = tf.cos(thetas)
sin = tf.sin(thetas)
nsin = tf.neg(sin)
thetas_concat = tf.concat(0, [cos,sin,nsin])
gathered_values = tf.squeeze(tf.gather(thetas_concat, values_idxs))
shape = tf.constant([n, n], dtype=tf.int64)
splt_values = tf.split(0, num_rots, gathered_values)
splt_indices = tf.split(0, num_rots, indices)
shape = tf.constant([n,n], dtype=tf.int64)
for i in range(num_rots):
curr_indices = splt_indices[i]
curr_values = splt_values[i]
sparse_rot = tf.SparseTensor(indices=curr_indices, values=curr_values, shape=shape)
x = tf.sparse_tensor_dense_matmul(sparse_rot, x)
outputs.append(x)
return outputs
def lat_long_to_xyz(S, T):
x = tf.cos(T) * tf.sin(S)
y = tf.sin(T)
z = tf.cos(T) * tf.cos(S)
return x, y, z
def backproject(S, T, depth):
# Convert to Cartesian for modified depth input.
# depth = sqrt(x^2 + z^2).
x = depth * tf.sin(S)
y = depth * tf.tan(T)
z = depth * tf.cos(S)
return x, y, z
def add_timing_signal(x, min_timescale=1.0, max_timescale=1.0e4, name=None):
"""
This function adds a bunch of sinusoids of different frequencies to a
Tensor. See paper: Attention is all you need
:param x: A tensor with shape [batch, length, channels]
:param min_timescale: A floating point number
:param max_timescale: A floating point number
:param name: An optional string
:returns: a Tensor the same shape as x.
"""
with tf.name_scope(name, default_name="add_timing_signal", values=[x]):
length = tf.shape(x)[1]
channels = tf.shape(x)[2]
position = tf.to_float(tf.range(length))
num_timescales = channels // 2
log_timescale_increment = (
math.log(float(max_timescale) / float(min_timescale)) /
(tf.to_float(num_timescales) - 1)
)
inv_timescales = min_timescale * tf.exp(
tf.to_float(tf.range(num_timescales)) * -log_timescale_increment
)
scaled_time = (tf.expand_dims(position, 1) *
tf.expand_dims(inv_timescales, 0))
signal = tf.concat([tf.sin(scaled_time), tf.cos(scaled_time)], axis=1)
signal = tf.pad(signal, [[0, 0], [0, tf.mod(channels, 2)]])
signal = tf.reshape(signal, [1, length, channels])
return x + signal
def sine_wave(frequency):
"""Emit a sine wave at the given frequency."""
xs = tf.reshape(tf.range(_samples(), dtype=tf.float32), [1, _samples(), 1])
ts = xs / FLAGS.sample_rate
return tf.sin(2 * math.pi * frequency * ts)
def bisine_wahwah_wave(frequency):
"""Emit two sine waves with balance oscillating left and right."""
#
# This is clearly intended to build on the bisine wave defined above,
# so we can start by generating that.
waves_a = bisine_wave(frequency)
#
# Then, by reversing axis 2, we swap the stereo channels. By mixing
# this with `waves_a`, we'll be able to create the desired effect.
waves_b = tf.reverse(waves_a, axis=[2])
#
# Let's have the balance oscillate from left to right four times.
iterations = 4
#
# Now, we compute the balance for each sample: `ts` has values
# in [0, 1] that indicate how much we should use `waves_a`.
xs = tf.reshape(tf.range(_samples(), dtype=tf.float32), [1, _samples(), 1])
thetas = xs / _samples() * iterations
ts = (tf.sin(math.pi * 2 * thetas) + 1) / 2
#
# Finally, we can mix the two together, and we're done.
wave = ts * waves_a + (1.0 - ts) * waves_b
#
# Alternately, we can make the effect more pronounced by exaggerating
# the sample data. Let's emit both variations.
exaggerated_wave = wave ** 3.0
return tf.concat([wave, exaggerated_wave], axis=0)
def sin(x):
"""Computes sin of x element-wise.
# Returns
A tensor.
"""
return tf.sin(x)