keras搭建的CNN-BiLSTM进行图像分类python代码
时间: 2023-07-26 12:04:48 浏览: 123
以下是使用Keras搭建的CNN-BiLSTM进行图像分类的Python代码示例:
```python
from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPooling2D, LSTM, Bidirectional
from keras.optimizers import Adam
from keras.utils import to_categorical
# 定义CNN-BiLSTM模型
def create_model(input_shape, num_classes):
model = Sequential()
model.add(Conv2D(32, kernel_size=(3, 3), activation='relu', input_shape=input_shape))
model.add(Conv2D(64, kernel_size=(3, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))
model.add(Flatten())
model.add(Dense(128, activation='relu'))
model.add(Dropout(0.5))
model.add(Bidirectional(LSTM(128, return_sequences=False)))
model.add(Dense(num_classes, activation='softmax'))
optimizer = Adam(lr=0.001, decay=1e-6)
model.compile(loss='categorical_crossentropy', optimizer=optimizer, metrics=['accuracy'])
return model
# 加载数据集并进行预处理
(x_train, y_train), (x_test, y_test) = load_data()
x_train = x_train.reshape(x_train.shape[0], 28, 28, 1)
x_test = x_test.reshape(x_test.shape[0], 28, 28, 1)
y_train = to_categorical(y_train, num_classes=10)
y_test = to_categorical(y_test, num_classes=10)
# 创建CNN-BiLSTM模型
model = create_model(input_shape=(28, 28, 1), num_classes=10)
# 训练模型
model.fit(x_train, y_train, batch_size=128, epochs=10, verbose=1, validation_data=(x_test, y_test))
# 评估模型
score = model.evaluate(x_test, y_test, verbose=0)
print('Test loss:', score[0])
print('Test accuracy:', score[1])
```
在这个示例中,我们使用了MNIST数据集进行图像分类,该数据集包含手写数字的图像。我们首先定义了一个名为`create_model`的函数,该函数创建CNN-BiLSTM模型。然后,我们加载了MNIST数据集并进行了必要的预处理。最后,我们使用`fit`方法训练模型,并使用`evaluate`方法评估模型的性能。
阅读全文