用Keras预测向量序列

时间:2018-06-27 03:56:14

标签: python keras

给定995(1,4)个向量的序列,我想用Keras预测接下来的5(1,4)个向量。

我的数据数组的形状为(1000,1000,1,4),即1000个(1,4)向量的1000个表示形式。

我将此数据数组分为输入和输出,得到形状为(1000,995,1,4)的输入数组和形状为(1000,5,1,4)的输出数组。

我正在使用以下代码,但是出现了与输出形状有关的错误,并且我不清楚如何在模型中构造最后一层来处理输出数组的形状。

from keras.models import Sequential
from keras.layers import Dense 


X = np.array(test_data)[:,0:-5]
Y = np.array(test_data)[:,-5:]

print(np.shape(X))
print(np.shape(Y))

# create model
model = Sequential()
model.add(Dense(12, input_shape=X.shape[1:], activation='relu'))
model.add(Dense(8, activation='relu'))
model.add(Dense(4, activation='sigmoid'))


# Compile model
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])

# Fit the model and use 10% of the data for validation
model.fit(X, Y, epochs=50, batch_size=10, validation_split=0.1)

# evaluate the model on accuracy
scores = model.evaluate(X, Y)
print("\n%s: %.2f%%" % (model.metrics_names[1], scores[1]*100))

我收到的输出是一个错误,似乎最后一层期望与输入数据X而不是输出数据Y具有相同的形状,如下所示:

(1000, 995, 1, 4)
(1000, 5, 1, 4)

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-45-ce15e7f4b527> in <module>()
     24 
     25 # Fit the model and use 10% of the data for validation
---> 26 model.fit(X, Y, epochs=50, batch_size=10, validation_split=0.1)
     27 
     28 # evaluate the model on accuracy

...

~/Applications/miniconda3/envs/MLGA/lib/python3.6/site-packages/keras/engine/training.py in _standardize_input_data(data, names, shapes, check_batch_axis, exception_prefix)
    121                             ': expected ' + names[i] + ' to have shape ' +
    122                             str(shape) + ' but got array with shape ' +
--> 123                             str(data_shape))
    124     return data
    125 

ValueError: Error when checking target: expected dense_70 to have shape (995, 1, 4) but got array with shape (5, 1, 4)

1 个答案:

答案 0 :(得分:0)

编辑:

问题在于输出数组的形状应等于Y中的要素数量,即

model = Sequential()
model.add(Dense(12, input_shape=X.shape[1:], activation='relu'))
model.add(Dense(8, activation='relu'))
model.add(Dense(Y.shape[1], activation='sigmoid'))

X和Y可以按照以前的方式进行初始化。

希望这会有所帮助。