【发布时间】:2020-11-05 04:40:06
【问题描述】:
我正在尝试使用 keras 从论文中实现一种算法,他们在其中训练神经网络以使用有限的数据点来逼近数学函数 f(x)。我希望神经网络的输入为 x,输出形式为 f(x) = 1 + xN(x),其中 N(x) 是来自最终密集层的值。
我知道如何使它对输出 f(x) = N(x) 起作用,但我只是不知道如何调整网络以获得 f(x) = 1 + xN(x)。有人可以帮我吗?
这是我当前的代码
from keras.layers import Input, Dense, Add, Multiply
from keras.models import Model
import keras.backend as K
import matplotlib.pyplot as plt
import numpy as np
import time
def f(x):
return x**2
Xtrain = np.linspace(0, 1, 10)
ytrain = np.array([f(x) for x in Xtrain])
X = np.linspace(0, 2, 100)
y = np.array([f(x) for x in X])
input = Input(shape=(1,))
init = np.ones(shape=(10, 1))
init = K.variable(init)
hidden = input
hidden = Dense(8, activation='relu')(hidden)
out = Dense(1, activation='linear')(hidden)
out = Add()([init, Multiply()([out, input])])
model = Model(inputs=input, outputs=out)
model.compile(loss='mean_squared_error', optimizer="adam")
tic = time.perf_counter()
model.fit(Xtrain, ytrain, epochs=1000, verbose=1)
toc = time.perf_counter()
print(f"Training time: {toc - tic:0.4f} seconds")
prediction = model.predict(X)
prediction = prediction.reshape((100,))
plt.figure(figsize=(10,5))
plt.plot(X, y, color='red', label='Analytical solution')
plt.plot(X, prediction, color='black', label = 'Prediction')
plt.scatter(Xtrain, ytrain, color='blue', label='Training points')
plt.legend()
plt.show()
plt.tight_layout()
在线崩溃
out = Add()([init, Multiply()([out, input])])
【问题讨论】:
标签: python tensorflow keras neural-network