我正在構建一個影像字幕模型,為此我將ResNet50其用作特征提取模型。我已經撰寫了代碼,并且可以正常作業:
rs50 = tf.keras.applications.ResNet50(include_top = False, weights = 'imagenet', input_shape = (224, 224, 3))
new_input = rs50.input
hidden_layer = rs50.layers[-1].output
feature_extract = tf.keras.Model(new_input, hidden_layer)
以下是模型摘要 ( feature_extract.summary()) 的最后幾行:
conv5_block3_3_bn (BatchNormal (None, 7, 7, 2048) 8192 ['conv5_block3_3_conv[0][0]']
ization)
conv5_block3_add (Add) (None, 7, 7, 2048) 0 ['conv5_block2_out[0][0]',
'conv5_block3_3_bn[0][0]']
conv5_block3_out (Activation) (None, 7, 7, 2048) 0 ['conv5_block3_add[0][0]']
==================================================================================================
Total params: 23,587,712
Trainable params: 23,534,592
Non-trainable params: 53,120
但是,問題在于它生成了 2048 個特征。我沒有那么多記憶,所以我想把它改成我該(None, 7, 7, 2048)怎么(None, 7, 7, 1024)
做?
uj5u.com熱心網友回復:
一種方法是找到具有輸出形狀的最后一層(None, 14, 14, 1024)并提取模型的層直到該點。該conv4_block6_out層恰好是最后一個塊開始之前的最后一層。這樣,最后一個塊被完全跳過,從而節省了更多記憶體。然后,應用一個或多個Conv2D或MaxPooling層來獲得形狀(None, 7, 7, 1024):
import tensorflow as tf
rs50 = tf.keras.applications.ResNet50(include_top = False, weights = 'imagenet', input_shape = (224, 224, 3))
index = 0
for i, l in enumerate(rs50.layers):
if 'conv4_block6_out' in l.name:
index = i
new_input = rs50.input
hidden_layer = rs50.layers[index].output
output = tf.keras.layers.Conv2D(1024, kernel_size=8)(hidden_layer)
feature_extract = tf.keras.Model(new_input, output)
print(feature_extract.output)
KerasTensor(type_spec=TensorSpec(shape=(None, 7, 7, 1024), dtype=tf.float32, name=None), name='conv2d_4/BiasAdd:0', description="created by layer 'conv2d_4'")
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/465896.html
