问题描述
给出x,y形式的数据,使y = A sin(B(x)+ C)+ D,使用Tensorflow识别A,B,C和D。
我已经编写了以下代码来这样做,但不幸的是它没有学到。注意这里的问题不是正确地预测正弦曲线,而是识别变量。如果可以将函数的形式更改为y = A * X_2 * sin(B(X_1)+ C)+ D,则加分。
x = np.linspace(0,100,1000)
A = np.random.normal(1)
B = np.random.normal(.5)
C = np.random.normal(1)
D = np.random.normal(1)
y = A*np.sin((B*x) + C) + D
x = tf.constant([x.astype('float32')])
y = tf.constant([y.astype('float32')])
class Addition(tf.Module):
def __init__(self,inputs,name=None):
super().__init__(name=name)
self.b_1 = tf.Variable(tf.random.normal([inputs]),name='b1')
self.b_2 = tf.Variable(tf.random.normal([inputs]),name='b2')
def __call__(self,x):
out = tf.math.multiply(x,self.b_1) + self.b_2
return out
class Sinusoid(tf.Module):
def __init__(self,name=None):
super().__init__(name=name)
def __call__(self,x):
sine = tf.math.sin(x)
return sine
class Sine_Model(tf.Module):
def __init__(self,name=None):
super().__init__(name=name)
self.add_1 = Addition(inputs=1)
self.sin_1 = Sinusoid(inputs=1)
self.add_2 = Addition(inputs=1)
def __call__(self,x):
x = self.add_1(x)
x = self.sin_1(x)
x = self.add_2(x)
return x
model = Sine_Model(name='sine')
loss_object = tf.keras.losses.MeanSquaredError()
optimizer = tf.keras.optimizers.Adam(learning_rate=.1)
train_loss = tf.keras.metrics.Mean(name='train_loss')
@tf.function
def train_step(x,y):
with tf.GradientTape() as tape:
predictions = model(x)
loss = loss_object(y,predictions)
gradients = tape.gradient(loss,model.trainable_variables)
optimizer.apply_gradients(zip(gradients,model.trainable_variables))
train_loss(loss)
EPOCHS = 200
for epoch in range(EPOCHS):
# Reset the metrics at the start of the next epoch
train_loss.reset_states()
train_step(x,y)
template = 'Epoch {},Loss: {}'
#print(template.format(epoch + 1,# train_loss.result()))
y_predicted = sine_model(x)
plt.scatter(x,y_predicted.numpy()[0])
plt.scatter(x,y,c='r')
我确实使用scipy here看到了这个问题的答案。但是我想看看是否有可能专门使用Tensorflow,因为我对模块化很感兴趣,并且希望能够解决上述问题(y = A * X_2 * sin(B(X_1) + C)+ D)。
谢谢!
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)