如何使用另一个函数代替一个函数-NN

时间:2019-05-25 23:27:10

标签: python keras neural-network

因此,存在一个通用逼近定理,它说一个神经网络可以近似任何连续函数,只要它具有至少一个隐藏层并在那里使用非线性激活即可。

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

假设我要近似 y = x + 1 ,并且我有 z_1 = 2x,z_2 = 3x + 3 z_3 = 4x + 1 < / em>,其中 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 的未来值( 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()

1 个答案:

答案 0 :(得分:1)

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

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