在Keras中搭建卷積神經網絡(CNN)可以通過Sequential模型或Functional API來實現。下面分別介紹這兩種方法:
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()
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方法來訓練模型。