zhouxiaoxi commited on
Commit
bf33743
·
verified ·
1 Parent(s): b2901f6

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +21 -1
app.py CHANGED
@@ -1,6 +1,7 @@
1
  import gradio as gr
2
  import torch
3
- from transformers import BertTokenizer
 
4
 
5
  device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
6
  names = ['负向', '正向']
@@ -8,6 +9,25 @@ names = ['负向', '正向']
8
  # 分词器
9
  tokenizer = BertTokenizer.from_pretrained("bert-base-chinese")
10
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11
  # 加载预训练模型
12
  bert_model = BertModel.from_pretrained("ckiplab/bert-base-chinese").to(device)
13
  model = Model(bert_model).to(device)
 
1
  import gradio as gr
2
  import torch
3
+ import torch.nn as nn
4
+ from transformers import BertTokenizer, BertModel
5
 
6
  device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
7
  names = ['负向', '正向']
 
9
  # 分词器
10
  tokenizer = BertTokenizer.from_pretrained("bert-base-chinese")
11
 
12
+ class Model(nn.Module):
13
+ def __init__(self, bert_model):
14
+ super().__init__()
15
+ self.bert = bert_model
16
+ # 全连接,模型输入为768,分类为2
17
+ self.fc = nn.Linear(768, 2)
18
+
19
+ #
20
+ def forward(self, input_ids, attention_mask, token_type_ids):
21
+ # 使用预训练模型提取特征, 上游任务不参与训练,锁定权重
22
+ with torch.no_grad():
23
+ # Correctly call the BertModel instance stored in self.bert
24
+ output = self.bert(input_ids, attention_mask, token_type_ids)
25
+ # 下游参与训练,二分类任务,获取最新后的状态
26
+ output = self.fc(output.last_hidden_state[:, 0])
27
+ # softmax激活函数,NV结构,获取特征值dim维度为1
28
+ output = output.softmax(dim=1)
29
+ return output
30
+
31
  # 加载预训练模型
32
  bert_model = BertModel.from_pretrained("ckiplab/bert-base-chinese").to(device)
33
  model = Model(bert_model).to(device)