如何在喀拉拉邦中使用带有灰度图像的中性网络

时间:2019-04-08 11:23:38

标签: keras neural-network

我正在尝试训练灰色图像。 batch_size = 32, image size = (48*48)。 我定义了我的网络input_shape = (48,48,1)。训练网络时,我收到类似以下的错误。

错误:

  

ValueError:检查输入时出错:预期conv2d_17_input具有4维,但数组的形状为(32,48,48)

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

3 个答案:

答案 0 :(得分:1)

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

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

现在,为了提供此数据以训练CNN,您必须将此列表重塑为(1000, 48, 48, 1),其中1代表渠道维度。由于您具有灰度图像,因此必须使用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)

这将引发错误

  

检查输入时出错:预期conv2d_3_input具有4维,但数组的形状为(1000,48,48)

要解决此问题,应像这样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

答案 1 :(得分:0)

即使输入是灰度,您的输入也应具有4个尺寸。因此,您可以使用np.reshape(input,(32,48,48,1))np.expand_dims(input,axis=3)

答案 2 :(得分:0)

您的图片应重塑为// xml config <context:annotation-config/> <beans> // use the primary tag here too! in order to say this the primary bean // this only works when there are only two implementations of the same interface <bean id="bike" primary="true" class="your_pkg_route.Bike"/> <bean id="car" class="your_pkg_route.Car"/> <bean autowire="byName" class="your_pkg_route.VehicleService"/> <beans> </context:annotation-config> // VehicleService @Component public class VehicleService { private Vehicle bike; // call attribute 'bike' so it is autowired by its name public void service() { //... } } ,而您的(sample_length, 48, 48, 1)

input_shape = (48, 48, 1)

您可以查看MNIST示例here,它与您的情况类似。