Keras无法正确预测多输出

hgqdbh6s  于 2023-05-29  发布在  其他
关注(0)|答案(3)|浏览(178)

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

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

qfe3c7zg1#

如果你这样定义你的数据:

raw = np.array([[41.392953, 41.392889, 41.392825,41.392761, 41.392697],
        [2.163917,2.163995,2.164072,2.164150,2.164229 ]])
X = raw[:,:-1]
y = raw[:,-1]

将有4个特征、2个样本和1个标签的回归:

对于多个输出,只需像这样设置最终层:
model.add(Dense(n_classes, activation='linear'))
n_classes可以是任何你喜欢的数字。

xkftehaa

xkftehaa2#

如果你想有两个输出,你必须在你的输出层中显式地指定它们。例如:

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

ejk8hzay3#

我认为问题出在你的输入格式上。为什么不使用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]]

相关问题