使用Keras的Tensorflow:ValueError - 期望dense_84具有2个维度,但是具有形状的数组(100,9,1)

时间:2017-08-28 20:27:48

标签: tensorflow keras shape valueerror

我正在尝试使用Tensorflow通过Keras构建一个使用时间序列数据来预测下一个值的网络,但是我收到了这个错误:

ValueError: Error when checking target: expected dense_84 to have 2 dimensions, but got array with shape (100, 9, 1)

造成这种情况的原因是什么?我试过像其他帖子所建议的那样重新整理数据,但到目前为止无济于事。这是代码:

import keras
import numpy as np
import os
from keras import losses
from keras.models import Sequential
from keras.layers import Dense, Activation, Flatten, Dropout
from keras.layers.convolutional import Conv1D, Conv2D

# add the desktop to our path so we can access the data
os.path.join("C:\\Users\\user\\Desktop")
# import data
data = np.genfromtxt("C:\\Users\\user\\Desktop\\aapl_blocks_10.csv",
                     delimiter=',')
# separate into inputs and outputs
X = data[:, :9]
X = np.expand_dims(X, axis=2) # reshape (409, 9) to (409, 9, 1) for network
Y = data[:, 9]

# separate into test and train data
X_train = X[:100]
X_test = X[100:]
Y_train = Y[:100]
Y_test = Y[100:]

# set parameters
batch_size = 20;

# define model
model = Sequential()
model.add(Conv1D(filters=20,
                 kernel_size=5,
                 input_shape=(9, 1),
                 padding='causal'))
model.add(Flatten())
model.add(Dropout(rate=0.3))
model.add(Dense(units=10))
model.add(Activation('relu'))
model.add(Dense(units=1))
model.compile(loss=losses.mean_squared_error,
              optimizer='sgd',
              metrics=['accuracy'])

# train model
model.fit(X_train, Y_train, epochs=10, batch_size=batch_size)

# evaluate model
model.evaluate(X_test, Y_test, batch_size=batch_size)

以下是模型摘要:

Layer (type)                 Output Shape              Param #
=================================================================
conv1d_43 (Conv1D)           (None, 9, 20)             120
_________________________________________________________________
flatten_31 (Flatten)         (None, 180)               0
_________________________________________________________________
dropout_14 (Dropout)         (None, 180)               0
_________________________________________________________________
dense_83 (Dense)             (None, 10)                1810
_________________________________________________________________
activation_29 (Activation)   (None, 10)                0
_________________________________________________________________
dense_84 (Dense)             (None, 1)                 11
=================================================================
Total params: 1,941
Trainable params: 1,941
Non-trainable params: 0

如果有正确的格式化数据的方法,或者可能是堆叠这些图层的正确方法,我很想知道。

1 个答案:

答案 0 :(得分:0)

我怀疑你需要从输出中挤出通道尺寸,即实验室是形状(batch_size,9)并且你将它与具有1个通道的密集层的输出进行比较(batch_size, 9,1)。解决方案:在计算损失之前挤压/压扁。

...
model.add(Activation('relu'))
model.add(Dense(units=1))
model.add(Flatten())
model.compile(loss=losses.mean_squared_error,
              optimizer='sgd',
              metrics=['accuracy'])

关于squeeze vs Flatten的说明:在这种情况下,挤压(移除尺寸1的轴)和展平(形成某种形状的结果)(batch_size,n,m,.. 。)成形(batch_size,n m ...)将是相同的。在这种情况下,挤压可能稍微合适一些,因为如果你不小心挤压没有尺寸1的轴你就会得到一个错误(一件好事),而不是让你的程序以意想不到的行为运行。虽然我不会使用keras而且找不到一个' Squeeze'层 - 只是一个squeeze功能 - 我并不完全确定如何整合它。