【发布时间】:2020-11-05 22:58:54
【问题描述】:
import keras
from keras_self_attention import SeqSelfAttention
inputs = keras.layers.Input(shape=(None,))
embd = keras.layers.Embedding(vocab_size,
300, weights=[embedding_matrix],
trainable=False, mask_zero=True, name='Encoder-Word-Embedding')(inputs)
lstm = keras.layers.Bidirectional(keras.layers.LSTM(units=150,
return_sequences=True))(embd)
att = SeqSelfAttention(attention_type=SeqSelfAttention.ATTENTION_TYPE_MUL,
kernel_regularizer=keras.regularizers.l2(1e-4),
bias_regularizer=keras.regularizers.l1(1e-4),
attention_regularizer_weight=1e-4,
name='Attention')(lstm)
dense = keras.layers.Dense(units=max_seq_len_y, name='Dense')(att)
model = keras.models.Model(inputs=inputs, outputs=[dense])
model.compile(
optimizer='adam',
loss={'Dense': 'sparse_categorical_crossentropy'},
metrics={'Dense': 'categorical_accuracy'},
)
model.summary()
history = model.fit(x=X, y=y, batch_size=1, epochs=32)
X.shape, y.shape
=> ((52, 139), (52, 14))
X[0]
数组([293, 40, 294, 129, 75, 130, 129, 131, 295, 296, 132, 297, 298, 2、299、34、12、76、300、27、301、15、1、302、133、4、 77、303、3、134、304、78、34、305、11、306、307、4、1、 132、135、22、10、308、11、136、4、1、309、50、4、310、 11、78、311、312、3、77、1、313、130、10、137、11、12、 109、7、314、315、7、1、76、316、4、317、318、34、138、 319, 139, 320, 3, 77, 321, 79, 322, 4, 1, 323, 324, 4, 1, 325, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
y[0]
数组([1040, 1041, 2, 1042, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0])
这里的 X,y 表示使用 keras tokenizer 库转换的序列。我的目标是学习段落的标题。
【问题讨论】:
标签: python tensorflow machine-learning deep-learning nlp