Search code examples
pythonkerasregressionlstmprediction

Keras doesn't predict multi output correctly


I have a dataset with two features to predict those two features. Here and example of data:

raw = {'one':  ['41.392953', '41.392889', '41.392825','41.392761', '41.392697'],
        'two': ['2.163917','2.163995','2.164072','2.164150','2.164229' ]}
   

When I'm using Keras (below my code):

# example of making predictions for a regression problem
from keras.models import Sequential
from keras.layers import Dense
X = raw[:-1]
y = raw[1:]
# define and fit the final model
model = Sequential()
model.add(Dense(4, input_dim=2, activation='relu'))
model.add(Dense(4, activation='relu'))
model.add(Dense(1, activation='linear'))
model.compile(loss='mse', optimizer='adam')
model.fit(X[0:len(X)-1], y[0:len(y)-1], epochs=1000, verbose=0)
# make a prediction
Xnew=X[len(X)-1:len(X)]
ynew = model.predict(Xnew)
# show the inputs and predicted outputs
print("X=%s, Predicted=%s" % (Xnew, ynew))

However, the output is different from the input, it should contain two parameters and with similar size.

X=        latitude  longitude
55740  41.392052   2.164564, Predicted=[[21.778254]]

Solution

  • If you want to have two outputs, you have to explicitly specify them in your output layer. For example:

    from keras.models import Sequential
    from keras.layers import Dense
    
    X = tf.random.normal((341, 2))
    Y = tf.random.normal((341, 2))
    # define and fit the final model
    model = Sequential()
    model.add(Dense(4, input_dim=2, activation='relu'))
    model.add(Dense(4, activation='relu'))
    model.add(Dense(2, activation='linear'))
    model.compile(loss='mse', optimizer='adam')
    model.fit(X, Y, epochs=1, verbose=0)
    # make a prediction
    Xnew=tf.random.normal((1, 2))
    ynew = model.predict(Xnew)
    # show the inputs and predicted outputs
    print("X=%s, Predicted=%s" % (Xnew, ynew))
    # X=tf.Tensor([[-0.8087067  0.5405918]], shape=(1, 2), dtype=float32), Predicted=[[-0.02120915 -0.0466493 ]]