问题
I'm trying to build a convolutional network that will work on a 3D voxel grid. I try to add a fully connected layer but get an error:
ValueError: Error when checking target: expected dense_1 to have 2 dimensions, but got array with shape (68, 50, 50, 50, 1)
How can this be happening when I have a flatten layer first? Shouldn't my input to the dense layer at that point be, well, flat?
x, y = load_data(directory)
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.25, random_state=42)
model = Sequential()
model.add(Convolution3D(1, kernel_size=(3, 3, 3), activation='relu',
border_mode='same', name='conv1',
input_shape=(50, 50, 50, 1)))
model.add(MaxPooling3D(pool_size=(2, 2, 2)))
model.add(Flatten())
model.add(Dense(32))
model.compile(
loss='mean_squared_error',
optimizer='adam',
metrics=['accuracy']
)
model.fit(
x_train,
y_train,
epochs=10,
batch_size=32,
)
model.evaluate(x_test, y_test)
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
conv1 (Conv3D) (None, 50, 50, 50, 1) 28
_________________________________________________________________
max_pooling3d_1 (MaxPooling3 (None, 25, 25, 25, 1) 0
_________________________________________________________________
flatten_1 (Flatten) (None, 15625) 0
_________________________________________________________________
dense_1 (Dense) (None, 32) 500032
=================================================================
回答1:
train_test_split
method split arrays into train and test set. If input to the method are list of arrays, the methods returns train and test tuples.
train_set, test_set = train_test_split(x, y, test_size=0.25, random_state=42)
x_train, y_train = train_set
x_test, y_test = test_set
or since python support left side assignment to tuples,
(x_train, y_train), (x_test, y_test) = train_test_split(x, y, test_size=0.25, random_state=42)
来源:https://stackoverflow.com/questions/57928270/valueerror-error-when-checking-target-expected-dense-1-to-have-2-dimensions-b