gpt4 book ai didi

keras - 我如何在 keras 中使用带有灰度图像的神经网络

转载 作者:行者123 更新时间:2023-12-04 14:37:40 36 4
gpt4 key购买 nike

我正在尝试对灰色图像进行训练。 batch_size = 32, image size = (48*48) .
我定义我的网络 input_shape = (48,48,1) .训练网络时出现如下错误。

错误 :

ValueError: Error when checking input: expected conv2d_17_input to have 4 dimensions, but got array with shape (32, 48, 48)


model.add(Conv2D(32, kernel_size=(5, 5),
activation='relu',
input_shape=(48,48,1)
)
)

最佳答案

假设您有 1000训练图像,其中每个图像是 48x48灰度。将图像加载到 numpy 数组中后,您将得到以下形状:(1000, 48, 48) .

这实质上意味着您有 1000数组中的元素,每个元素都是 48x48矩阵。

现在为了提供这些数据来训练 CNN ,您必须将此列表 reshape 为 (1000, 48, 48, 1)哪里1代表 channel 维度。由于您使用的是灰度图像,因此您必须使用 1 .如果是 RGB,它将是 3 .

考虑下面给出的玩具示例,

x_train = np.random.rand(1000, 48, 48) #images
y_train = np.array([np.random.randint(0, 2) for x in range(1000)]) # labels

# simple model

model = Sequential()

model.add(Conv2D(32, kernel_size=(5, 5),
activation='relu',
input_shape=(48,48,1)
)
)

model.add(Flatten())

model.add(Dense(1, activation='sigmoid'))
model.compile(loss='binary_crossentropy', optimizer='adam')

# fitting model
model.fit(x_train, y_train, epochs=10, batch_size=32)

这将引发错误,

Error when checking input: expected conv2d_3_input to have 4 dimensions, but got array with shape (1000, 48, 48)



要修复它,请 reshape x_train像这样,
x_train = x_train.reshape(x_train.shape[0], x_train.shape[1], x_train.shape[2], 1)
现在拟合模型,
model.fit(x_train, y_train, epochs=10, batch_size=32)

Epoch 1/10
1000/1000 [==============================] - 1s 1ms/step - loss: 0.7177
Epoch 2/10
1000/1000 [==============================] - 1s 882us/step - loss: 0.6762
Epoch 3/10
1000/1000 [==============================] - 1s 870us/step - loss: 0.5882
Epoch 4/10
1000/1000 [==============================] - 1s 888us/step - loss: 0.4588
Epoch 5/10
1000/1000 [==============================] - 1s 906us/step - loss: 0.3272
Epoch 6/10
1000/1000 [==============================] - 1s 910us/step - loss: 0.2228
Epoch 7/10
1000/1000 [==============================] - 1s 895us/step - loss: 0.1607
Epoch 8/10
1000/1000 [==============================] - 1s 879us/step - loss: 0.1172
Epoch 9/10
1000/1000 [==============================] - 1s 886us/step - loss: 0.0935
Epoch 10/10
1000/1000 [==============================] - 1s 888us/step - loss: 0.0638

关于keras - 我如何在 keras 中使用带有灰度图像的神经网络,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55572325/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com