我在一个包含40张花卉图像的训练数据集上使用了以下代码,但CNN分类器未能对其进行分类。
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Conv2D
from tensorflow.keras.layers import MaxPooling2D
from tensorflow.keras.layers import Flatten
from tensorflow.keras.layers import Dense
from tensorflow.keras.preprocessing.image import ImageDataGenerator
model = Sequential()
model.add(Conv2D(16, (3, 3), input_shape = (32, 32, 3), activation = 'relu'))
model.add(MaxPooling2D(pool_size = (2, 2)))
model.add(Flatten())
model.add(Dense(units = 128, activation = 'relu'))
model.add(Dense(units = 4, activation = 'softmax'))
model.summary()
model.compile(optimizer = 'adam', loss = 'categorical_crossentropy', metrics = ['accuracy'])
train_datagen = ImageDataGenerator(rescale = 1./255,
shear_range = 0.2,
zoom_range = 0.2,
horizontal_flip = True)
val_datagen = ImageDataGenerator(rescale = 1./255)
training_set =
train_datagen.flow_from_directory('C:\Users\vinay\flowerclassification\dataset\train',
target_size = (32, 32),
batch_size = 8
)
val_set =
val_datagen.flow_from_directory('C:\Users\vinay\flowerclassification\dataset\val',
target_size = (32, 32),
batch_size = 8)
model.fit(training_set,
steps_per_epoch = 10,
epochs = 25,
validation_data = val_set,
validation_steps = 4)
model_json = model.to_json()
with open("model.json", "w") as json_file:
json_file.write(model_json)
model.save_weights("model.h5")
print("Saved model to disk")
/usr/local/lib/python3.7/dist-packages/tensorflow/python/keras/engine/training.py:1940: UserWarning:Model.fit_generator
已弃用,将在未来的版本中删除。请使用Model.fit
,它支持发电机。警告。警告('Model.fit_generator
已弃用'和'
ValueError Traceback(最近一次调用)在()——比;1模型。Fit_generator (training_set,steps_per_epoch = 10,epochs = 25,validation_data = val_set,validation_steps = 2)
7帧/usr/local/lib/python3.7/dist-packages/keras_preprocessing/image/iterator.py ingetitem(自我idx)55"但是顺序"{{length}}'.format(idx=idx,——比;57 长度= len(自我)))如果自我。种子不是无;59 np.random.seed(自我。Seed + self.total_batches_seen)
ValueError:请求检索元素0,但序列长度为0
在上一步中也打印了这个消息:找到属于0个类的0个图像。发现0个图片属于0个类。
请从model.fit
中删除steps_per_epoch
和validation_steps
,再试一次执行上述相同的代码:
model.fit(training_set,
#steps_per_epoch = 10,
epochs = 25,
validation_data = val_set,
# validation_steps = 4
)
Steps_per_epoch
和validation_steps
不正确。从模型中删除这些将根据给定的images_count
和batch_size
计算steps_per_epoch
。参考这个类似的答案。
从警告开始,它显示Model.fit_generator
已被弃用。您可以使用model.fit
来删除警告。如果问题仍然存在,请告诉我们。