Search code examples
tensorflowkeraskeras-layertf.keras

keras how to feed an input variable with the output of my model


Im turning around since a years with this problem, I want to forcast t+1 using the forcast t+0 as one of my input. All I find is running my model one step at time and manualy insert my last forcast in the input for the next one step run... not efficient and impossible to train.

I use keras with tensorflow. Thank for any help!


Solution

  • I suggest u ChainRegressor/Classifier from sklearn. as u specify this model iterate fit in each step using the previous predictions as features for the new fit. here an example in a regression task

    import numpy as np
    import tensorflow as tf
    from tensorflow.keras.layers import *
    from tensorflow.keras.models import *
    from sklearn.multioutput import RegressorChain
    
    n_sample = 1000
    input_size = 20
    
    X = np.random.uniform(0,1, (n_sample,input_size))
    y = np.random.uniform(0,1, (n_sample,3)) <=== 3 step forecast
    
    def create_model():
        
        global input_size
        
        model = Sequential([
            Dense(32, activation='relu', input_shape=(input_size,)),
            Dense(1)
        ])
    
        model.compile(optimizer='Adam', loss='mse')
        input_size += 1 # <== important 
        # increase the input dimension and include the previous predictions in each iteration
        
        return model
    
    model = tf.keras.wrappers.scikit_learn.KerasRegressor(build_fn=create_model, epochs=1, 
                                                           batch_size=256, verbose = 1)
    chain = RegressorChain(model, order='random', random_state=42)
    chain.fit(X, y)
    
    chain.predict(X).shape