Kau*_*l28 2 python machine-learning conv-neural-network keras
我正在关注这个 github存储库以实现简单的对象检测.在该存储库中,没有使用卷积层,但我想在Dense层之前添加两个卷积层.所以我改变了model
以下代码:
def baseline_model():
# create model
model = Sequential()
model.add(Conv2D(32, (2,2), input_shape=(1, 16, 16), activation='relu'))
model.add(MaxPooling2D(pool_size=(2,2)))
model.add(Conv2D(32, (2,2), activation='relu'))
model.add(MaxPooling2D(pool_size=(2,2)))
model.add(Dropout(0.2))
model.add(Flatten())
model.add(Dense(128, activation='relu'))
model.add(Dense(2, activation='softmax'))
# Compile model
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
return model
Run Code Online (Sandbox Code Playgroud)
同时,我已经从改变图像的尺寸8*8
来16*16
.
所以这里我的输入数据集的维度将是(40000*16*16),其中40000是图像的数量.
现在我无法决定是否使用conv1D
或conv2D
.我读过这个 keras官方文档,但对conv的维度之间的关系无法理解.图层和输入数据形状.
如果我使用上面的模型配置,那么我会收到以下错误:
Error when checking input: expected conv2d_21_input to have 4 dimensions, but got array with shape (40000, 16, 16)
Run Code Online (Sandbox Code Playgroud)
那么我在这里缺少什么?而一般如何决定是否使用conv1D
或conv2D
?谢谢你的帮助,我在这个领域完成了新手.
你必须正确塑造你的图像.所有卷积层都需要额外的维度channels
.
RGB图像有3个通道.但是如果你没有频道,那么你实际上有1个频道.您必须将其显示在数据中才能生效:
#if using channels_last - the default configuration in keras
x_train = x_train.reshape(40000,16,16,1)
#if using channels_first
x_train = x_train.reshape(40000,1, 16,16)
Run Code Online (Sandbox Code Playgroud)
请注意,input_shape
参数必须与数据的形状完全匹配,不包括批量大小(40000).
对于图像,你肯定会使用2D卷积(除非你有一些非常标准的想法).1D卷积适用于序列.这很简单:
channels
但是,所有这些都将为输入添加额外的维度.
2D卷积层需要两种可能性,具体取决于您的keras配置:
(BatchSize, pixelsX, pixelsY, channels)
(BatchSize, channels, pixelsX, pixelsY)
您没有将批量大小传递给input_shape
,因此您可以使用以下方法之一:
#channels last (if you have 1 channel only, but if you have RGB, use 3 instead of 1
model.add(Conv2D(32, (2,2), input_shape=(16, 16, 1), activation='relu'))
#channels first (if you have 1 channel only, but if you have RGB, use 3 instead of 1
model.add(Conv2D(32, (2,2), input_shape=(1,16, 16), activation='relu'))
Run Code Online (Sandbox Code Playgroud)
您可以在位于的文件中找到您的keras默认配置<yourUserFolder>/.keras/keras.json
.
data_format
如果需要,您还可以将单个参数传递给每个卷积层.