首页 > 解决方案 > 如何在 Keras 中实现 CNN2D+ LSTM 模型进行图像分类?

问题描述

有 2550 张图像作为训练集,1530 张图像作为测试集。为了将这些图像分为两类,使用了包含 CNN2D+LSTM 的混合深度学习模型,但在运行代码时出现错误,如下所示。我想知道是否有人帮我解决它。提前致谢

错误:

RuntimeError:您必须在使用模型之前对其进行编译

# importing libraries
from keras.models import Sequential
from keras.layers import Convolution2D
from keras.layers import MaxPooling2D
from keras.layers import Flatten
from keras.layers import Dense
from keras.layers import LSTM
from keras.layers import TimeDistributed

from keras.preprocessing.image import ImageDataGenerator
train_datagen = ImageDataGenerator(
                                    rescale=1./255,
                                    shear_range=0.2,
                                    zoom_range=0.2,
                                    horizontal_flip=True)
test_datagen = ImageDataGenerator(rescale=1./255)
training_set = train_datagen.flow_from_directory(
                                    'D:\\thesis\\Paper 3\\Feature Extraction\\two_dimension_Feature_extraction\\stft_feature\\Training_set',
                                    target_size=(64, 64),
                                    batch_size=32,
                                    class_mode='binary')
test_set = test_datagen.flow_from_directory(
                                    'D:\\thesis\\Paper 3\\Feature Extraction\\two_dimension_Feature_extraction\\stft_feature\\Test_set',
                                    target_size=(64, 64),
                                    batch_size=32,
                                    class_mode='binary')

#initializing the CNN
classifier = Sequential()

#convolution2D
classifier.add(TimeDistributed(Convolution2D(32,3,3, input_shape = (64,64,3), activation = 'relu'))) #32 feature detector with 3*3 dimensions, 64*64 is the used format with 3 channel because the image is colored

#adding maxpooling 
classifier.add(TimeDistributed(MaxPooling2D(2, 2)))
#Flattening
classifier.add(TimeDistributed(Flatten()))

classifier.add(TimeDistributed(classifier))
classifier.add(LSTM(units= 20, input_shape = (1,5), return_sequences = True ))
classifier.add(LSTM(units = 20))

#Full Connection
classifier.add(Dense(output_dim = 128, activation = 'relu'))
classifier.add(Dense(output_dim = 1, activation = 'sigmoid'))

#compiling the CNN
classifier.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = ['accuracy'])

#Fitting the CNN to the images

history = classifier.fit_generator(training_set,
                         steps_per_epoch=2550,
                         epochs=25,
                         validation_data= test_set,
                         validation_steps=510)

import matplotlib.pyplot as plt
acc = history.history['acc']
val_acc = history.history['val_acc']
loss = history.history['loss']
val_loss = history.history['val_loss']
epochs = range(1, len(acc) + 1)
plt.plot(epochs, acc, 'r', label='Training acc')
plt.plot(epochs, val_acc, 'b', label='Validation acc')
plt.title('Training and validation accuracy')
plt.legend()
plt.figure()
plt.plot(epochs, loss, 'r', label='Training loss')
plt.plot(epochs, val_loss, 'b', label='Validation loss')
plt.title('Training and validation loss')
plt.plot()
plt.legend()
plt.show()

test_loss, test_acc = classifier.evaluate(test_set)
print('test_acc:', test_acc)

标签: pythonkeraslstmconv-neural-network

解决方案


推荐阅读