检查目标时出错:预期density_3具有2维,但数组的形状为(10,10,2)

时间:2019-04-06 22:22:56

标签: python tensorflow machine-learning neural-network conv-neural-network

我有形状为(n,128,128,3),标签为(n,10,2)的128x128 RGB图像。 这是我的神经网络代码:

from tensorflow.python.keras.models import Sequential
from tensorflow.python.keras.layers import InputLayer
from tensorflow.python.keras.layers import  MaxPooling2D
from tensorflow.python.keras.layers import Conv2D, Dense, Flatten
from tensorflow.python.keras.optimizers import Adam

from data_gen import gen_dataset
data, labels = gen_dataset(10)
test_data, test_labels = gen_dataset(10)

model = Sequential()

print(data.shape) # (10, 128, 128, 3)
print(labels.shape) # (10, 10, 2)

model.add(InputLayer(input_shape=(128, 128, 3)))
model.add(Conv2D(kernel_size=5, strides=1, filters=32, padding='same', activation='relu', name='conv1'))
model.add(MaxPooling2D(pool_size=2, strides=2))
model.add(Conv2D(kernel_size=5, strides=1, filters=64, padding='same', activation='relu', name='conv2'))
model.add(MaxPooling2D(pool_size=2, strides=2))
model.add(Conv2D(kernel_size=5, strides=1, filters=64, padding='same', activation='relu', name='conv3'))
model.add(MaxPooling2D(pool_size=2, strides=2))
model.add(Flatten())
model.add(Dense(512, activation='relu'))
model.add(Dense(10, activation='relu'))
model.add(Dense(10, activation='relu'))
model.add(Dense(2, activation='softmax'))

optimizer = Adam(lr=1e-3)

model.compile(optimizer=optimizer, loss='categorical_crossentropy', metrics=['accuracy'])
model.fit(x=data, y=labels, epochs=5, batch_size=5)
result = model.evaluate(x=test_data, y=test_labels)
print('\n\nAccuracy:', result[1])

如果我运行它,则会收到错误ValueError: Error when checking target: expected dense_3 to have 2 dimensions, but got array with shape (10, 10, 2)

我知道存在与此类似的问题,但是这些问题尚未回答我的问题。 我尝试改变第一个密集层神经元的数量,尝试添加更多的最大池和转换层,但这些都没有解决。

1 个答案:

答案 0 :(得分:0)

该行中的错误:

model.add(Dense(2, activation='softmax')) 

应该是:

model.add(Dense(10, activation='softmax'))

原因

因为你有十节课。