Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Thêm Dense layer lên trên Conv base TensorFlow/Keras Python

Sau các layer Conv2D, thêm Flatten và Dense layers để phân loại.

Mã ví dụ

print("Thêm Dense layer lên trên...")
model.add(layers.Flatten())
model.add(layers.Dense(64, activation='relu'))
model.add(layers.Dense(10))

print("Kiến trúc hoàn chỉnh:")
model.summary()

Kết quả

Thêm Dense layer lên trên...
Kiến trúc hoàn chỉnh:
Model: "sequential_1"
_________________________________________________________________
Layer (type)                 Output Shape              Param #
=================================================================
conv2d_3 (Conv2D)            (None, 30, 30, 32)        896
max_pooling2d_2 (MaxPooling2 (None, 15, 15, 32)        0
conv2d_4 (Conv2D)            (None, 13, 13, 64)        18496
max_pooling2d_3 (MaxPooling2 (None, 6, 6, 64)          0
conv2d_5 (Conv2D)            (None, 4, 4, 64)          36928
flatten (Flatten)            (None, 1024)              0
dense (Dense)                (None, 64)                65600
dense_1 (Dense)              (None, 10)                650
=================================================================
Total params: 122,570
Trainable params: 122,570
Non-trainable params: 0
_________________________________________________________________

Giải thích

  • Output Conv base: (4, 4, 64) = 1024 features.
  • Flatten: (4,4,64) → (1024,) vector 1D.
  • Dense(64, relu): Hidden layer 64 units. Params = 1024*64 + 64 = 65,600.
  • Dense(10): Output 10 classes (CIFAR-10). Params = 64*10 + 10 = 650.
  • Tổng params: 122,570 (nhẹ, train nhanh trên CPU).
  • model.add() nối layer tuần tự vào Sequential model.