我正在尝试制作一个傅立叶级数函数,它将Tensor作为机器学习主题的y值。我得到了浮点数的代码,但还没有完成TensorflowTensor的代码。你可以重写这段代码,这样就可以使用y值了:
BATCH_SIZE = 16
MAX_LENGTH = 50
D_MODEL = 32
input_tensor_1 = tf.random.normal((BATCH_SIZE, MAX_LENGTH, D_MODEL))
input_tensor_2 = tf.random.normal((BATCH_SIZE, MAX_LENGTH, D_MODEL))
y = [input_tensor_1, input_tensor_2]
x = tf.range(len(y), dtype=tf.float32)
适用于浮点数的傅立叶级数,将被重写为Tensor:
import tensorflow as tf
import numpy as np
def construct_periodic_function(x, y, num_coefficients):
sorted_indices = tf.argsort(x)
x_sorted = tf.gather(x, sorted_indices)
y_sorted = tf.gather(y, sorted_indices)
n = tf.shape(x_sorted)[0]
T = x_sorted[-1] - x_sorted[0] # Total period
omega = 2 * np.pi / T # Angular frequency
a0 = tf.reduce_mean(y_sorted)
an = []
bn = []
for i in range(1, num_coefficients + 1):
an_i = 2 * tf.reduce_mean(y_sorted * tf.cos(i * omega * x_sorted)) # Cosine coefficients
bn_i = 2 * tf.reduce_mean(y_sorted * tf.sin(i * omega * x_sorted)) # Sine coefficients
an.append(an_i)
bn.append(bn_i)
an = tf.stack(an)
bn = tf.stack(bn)
def f(x_new):
y_new = tf.zeros_like(x_new, dtype=tf.float32)
y_new += a0
for i in range(1, num_coefficients + 1):
y_new += an[i-1] * tf.cos(i * omega * x_new)
y_new += bn[i-1] * tf.sin(i * omega * x_new)
return y_new
return f
x = tf.linspace(0.0, 2 * np.pi, 50)
y = tf.sin(x)
num_coefficients = 10
f = construct_periodic_function(x, y, num_coefficients)
x_range = tf.linspace(0.0, 2 * np.pi, 1000)
y_range = f(x_range)
1条答案
按热度按时间cxfofazt1#
我做了一个低效的变通方案,那就是一个接一个地遍历Tensor的每个元素,对所有Tensor进行傅里叶级数。这是令人难以置信的低效,甚至可能无法产生预期的结果;我不能保证它完全执行,但下面是代码:
傅里叶级数函数的其余部分保持不变。