Skip to content

Commit 0f83d3f

Browse files
author
chongjiu.jin
committed
python bert code fix
1 parent 8b91556 commit 0f83d3f

File tree

5 files changed

+55
-31
lines changed

5 files changed

+55
-31
lines changed

pytorch-bert-code/bert-example.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@
3232
tokenizer = tokenization(vocab_file=vocab_file, do_lower_case=do_lower_case)
3333

3434
# 加载模型
35-
model_bert = BertModel.from_pretrained(bert_path)
35+
model_bert = BertModel.from_pretrained(bert_path,config=bert_config)
3636
model_bert.to(device)
3737

3838

pytorch-bert-code/bert.py

+22-27
Original file line numberDiff line numberDiff line change
@@ -1,30 +1,29 @@
11
# coding: UTF-8
22
import torch
33
import torch.nn as nn
4-
import torch.nn.functional as F
54
# from pytorch_pretrained_bert import BertModel, BertTokenizer
6-
from transformers import BertModel, BertTokenizer
7-
5+
from transformers import BertModel, BertTokenizer,BertConfig
6+
import os
87

98
class Config(object):
109

1110
"""配置参数"""
1211
def __init__(self, dataset):
1312
self.model_name = 'bert'
14-
self.train_path = dataset + '/data/train.txt'
15-
self.dev_path = dataset + '/data/dev.txt'
16-
self.test_path = dataset + '/data/test.txt'
13+
self.train_path = dataset + '/data/train.txt' # 训练集
14+
self.dev_path = dataset + '/data/dev.txt' # 验证集
15+
self.test_path = dataset + '/data/test.txt' # 测试集
1716
self.class_list = [x.strip() for x in open(
18-
dataset + '/data/class.txt').readlines()]
19-
self.save_path = dataset + '/saved_dict/' + self.model_name + '.ckpt'
20-
self.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
21-
22-
23-
self.num_classes = len(self.class_list)
24-
self.num_epochs = 3
25-
self.batch_size = 128
26-
self.pad_size = 32
27-
self.learning_rate = 5e-5
17+
dataset + '/data/class.txt').readlines()] # 类别名单
18+
self.save_path = dataset + '/saved_dict/' + self.model_name + '.ckpt' # 模型训练结果
19+
self.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') # 设备
20+
21+
self.require_improvement = 1000 # 若超过1000batch效果还没提升,则提前结束训练
22+
self.num_classes = len(self.class_list) # 类别数
23+
self.num_epochs = 3 # epoch数
24+
self.batch_size = 128 # mini-batch大小
25+
self.pad_size = 32 # 每句话处理成的长度(短填长切)
26+
self.learning_rate = 5e-5 # 学习率
2827
self.bert_path = './bert'
2928
self.tokenizer = BertTokenizer.from_pretrained(self.bert_path)
3029
self.hidden_size = 768
@@ -34,20 +33,16 @@ class Model(nn.Module):
3433

3534
def __init__(self, config):
3635
super(Model, self).__init__()
37-
self.bert = BertModel.from_pretrained(config.bert_path)
36+
bert_config_file = os.path.join(config.bert_path, f'bert_config.json')
37+
bert_config = BertConfig.from_json_file(bert_config_file)
38+
self.bert = BertModel.from_pretrained(config.bert_path,config=bert_config)
3839
for param in self.bert.parameters():
3940
param.requires_grad = True
4041
self.fc = nn.Linear(config.hidden_size, config.num_classes)
4142

42-
43-
def forward(self, input_ids,# 输入的句子
44-
input_mask,# 对padding部分进行mask,和句子一个size,padding部分用0表示,如:[1, 1, 1, 1, 0, 0]
45-
segments_ids
46-
):
47-
_, pooled = self.bert(input_ids, attention_mask=input_mask,token_type_ids=segments_ids)#pooled [batch_size, hidden_size]
43+
def forward(self, x):
44+
context = x[0] # 输入的句子
45+
mask = x[2] # 对padding部分进行mask,和句子一个size,padding部分用0表示,如:[1, 1, 1, 1, 0, 0]
46+
_, pooled = self.bert(context, attention_mask=mask)
4847
out = self.fc(pooled)
4948
return out
50-
def loss(self,outputs,labels):
51-
criterion=F.cross_entropy
52-
loss = criterion(outputs, labels)
53-
return loss

pytorch-bert-code/bert/README.md

+13-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,18 @@
1-
### how to convert bert Converting Tensorflow Checkpoints to pytorch model file
21

2+
update to transformer 2.3.0
33

4+
转换工具已经失效
5+
6+
chinese bert
7+
8+
https://github.com/ymcui/Chinese-BERT-wwm/blob/master/README_EN.md
9+
10+
下载 BERT-wwm-ext, Chinese 或者 BERT-wwm, Chinese pytorch模型
11+
12+
13+
-------
14+
15+
transformer 2.1.1
416
### 如何将bert model 的Tensorflow模型 转换为pytorch模型
517

618

pytorch-bert-code/run.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,8 @@
22
import time
33
import torch
44
import numpy as np
5-
from train_eval import train
5+
from train_eval import train, init_network
6+
from importlib import import_module
67
import argparse
78
from utils import build_dataset, build_iterator, get_time_dif
89
import bert

pytorch-bert-code/train_eval.py

+17-1
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,23 @@
99
from transformers.optimization import AdamW
1010

1111

12-
12+
# 权重初始化,默认xavier
13+
def init_network(model, method='xavier', exclude='embedding', seed=123):
14+
for name, w in model.named_parameters():
15+
if exclude not in name:
16+
if len(w.size()) < 2:
17+
continue
18+
if 'weight' in name:
19+
if method == 'xavier':
20+
nn.init.xavier_normal_(w)
21+
elif method == 'kaiming':
22+
nn.init.kaiming_normal_(w)
23+
else:
24+
nn.init.normal_(w)
25+
elif 'bias' in name:
26+
nn.init.constant_(w, 0)
27+
else:
28+
pass
1329

1430

1531
def train(config, model, train_iter, dev_iter, test_iter):

0 commit comments

Comments
 (0)