【发布时间】:2020-08-06 21:13:20
【问题描述】:
我正在使用 huggingface TFBertModel 来执行分类任务(来自 here: ),我使用的是裸露的 TFBertModel 并添加了头部密集层而不是 TFBertForSequenceClassification,因为我没有看到我是如何可以使用后者使用预训练的权重来仅微调模型。
据我所知,微调应该能让我在 BERT 和 ALBERT 中获得大约 80% 或更高的准确度,但我什至没有接近这个数字:
Train on 3600 samples, validate on 400 samples
Epoch 1/2
3600/3600 [==============================] - 177s 49ms/sample - loss: 0.6531 - accuracy: 0.5792 - val_loss: 0.5296 - val_accuracy: 0.7675
Epoch 2/2
3600/3600 [==============================] - 172s 48ms/sample - loss: 0.6288 - accuracy: 0.6119 - val_loss: 0.5020 - val_accuracy: 0.7850
更多的时代没有太大的区别。
我正在使用 CoLA public data set 进行微调,这是数据的样子:
gj04 1 Our friends won't buy this analysis, let alone the next one we propose.
gj04 1 One more pseudo generalization and I'm giving up.
gj04 1 One more pseudo generalization or I'm giving up.
gj04 1 The more we study verbs, the crazier they get.
...
这是将数据加载到 python 中的代码:
import csv
def get_cola_data(max_items=None):
csv_file = open('cola_public/raw/in_domain_train.tsv')
reader = csv.reader(csv_file, delimiter='\t')
x = []
y = []
for row in reader:
x.append(row[3])
y.append(float(row[1]))
if max_items is not None:
x = x[:max_items]
y = y[:max_items]
return x, y
我验证了数据的格式是我希望它出现在列表中的格式,这是模型本身的代码:
#!/usr/bin/env python
import tensorflow as tf
from tensorflow import keras
from transformers import BertTokenizer, TFBertModel
import numpy as np
from cola_public import get_cola_data
tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')
bert_model = TFBertModel.from_pretrained('bert-base-uncased')
bert_model.trainable = False
x_input = keras.Input(shape=(512,), dtype=tf.int64)
x_mask = keras.Input(shape=(512,), dtype=tf.int64)
_, output = bert_model([x_input, x_mask])
output = keras.layers.Dense(1)(output)
model = keras.Model(
inputs=[x_input, x_mask],
outputs=output,
name='bert_classifier',
)
model.compile(
loss=keras.losses.BinaryCrossentropy(from_logits=True),
optimizer=keras.optimizers.Adam(),
metrics=['accuracy'],
)
train_data_x, train_data_y = get_cola_data(max_items=4000)
encoded_data = [tokenizer.encode_plus(data, add_special_tokens=True, pad_to_max_length=True) for data in train_data_x]
train_data_x = np.array([data['input_ids'] for data in encoded_data])
mask_data_x = np.array([data['attention_mask'] for data in encoded_data])
train_data_y = np.array(train_data_y)
model.fit(
[train_data_x, mask_data_x],
train_data_y,
epochs=2,
validation_split=0.1,
)
cmd_input = ''
while True:
print("Type an opinion: ")
cmd_input = input()
# print('Your opinion is: %s' % cmd_input)
if cmd_input == 'exit':
break
cmd_input_tokens = tokenizer.encode_plus(cmd_input, add_special_tokens=True, pad_to_max_length=True)
cmd_input_ids = np.array([cmd_input_tokens['input_ids']])
cmd_mask = np.array([cmd_input_tokens['attention_mask']])
model.reset_states()
result = model.predict([cmd_input_ids, cmd_mask])
print(result)
现在,无论我是否使用其他数据集,数据集中其他数量的项目,如果我在最后一个密集层之前使用一个 dropout 层,如果我在最后一个密集层之前给出另一个具有更高单元数的密集层,或者如果我用的是 Albert 而不是 BERT,我总是准确率低,损失高,而且经常验证准确率高于训练准确率。
如果我尝试将 BERT/ALBERT 用于 NER 任务,我得到相同的结果,总是相同的结果,这让我相信我在微调中系统地犯了一些基本错误。
我知道我有bert_model.trainable = False,这就是我想要的,因为我只想训练最后一个头而不是预训练的重量,而且我知道人们以这种方式训练成功。即使我使用预训练的权重进行训练,结果也会差很多。
我发现我的欠拟合度非常高,但我无法在这方面有所改进,尤其是看到人们倾向于在模型顶部仅使用单个密集层时获得良好的结果。
【问题讨论】:
标签: python tensorflow machine-learning keras deep-learning