在Keras中搭建卷积神经网络(CNN)可以通过Sequential模型或Functional API来实现。下面分别介绍这两种方法:
- Sequential模型:
from keras.models import Sequential from keras.layers import Conv2D, MaxPooling2D, Flatten, Dense model = Sequential() # 添加卷积层和池化层 model.add(Conv2D(filters=32, kernel_size=(3, 3), activation='relu', input_shape=(28, 28, 1))) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Conv2D(filters=64, kernel_size=(3, 3), activation='relu')) model.add(MaxPooling2D(pool_size=(2, 2))) # 展平层 model.add(Flatten()) # 添加全连接层 model.add(Dense(units=128, activation='relu')) model.add(Dense(units=10, activation='softmax')) model.summary()
- Functional API:
from keras.models import Model from keras.layers import Input, Conv2D, MaxPooling2D, Flatten, Dense input_layer = Input(shape=(28, 28, 1)) # 添加卷积层和池化层 conv1 = Conv2D(filters=32, kernel_size=(3, 3), activation='relu')(input_layer) pool1 = MaxPooling2D(pool_size=(2, 2))(conv1) conv2 = Conv2D(filters=64, kernel_size=(3, 3), activation='relu')(pool1) pool2 = MaxPooling2D(pool_size=(2, 2))(conv2) # 展平层 flatten = Flatten()(pool2) # 添加全连接层 fc1 = Dense(units=128, activation='relu')(flatten) output_layer = Dense(units=10, activation='softmax')(fc1) model = Model(inputs=input_layer, outputs=output_layer) model.summary()
以上是搭建一个简单的卷积神经网络的示例,你可以根据具体的任务需求和数据集来调整网络结构和参数。训练模型时,你需要使用compile方法来编译模型,并调用fit方法来训练模型。