我正在研究用于文本分类问题的Bert + MLP模型。本质上,我正在尝试用基本的LSTM模型替换MLP模型。
是否可以通过嵌入创建LSTM?还是最好创建具有嵌入式层的LSTM?
更具体地说,我很难创建嵌入式矩阵,因此可以使用Bert嵌入来创建嵌入层。
def get_bert_embeddings(dataset='gap_corrected_train',
dataset_path=TRAIN_PATH,
bert_path=BERT_UNCASED_LARGE_PATH,
bert_layers=BERT_LAYERS):
"""Get BERT embeddings for all files in dataset_path and specified BERT layers and write them to file."""
df = None
for file in os.listdir(dataset_path):
if df is None:
df = pd.read_csv(dataset_path+'/'+file, sep='\t')
else:
next_df = pd.read_csv(dataset_path+'/'+file, sep='\t')
df = pd.concat([df, next_df], axis=0)
df.reset_index(inplace=True, drop=True)
for i, layer in enumerate(bert_layers):
embeddings_file = INTERIM_PATH + 'emb_bert' + str(layer) + '_' + dataset + '.h5'
if not os.path.exists(embeddings_file):
print('Embeddings file: ', embeddings_file)
print('Extracting BERT Layer {0} embeddings for {1}...'.format(layer, dataset))
print("Started at ", time.ctime())
emb = get_bert_token_embeddings(df, bert_path, layer)
emb.to_hdf(embeddings_file, 'table')
print("Finished at ", time.ctime())
def build_mlp_model(input_shape):
input_layer = layers.Input(input_shape)
input_features = layers.Input((len(FEATURES),))
x = layers.Concatenate(axis=1, name="concate_layer")([input_layer, input_features])
x = layers.Dense(HIDDEN_SIZE, name='dense1')(x)
x = layers.BatchNormalization()(x)
x = layers.Activation('relu')(x)
x = layers.Dropout(DROPOUT, seed=RANDOM)(x)
x = layers.Dense(HIDDEN_SIZE//2, name='dense2')(x)
x = layers.BatchNormalization()(x)
x = layers.Activation('relu')(x)
x = layers.Dropout(DROPOUT//2, seed=RANDOM)(x)
x = layers.Dense(HIDDEN_SIZE//4, name='dense3')(x)
x = layers.BatchNormalization()(x)
x = layers.Activation('relu')(x)
x = layers.Dropout(DROPOUT//2, seed=RANDOM)(x)
output_layer = layers.Dense(3, name='output', kernel_regularizer = regularizers.l2(LAMBDA))(x)
output_layer = layers.Activation('softmax')(output_layer)
model = models.Model(input=[input_layer, input_features], output=output_layer, name="mlp")
return model
答案 0 :(得分:2)
您可以创建一个模型,该模型首先使用Embedding层,然后使用LSTM,然后使用Dense。 如此处:
deep_inputs = Input(shape=(length_of_your_data,))
embedding_layer = Embedding(vocab_size, output_dim = 3000, trainable=True)(deep_inputs)
LSTM_Layer_1 = LSTM(512)(embedding_layer)
dense_layer_1 = Dense(number_of_classes, activation='softmax')(LSTM_Layer_1)
model_AdGroups = Model(inputs=deep_inputs, outputs=dense_layer_1)