Keras中的Masking和Padding

对于变长特征编码,我们往往需要用到此。它们的作用是:

  • Padding:将本来不相同的样本填充到相同的长度,以便于后面的处理,我们一般使用0做填充
  • Mask:告诉网络层那些是真正的数据,哪些是填充的“0”,从而帮助网络层更好地计算

目的:提升序列模型的精度和准确率

使用方法如下:

# 第一步,将数据padding
raw_inputs = [[1,2],[3,4,5],[6,7,8,9,10,100,1000,1,1,1,1,1]]
inputs = keras.preprocessing.sequence.pad_sequences(raw_inputs, padding="post", value=0)
print(inputs, type(inputs))

# 第二步,对无效数据做Mask,添加一个keras.layers.Masking层
input_x = Input(shape=(12,), name="in")
masking_layer = Masking(input_shape=(12,), mask_value=0)
input_masked = masking_layer(input_x)
embedd = Embedding(10000, 32)(input_masked)
avg_layer = GlobalAveragePooling1D()(embedd)
dense_layer = Dense(64, activation="relu")(avg_layer)
out_y = Dense(1, activation="sigmoid")(dense_layer)
model = Model(inputs=input_x, outputs=out_y)
model.summary()

 

# 不做掩码
input_x = Input(shape=(12,), name="in")
embedd = Embedding(10000, 32)(input_x)
avg_layer = GlobalAveragePooling1D()(embedd)
dense_layer = Dense(64, activation="relu")(avg_layer)
out_y = Dense(1, activation="sigmoid")(dense_layer)
model2 = Model(inputs=input_x, outputs=out_y)
model2.summary()

 

# seq方式测试
model3 = tf.keras.Sequential([
    tf.keras.layers.Masking(input_shape=(12,)),
    tf.keras.layers.Embedding(10000, 32),
    tf.keras.layers.GlobalAveragePooling1D(),
    tf.keras.layers.Dense(64, activation='relu'),
    tf.keras.layers.Dense(1, activation='sigmoid')
])
model3.summary()

 

 对比结果展示:

 

 

 

posted @ 2022-03-02 16:26  今夜无风  阅读(695)  评论(0编辑  收藏  举报