我想制作一个简单的CNN模型,以预测图像的颜色(红色或绿色)。我人为地制作了包含红色或绿色背景的图像数据集,并在其上构建了CNN模型。在每个时期,火车的精度始终保持在50%。我以为是数据,但是找不到数据错误。因此,我认为让我们创建随机数据,看看它是否仍保持50%不变。在这种情况下,它应该每次波动约50%,但不会波动50%。这是我使用的代码:
from keras.preprocessing.image import ImageDataGenerator
from keras.applications.vgg16 import VGG16
from keras.layers import Dense, Flatten, Input
from keras.models import Model
import numpy as np
X = np.random.rand(140,224,224,3)
y = [0]*70 + [1]*70
y = to_categorical(y)
def train_model():
vgg = VGG16(weights="imagenet", include_top=False)
input = Input(shape=(224,224,3),name = 'image_input')
output_vgg16_conv = vgg(input)
x = Flatten(name='flatten')(output_vgg16_conv)
x = Dense(128, activation='relu', name='fc1')(x)
x = Dense(128, activation='relu', name='fc2')(x)
x = Dense(2, activation='softmax', name='predictions')(x)
model = Model(input=input, output=x)
print(model.summary())
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
model.fit(X,y, epochs=10, batch_size=32)
return model
train_model()
我得到以下输出:
Layer (type) Output Shape Param #
=================================================================
image_input (InputLayer) (None, 224, 224, 3) 0
_________________________________________________________________
vgg16 (Model) multiple 14714688
_________________________________________________________________
flatten (Flatten) (None, 25088) 0
_________________________________________________________________
fc1 (Dense) (None, 128) 3211392
_________________________________________________________________
fc2 (Dense) (None, 128) 16512
_________________________________________________________________
predictions (Dense) (None, 2) 258
=================================================================
Total params: 17,942,850
Trainable params: 17,942,850
Non-trainable params: 0
_________________________________________________________________
None
Epoch 1/10
140/140 [==============================] - 6s 40ms/step - loss: 6.4980 - acc: 0.4857
Epoch 2/10
140/140 [==============================] - 4s 27ms/step - loss: 8.0590 - acc: 0.5000
Epoch 3/10
140/140 [==============================] - 4s 27ms/step - loss: 8.0590 - acc: 0.5000
Epoch 4/10
140/140 [==============================] - 4s 27ms/step - loss: 8.0590 - acc: 0.5000
Epoch 5/10
140/140 [==============================] - 4s 27ms/step - loss: 8.0590 - acc: 0.5000
Epoch 6/10
140/140 [==============================] - 4s 27ms/step - loss: 8.0590 - acc: 0.5000
Epoch 7/10
140/140 [==============================] - 4s 27ms/step - loss: 8.0590 - acc: 0.5000
Epoch 8/10
140/140 [==============================] - 4s 27ms/step - loss: 8.0590 - acc: 0.5000
Epoch 9/10
140/140 [==============================] - 4s 27ms/step - loss: 8.0590 - acc: 0.5000
Epoch 10/10
140/140 [==============================] - 4s 27ms/step - loss: 8.0590 - acc: 0.5000
持续获得50%表示我在训练中做错了,很可能不在数据中。在培训过程中我做错了什么?