Skip to main content
 首页 » 编程设计

python之如何使用另一个函数来逼近一个函数之NN

2024年11月24日9jyk

因此,存在通用逼近定理,该定理表明神经网络可以逼近任何连续函数,前提是它至少有一个隐藏层并在那里使用非线性激活。

所以我的疑问如下:“如何使用神经网络逼近一个函数,而我的输入是其他函数?”

假设我想近似 y = x + 1 并且我有 z_1 = 2x、z_2 = 3x + 3 和 z_3 = 4x + 1,其中 x 是时变的。我想让我的模型学习的是 z_1、z_2、z_3 和 y 之间的关系,正如我可能写的 *y = -6 * z_1 - 1 * z_2 + 4 z_3*(我希望我的网络了解这种关系)。

从 0 到 T 我有所有函数的值,可以做监督学习,但是从 (T + 1) +,我将只有 < em>z_1、z_2 和 z_3 等等,我将使用网络根据这些 z 函数来近似 y 的 future 值( z_1、z_2、z_3)。

我如何使用 Keras 在 python 上实现它?我使用了以下代码,但没有得到任何像样的结果。

import numpy as np 
import matplotlib.pyplot as plt 
import keras 
from keras.models import Sequential 
from keras.layers import Dense, Dropout 
from keras.optimizers import RMSprop 
 
n = 10000 
 
def z_1(x): 
    x_0 = [] 
    for i in x: 
        x_0.append(2*i) 
    return x_0 
 
def z_2(x): 
    x_0 = [] 
    for i in x: 
        x_0.append(3*i + 3) 
    return x_0 
 
def z_3(x): 
    x_0 = [] 
    for i in x: 
        x_0.append(4* i + 1) 
    return x_0 
 
def z_0(x): 
    x_0 = [] 
    for i in x: 
        x_0.append(i + 1) 
    return x_0 
 
model = Sequential() 
model.add(Dense(500, activation='relu', input_dim=3)) 
model.add(Dense(500, activation='relu')) 
model.add(Dense(1, activation='linear')) 
model.compile(loss='mean_squared_error', optimizer='adam', metrics=['accuracy']) 
 
np.random.seed(seed = 2000) 
input = np.random.random(n) * 10 
 
dataset = z_0(input) 
input_1 = z_1(input) 
input_2 = z_2(input) 
input_3 = z_3(input) 
 
x_train = np.array([input_1[0:int(0.8*n)], input_2[0:int(0.8*n)], input_3[0:int(0.8*n)]]) 
y_train = np.array([dataset[0:int(0.8*n)]]) 
x_train = x_train.reshape(int(0.8*n), 3) 
y_train = y_train.reshape(int(0.8*n),1) 
 
es = keras.callbacks.EarlyStopping(monitor='val_loss', 
                              min_delta=0, 
                              patience=0, 
                              verbose=0, mode='auto') 
 
model.fit(x_train, y_train, epochs=100, batch_size=128, callbacks = [es]) 
 
 
x_test = np.array([input_1[int(n-100):n], input_2[int(n-100):n], input_3[int(n-100):n]]) 
x_test = x_test.reshape(int(100), 3) 
 
classes = model.predict(x_test, batch_size=128) 
 
y_test = np.array([dataset[int(n-100):n]]).reshape(int(100),1) 
plt.plot(y_test,c='b', label = 'test data') 
plt.plot(classes,c='r', label = 'test result') 
plt.legend() 
plt.show() 

请您参考如下方法:

前馈神经网络无法做到这一点。您需要使用递归神经网络来执行此操作。在 Keras 中查找 LSTM 或 GRU 单元。

https://keras.io/layers/recurrent/