我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用tensorflow.sin()。
def rotate_points(orig_points, angle, w, h): """Return rotated points Args: orig_points: 'Tensor' with shape [N,2], each entry is point (x,y) angle: rotate radians Returns: 'Tensor' with shape [N,2], with rotated points """ # rotation rotate_mat = tf.stack([[tf.cos(angle) / w, tf.sin(angle) / h], [-tf.sin(angle) / w, tf.cos(angle) / h]]) # shift coord orig_points = tf.subtract(orig_points, 0.5) orig_points = tf.stack([orig_points[:, 0] * w, orig_points[:, 1] * h], axis=1) print(orig_points) rotated_points = tf.matmul(orig_points, rotate_mat) + 0.5 return rotated_points
def random_rotation(img: tf.Tensor, max_rotation: float=0.1, crop: bool=True) -> tf.Tensor: # from SeguinBe with tf.name_scope('RandomRotation'): rotation = tf.random_uniform([], -max_rotation, max_rotation) rotated_image = tf.contrib.image.rotate(img, rotation, interpolation='BILINEAR') if crop: rotation = tf.abs(rotation) original_shape = tf.shape(rotated_image)[:2] h, w = original_shape[0], original_shape[1] # see https://stackoverflow.com/questions/16702966/rotate-image-and-crop-out-black-borders for formulae old_l, old_s = tf.cond(h > w, lambda: [h, w], lambda: [w, h]) old_l, old_s = tf.cast(old_l, tf.float32), tf.cast(old_s, tf.float32) new_l = (old_l * tf.cos(rotation) - old_s * tf.sin(rotation)) / tf.cos(2*rotation) new_s = (old_s - tf.sin(rotation) * new_l) / tf.cos(rotation) new_h, new_w = tf.cond(h > w, lambda: [new_l, new_s], lambda: [new_s, new_l]) new_h, new_w = tf.cast(new_h, tf.int32), tf.cast(new_w, tf.int32) bb_begin = tf.cast(tf.ceil((h-new_h)/2), tf.int32), tf.cast(tf.ceil((w-new_w)/2), tf.int32) rotated_image_crop = rotated_image[bb_begin[0]:h - bb_begin[0], bb_begin[1]:w - bb_begin[1], :] # If crop removes the entire image, keep the original image rotated_image = tf.cond(tf.equal(tf.size(rotated_image_crop), 0), true_fn=lambda: img, false_fn=lambda: rotated_image_crop) return rotated_image
def rotate_crop(img, rotation, crop=True, interpolation='NEAREST'): with tf.name_scope('RotateCrop'): rotated_image = tf_rotate(img, rotation, interpolation) if crop: rotation = tf.abs(rotation) original_shape = tf.shape(rotated_image)[:2] h, w = original_shape[0], original_shape[1] # see https://stackoverflow.com/questions/16702966/rotate-image-and-crop-out-black-borders for formulae old_l, old_s = tf.cond(h > w, lambda: [h, w], lambda: [w, h]) old_l, old_s = tf.cast(old_l, tf.float32), tf.cast(old_s, tf.float32) new_l = (old_l * tf.cos(rotation) - old_s * tf.sin(rotation)) / tf.cos(2 * rotation) new_s = (old_s - tf.sin(rotation) * new_l) / tf.cos(rotation) new_h, new_w = tf.cond(h > w, lambda: [new_l, new_s], lambda: [new_s, new_l]) new_h, new_w = tf.cast(new_h, tf.int32), tf.cast(new_w, tf.int32) bb_begin = tf.cast(tf.ceil((h - new_h) / 2), tf.int32), tf.cast(tf.ceil((w - new_w) / 2), tf.int32) rotated_image_crop = rotated_image[bb_begin[0]:h - bb_begin[0], bb_begin[1]:w - bb_begin[1], :] # If crop removes the entire image, keep the original image rotated_image = tf.cond(tf.equal(tf.size(rotated_image_crop), 0), true_fn=lambda: img, false_fn=lambda: rotated_image_crop) return rotated_image
def cyclic_decay(learning_rate, min_learning_rate=1e-4, cycle_length=1000, decay_steps=20000, decay_rate=0.5): """Cyclic learning rate.""" step = tf.to_float(tf.train.get_or_create_global_step()) decay = decay_rate ** (step // decay_steps) min_learning_rate = min_learning_rate * decay max_learning_rate = learning_rate * decay cycle = tf.sin(step * 2 * 3.141592 / cycle_length) learning_rate = ((max_learning_rate - min_learning_rate) * (cycle + 1) * 0.5 + min_learning_rate) return learning_rate
def test_node(Simulator): minibatch_size = 3 with nengo.Network() as net: node0 = TensorNode(lambda t: tf.tile(tf.reshape(t, (1, -1)), (minibatch_size, 1))) node1 = TensorNode(lambda t, x: tf.sin(x), size_in=1) nengo.Connection(node0, node1, synapse=None) p0 = nengo.Probe(node0) p1 = nengo.Probe(node1) with Simulator(net, minibatch_size=minibatch_size) as sim: sim.run_steps(10) assert np.allclose(sim.data[p0], sim.trange()[None, :, None]) assert np.allclose(sim.data[p1], np.sin(sim.trange()[None, :, None]))
def init_tf_ops_weight(self): #tf weights of operators self.H0_weight = tf.Variable(tf.ones([self.sys_para.steps]), trainable=False) #Just a vector of ones needed for the kernel self.weights_unpacked=[self.H0_weight] #will collect all weights here self.ops_weight_base = tf.Variable(tf.constant(self.sys_para.ops_weight_base, dtype = tf.float32), dtype=tf.float32,name ="weights_base") self.ops_weight = tf.sin(self.ops_weight_base,name="weights") for ii in range (self.sys_para.ops_len): self.weights_unpacked.append(self.sys_para.ops_max_amp[ii]*self.ops_weight[ii,:]) #print len(self.sys_para.ops_max_amp) self.H_weights = tf.stack(self.weights_unpacked,name="packed_weights") print "Operators weight initialized."
def _get_rot_mat(self, ux_b, uy_b, uz_b): """ Returns a rotation matrix from axis and (encoded) angle.""" with tf.name_scope('get_rot_mat'): u_norm = tf.sqrt(tf.square(ux_b) + tf.square(uy_b) + tf.square(uz_b) + 1e-8) theta = u_norm # some tmp vars st_b = tf.sin(theta) ct_b = tf.cos(theta) one_ct_b = 1.0 - tf.cos(theta) st = st_b[:, 0] ct = ct_b[:, 0] one_ct = one_ct_b[:, 0] norm_fac = 1.0 / u_norm[:, 0] ux = ux_b[:, 0] * norm_fac uy = uy_b[:, 0] * norm_fac uz = uz_b[:, 0] * norm_fac trafo_matrix = self._stitch_mat_from_vecs([ct+ux*ux*one_ct, ux*uy*one_ct-uz*st, ux*uz*one_ct+uy*st, uy*ux*one_ct+uz*st, ct+uy*uy*one_ct, uy*uz*one_ct-ux*st, uz*ux*one_ct-uy*st, uz*uy*one_ct+ux*st, ct+uz*uz*one_ct]) return trafo_matrix
def DizzyLayerV2(X, rot_list, n): n_prime = int(n*(n-1)/2) thetas = tf.Variable(tf.random_uniform([n_prime, 1], 0, 2*math.pi), name="thetas") results = [X] k = 0 for sublist in rot_list: indices = [] values = [] for (a, b) in sublist: c = tf.cos(thetas[k]) s = tf.sin(thetas[k]) indices = indices + [[a, a], [a, b], [b, a], [b, b]] values = values + [c, s, -s, c] k += 1 shape = [n, n] v = tf.pack(tf.squeeze(values)) R = tf.SparseTensor(indices, v, shape) results.append(tf.sparse_tensor_dense_matmul(R, results[-1])) return results[-1]
def DizzyLayerV1(X, indices): n = int(X.get_shape()[0]) n_prime = int(n*(n-1)/2) thetas = tf.Variable(tf.random_uniform([n_prime, 1], 0, 2*math.pi), name="thetas") X_split = [X[k, :] for k in range(n)] for k in range(n_prime): (a, b) = indices[k] theta = thetas[k] c = tf.cos(theta) s = tf.sin(theta) v_1 = c*X_split[a]+s*X_split[b] v_2 = -s*X_split[a]+c*X_split[b] X_split[a] = v_1 X_split[b] = v_2 out = tf.pack(X_split) return out
def interpolate(self, x1, x2, n): ''' Interpolation from the latent space ''' x1 = tf.expand_dims(x1, 0) x2 = tf.expand_dims(x2, 0) z1, _ = self._encode(x1, is_training=False) z2, _ = self._encode(x2, is_training=False) def L2norm(x): return tf.sqrt(tf.reduce_sum(tf.square(x), -1)) norm1 = L2norm(z1) norm2 = L2norm(z2) theta = tf.matmul(z1/norm1, z2/norm2, transpose_b=True) a = tf.reshape(tf.linspace(0., 1., n), [n, 1]) # 10x1 a1 = tf.sin((1. - a) * theta) / tf.sin(theta) a2 = tf.sin(a * theta) / tf.sin(theta) z = a1 * z1 + a2 * z2 xh = self._generate(z, is_training=False) xh = tf.concat(0, [x1, xh, x2]) return xh
def gabor(ksize=32): """Use Tensorflow to compute a 2D Gabor Kernel. Parameters ---------- ksize : int, optional Size of kernel. Returns ------- gabor : np.ndarray Gabor kernel with ksize x ksize dimensions. """ g = tf.Graph() with tf.Session(graph=g): z_2d = gauss2d(0.0, 1.0, ksize) ones = tf.ones((1, ksize)) ys = tf.sin(tf.linspace(-3.0, 3.0, ksize)) ys = tf.reshape(ys, [ksize, 1]) wave = tf.matmul(ys, ones) gabor = tf.mul(wave, z_2d) return gabor.eval()
def get_timing_signal(length, min_timescale=1, max_timescale=1e4, num_timescales=16): """Create Tensor of sinusoids of different frequencies. Args: length: Length of the Tensor to create, i.e. Number of steps. min_timescale: a float max_timescale: a float num_timescales: an int Returns: Tensor of shape (length, 2*num_timescales) """ positions = tf.to_float(tf.range(length)) log_timescale_increment = ( math.log(max_timescale / min_timescale) / (num_timescales - 1)) inv_timescales = min_timescale * tf.exp( tf.to_float(tf.range(num_timescales)) * -log_timescale_increment) scaled_time = tf.expand_dims(positions, 1) * tf.expand_dims(inv_timescales, 0) return tf.concat([tf.sin(scaled_time), tf.cos(scaled_time)], axis=1)
def sin(x): '''Computes sin of x element-wise. ''' return tf.sin(x)
def sin_and_cos(x, name="ignored"): return tf.concat(axis=len(x.get_shape()) - 1, values=[tf.sin(x), tf.cos(x)])
def gaussian(config, gan, net): z_dim = int(config.z) net = (net + 1) / 2 za = tf.slice(net, [0,0], [gan.batch_size(), z_dim//2]) zb = tf.slice(net, [0,z_dim//2], [gan.batch_size(), z_dim//2]) pi = np.pi ra = tf.sqrt(-2 * tf.log(za+TINY))*tf.cos(2*pi*zb) rb = tf.sqrt(-2 * tf.log(za+TINY))*tf.sin(2*pi*zb) return tf.reshape(tf.concat(axis=1, values=[ra, rb]), net.get_shape())
def periodic_triangle_waveform(z, p): return 2.0 / np.pi * tf.asin(tf.sin(2*np.pi*z/p))
def __init__(self, args): with tf.device(args.device): def circle(x): spherenet = tf.square(x) spherenet = tf.reduce_sum(spherenet, 1) lam = tf.sqrt(spherenet) return x/tf.reshape(lam,[int(lam.get_shape()[0]), 1]) def modes(x): return tf.round(x*2)/2.0 if args.distribution == 'circle': x = tf.random_normal([args.batch_size, 2]) x = circle(x) elif args.distribution == 'modes': x = tf.random_uniform([args.batch_size, 2], -1, 1) x = modes(x) elif args.distribution == 'sin': x = tf.random_uniform((1, args.batch_size), -10.5, 10.5 ) x = tf.transpose(x) r_data = tf.random_normal((args.batch_size,1), mean=0, stddev=0.1) xy = tf.sin(0.75*x)*7.0+x*0.5+r_data*1.0 x = tf.concat([xy,x], 1)/16.0 elif args.distribution == 'arch': offset1 = tf.random_uniform((1, args.batch_size), -10, 10 ) xa = tf.random_uniform((1, 1), 1, 4 ) xb = tf.random_uniform((1, 1), 1, 4 ) x1 = tf.random_uniform((1, args.batch_size), -1, 1 ) xcos = tf.cos(x1*np.pi + offset1)*xa xsin = tf.sin(x1*np.pi + offset1)*xb x = tf.transpose(tf.concat([xcos,xsin], 0))/16.0 self.x = x self.xy = tf.zeros_like(self.x)
def wormhole(tensor, shape, kink, input_stride, alpha=1.0): """ Apply per-pixel field flow. Non-iterative. :param Tensor tensor: :param list[int] shape: :param float kink: Path twistiness :param float input_stride: Maximum pixel offset :return: Tensor """ height, width, channels = shape values = value_map(tensor, shape) degrees = values * 360.0 * math.radians(1) * kink # stride = values * height * input_stride stride = height * input_stride x_index = tf.cast(row_index(shape), tf.float32) y_index = tf.cast(column_index(shape), tf.float32) x_offset = (tf.cos(degrees) + 1) * stride y_offset = (tf.sin(degrees) + 1) * stride x = tf.cast(x_index + x_offset, tf.int32) % width y = tf.cast(y_index + y_offset, tf.int32) % height luminosity = tf.square(tf.reshape(values, [height, width, 1])) out = normalize(tf.scatter_nd(offset_index(y, height, x, width), tensor * luminosity, tf.shape(tensor))) return blend(tensor, tf.sqrt(out), alpha)
def sin_and_cos(x, name="ignored"): return tf.concat(len(x.get_shape()) - 1, [tf.sin(x), tf.cos(x)])
def _transformation(self, XP): """Build the kernel feature space transformation.""" real = tf.cos(XP) imag = tf.sin(XP) Net = tf.concat([real, imag], axis=-1) / np.sqrt(self.n_features) return Net
def func_to_approx(x): return tf.sin(x)
def __init__(self, name, num_units): init_w = tf.random_uniform([num_units], minval=-np.pi, maxval=np.pi) self.w = tf.Variable(init_w, name=name) self.vec = tf.complex(tf.cos(self.w), tf.sin(self.w)) # [batch_sz, num_units]
def sin(self, x): '''Computes sin of x element-wise. ''' return tf.sin(x)
def sin(x): """Computes sin of x element-wise. # Returns A tensor. """ return tf.sin(x)
def testCplxSinGPU(self): shapes = [(5,4,3), (5,4), (5,), (1,)] for sh in shapes: x = ((np.random.randn(*sh) + 1j*np.random.randn(*sh)).astype(np.complex64)) self._compareGpu(x, np.sin, tf.sin)
def testCplxSinGradGPU(self): shapes = [(5,4,3), (5,4), (5,), (1,)] for sh in shapes: x = ((np.random.randn(*sh) + 1j*np.random.randn(*sh)).astype(np.complex64)) self._compareGpuGrad(x, np.sin, tf.sin)
def call(self, inputs): k1 = tf.matmul(tf.cos(inputs), self.k1 * tf.cos(self.mu)) k2 = tf.matmul(tf.sin(inputs), self.k2 * tf.sin(self.mu)) # Defines the two model formulations: "glm" vs "gvm". if self.model_type == 'glm': return tf.exp(k1 + k2 + self.k0) else: return tf.nn.softplus(self.b) + self.g * tf.exp(k1 + k2)
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)
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 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 _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)