Keras 无法正确预测多输出

Keras doesn't predict multi output correctly

我有一个包含两个特征的数据集来预测这两个特征。这里和数据示例:

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

当我使用 Keras 时(在我的代码下方):

# 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))

然而,输出与输入不同,它应该包含两个参数并且大小相似。

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

我认为问题出在您的输入格式上。为什么不使用 4 作为输入维度?

我尝试使用不同的格式 (numpy)。效果还不错。

import numpy as np
raw = np.array([[41.392953, 41.392889, 41.392825,41.392761, 41.392697],
        [2.163917,2.163995,2.164072,2.164150,2.164229 ]])
# 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=4, activation='relu'))
model.add(Dense(4, activation='relu'))
model.add(Dense(1, activation='linear'))
model.compile(loss='mse', optimizer='adam')
model.fit(X, y, 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))

输出:

X=[[2.163917 2.163995 2.164072 2.16415 ]], Predicted=[[2.3935468]]

如果你想有两个输出,你必须在你的输出层明确指定它们。例如:

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 ]]