使用keras的NARX实现

时间:2018-10-31 16:06:28

标签: python tensorflow keras

我正在尝试在keras(后端Tensoflow)中实现一个简单的NARX网络。我通过子类tf.keras.Model来构建模型。可以将NARX网络训练为简单的前馈网络(串并联架构),因此我对该定义没有任何疑问。但是,为了进行预测,我需要闭环并将输出作为模型的输入返回。如何修改网络以使其能够进行预测和预测?

这是该代码的最低版本:

import tensorflow as tf
from tensorflow import keras

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
numPreviousSteps = 8
inputShape = (None, numPreviousSteps + 2)

class Narx(keras.Model):

    def __init__(self):
        super(Narx, self).__init__(name='narx')
        self.dense = keras.layers.Dense(10, input_shape=inputShape,
                                        activation=keras.activations.tanh)
        self.outputLayer = keras.layers.Dense(1, activation=keras.activations.linear)

    def call(self, inputs, training = False):
        if (training):
            x = self.dense(inputs)
            return self.outputLayer(x)
        else: # TODO: what should the network do when used for prediction
            x = self.dense(inputs)
            return self.outputLayer(x)


model = Narx()
model.compile(optimizer=keras.training.RMSPropOptimizer(0.001),
              loss=tf.losses.mean_squared_error,
              metric=tf.metrics.mean_absolute_error)

# input data generation
numTsSamples = 1000

# time series to learn from
y = np.random.random((numTsSamples + numPreviousSteps + 1,))
x = np.random.random((numTsSamples,)) # exogenous input

# creation of tapped delay
data = [np.roll(y, -i)[:numTsSamples] for i in range(numPreviousSteps, -1, -1)]
data = [x] + data

# training data
data = np.stack(data, axis=1)

# expected results
yNext = y[numPreviousSteps : -1]

# model training
model.fit(data, yNext)

0 个答案:

没有答案