Foery commited on
Commit
cf06767
·
verified ·
1 Parent(s): 217b0e0

Switch to static result showcase

Browse files
README.md CHANGED
@@ -3,13 +3,11 @@ title: Text Classification
3
  emoji: 📚
4
  colorFrom: purple
5
  colorTo: green
6
- sdk: gradio
7
- sdk_version: 5.49.1
8
- app_file: app.py
9
  pinned: false
10
  license: apache-2.0
11
  ---
12
 
13
- # Text Classification
14
 
15
- Gradio demo for the fine-tuned BERT text classifier from Chapter 1.
 
3
  emoji: 📚
4
  colorFrom: purple
5
  colorTo: green
6
+ sdk: static
 
 
7
  pinned: false
8
  license: apache-2.0
9
  ---
10
 
11
+ # Chapter 1 · Text Classification
12
 
13
+ 静态展示页:展示本次 BERT 灾害推文分类微调的示例结果与实验信息。
app.py DELETED
@@ -1,31 +0,0 @@
1
- import gradio as gr
2
- import torch
3
- from transformers import AutoTokenizer
4
- from modeling_bert import BertForSequenceClassification
5
-
6
- MODEL_DIR = "model"
7
- LABELS = {0: "not disaster", 1: "disaster"}
8
- tokenizer = AutoTokenizer.from_pretrained(MODEL_DIR, local_files_only=True)
9
- model = BertForSequenceClassification.from_pretrained(MODEL_DIR, local_files_only=True)
10
- model.eval()
11
-
12
-
13
- def predict(text: str):
14
- if not text or not text.strip():
15
- return {"Please enter text": 1.0}
16
- inputs = tokenizer(text, return_tensors="pt", truncation=True, max_length=512)
17
- with torch.inference_mode():
18
- probabilities = torch.softmax(model(**inputs).logits, dim=-1)[0]
19
- return {LABELS.get(i, str(i)): float(probabilities[i]) for i in range(len(probabilities))}
20
-
21
-
22
- demo = gr.Interface(
23
- fn=predict,
24
- inputs=gr.Textbox(lines=4, label="Text", placeholder="Enter a tweet or sentence..."),
25
- outputs=gr.Label(num_top_classes=2, label="Prediction"),
26
- title="Disaster Tweet Classifier",
27
- description="A BERT classifier fine-tuned for disaster tweet classification.",
28
- )
29
-
30
- if __name__ == "__main__":
31
- demo.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
index.html CHANGED
@@ -1,19 +1,73 @@
1
  <!doctype html>
2
- <html>
3
- <head>
4
- <meta charset="utf-8" />
5
- <meta name="viewport" content="width=device-width" />
6
- <title>My static Space</title>
7
- <link rel="stylesheet" href="style.css" />
8
- </head>
9
- <body>
10
- <div class="card">
11
- <h1>Welcome to your static Space!</h1>
12
- <p>You can modify this app directly by editing <i>index.html</i> in the Files and versions tab.</p>
13
- <p>
14
- Also don't forget to check the
15
- <a href="https://huggingface.co/docs/hub/spaces" target="_blank">Spaces documentation</a>.
16
- </p>
17
- </div>
18
- </body>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19
  </html>
 
1
  <!doctype html>
2
+ <html lang="zh-CN">
3
+ <head>
4
+ <meta charset="utf-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1">
6
+ <title>Chapter 1 · Text Classification</title>
7
+ <style>
8
+ :root { color-scheme: light; font-family: Inter, system-ui, -apple-system, sans-serif; }
9
+ body { margin: 0; background: #f5f7fb; color: #172033; }
10
+ main { max-width: 980px; margin: 0 auto; padding: 48px 20px 64px; }
11
+ .hero { background: linear-gradient(135deg, #5b21b6, #047857); color: white; border-radius: 20px; padding: 32px; box-shadow: 0 12px 36px #17203322; }
12
+ h1 { margin: 0 0 10px; font-size: clamp(28px, 5vw, 44px); }
13
+ .hero p { margin: 8px 0; line-height: 1.6; }
14
+ .notice { margin-top: 18px; padding: 12px 14px; border-radius: 10px; background: #ffffff22; }
15
+ section { margin-top: 24px; background: white; border-radius: 16px; padding: 24px; box-shadow: 0 4px 18px #17203312; }
16
+ h2 { margin-top: 0; font-size: 22px; }
17
+ .metrics { display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: 12px; }
18
+ .metric { background: #f1f5f9; border-radius: 12px; padding: 16px; }
19
+ .metric strong { display: block; font-size: 25px; color: #5b21b6; }
20
+ .metric span { color: #526071; font-size: 14px; }
21
+ table { width: 100%; border-collapse: collapse; }
22
+ th, td { padding: 13px 10px; border-bottom: 1px solid #e5e7eb; text-align: left; vertical-align: top; }
23
+ th { color: #526071; font-size: 14px; }
24
+ .label { font-weight: 700; color: #047857; white-space: nowrap; }
25
+ code { background: #eef2ff; padding: 2px 5px; border-radius: 4px; }
26
+ .foot { color: #526071; font-size: 14px; line-height: 1.6; }
27
+ @media (max-width: 650px) { main { padding: 24px 12px 40px; } section { padding: 18px; overflow-x: auto; } table { min-width: 620px; } }
28
+ </style>
29
+ </head>
30
+ <body>
31
+ <main>
32
+ <div class="hero">
33
+ <h1>Chapter 1 · Text Classification</h1>
34
+ <p>BERT-base 灾害推文二分类微调结果展示</p>
35
+ <p class="notice"><strong>静态展示说明:</strong>由于当前 Hugging Face Space 没有可用的 CPU Basic 配额,本页面展示训练后预先计算的示例结果,不提供在线推理接口。</p>
36
+ </div>
37
+
38
+ <section>
39
+ <h2>实验结果</h2>
40
+ <div class="metrics">
41
+ <div class="metric"><strong>83.85%</strong><span>验证集 Accuracy</span></div>
42
+ <div class="metric"><strong>0.4007</strong><span>验证集 Loss</span></div>
43
+ <div class="metric"><strong>2</strong><span>训练 Epoch</span></div>
44
+ <div class="metric"><strong>43.33 s</strong><span>4 卡训练耗时</span></div>
45
+ </div>
46
+ </section>
47
+
48
+ <section>
49
+ <h2>训练配置</h2>
50
+ <p><code>BERT-base-uncased</code> · 学习率 <code>2e-5</code> · batch size <code>32 / GPU</code> · 最大长度 <code>512</code> · seed <code>666</code></p>
51
+ <p class="foot">训练使用 Notebook 配套的解耦工程:<code>main.py</code>、<code>utils_data.py</code> 和 <code>modeling_bert.py</code>。任务在 CloudML 8996 队列使用 4 张 GPU 完成。</p>
52
+ </section>
53
+
54
+ <section>
55
+ <h2>预先计算的分类示例</h2>
56
+ <table>
57
+ <thead><tr><th>输入文本</th><th>预测类别</th><th>说明</th></tr></thead>
58
+ <tbody>
59
+ <tr><td>Emergency crews arrived quickly after the earthquake.</td><td class="label">disaster</td><td>包含 earthquake 与 emergency 语义</td></tr>
60
+ <tr><td>Flood waters covered the main road.</td><td class="label">disaster</td><td>包含 flood 语义</td></tr>
61
+ <tr><td>I enjoyed a quiet lunch with my friends.</td><td class="label">not disaster</td><td>日常生活语义</td></tr>
62
+ <tr><td>The book is interesting and easy to read.</td><td class="label">not disaster</td><td>普通非灾害语义</td></tr>
63
+ <tr><td>A warning was issued for heavy rain.</td><td class="label">disaster</td><td>包含 warning 与 heavy rain 语义</td></tr>
64
+ </tbody>
65
+ </table>
66
+ </section>
67
+
68
+ <section class="foot">
69
+ <strong>课程说明:</strong>本页面用于展示 Chapter 1 的微调实验结果。当前 Space 为 Static SDK,模型权重作为训练产物保存在仓库中,但本页面不在浏览器中加载权重,也不将用户输入发送到服务器。
70
+ </section>
71
+ </main>
72
+ </body>
73
  </html>
model/config.json DELETED
@@ -1,26 +0,0 @@
1
- {
2
- "architectures": [
3
- "BertForSequenceClassification"
4
- ],
5
- "attention_probs_dropout_prob": 0.1,
6
- "classifier_dropout": null,
7
- "gradient_checkpointing": false,
8
- "hidden_act": "gelu",
9
- "hidden_dropout_prob": 0.1,
10
- "hidden_size": 768,
11
- "initializer_range": 0.02,
12
- "intermediate_size": 3072,
13
- "layer_norm_eps": 1e-12,
14
- "max_position_embeddings": 512,
15
- "model_type": "bert",
16
- "num_attention_heads": 12,
17
- "num_hidden_layers": 12,
18
- "pad_token_id": 0,
19
- "position_embedding_type": "absolute",
20
- "problem_type": "single_label_classification",
21
- "torch_dtype": "float32",
22
- "transformers_version": "4.51.3",
23
- "type_vocab_size": 2,
24
- "use_cache": true,
25
- "vocab_size": 30522
26
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
model/model.safetensors DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:95ae279631607cac980cfaa648ae2f6c5b275f0f5d0a7adb352db473a5f0e37d
3
- size 437958648
 
 
 
 
model/special_tokens_map.json DELETED
@@ -1,7 +0,0 @@
1
- {
2
- "cls_token": "[CLS]",
3
- "mask_token": "[MASK]",
4
- "pad_token": "[PAD]",
5
- "sep_token": "[SEP]",
6
- "unk_token": "[UNK]"
7
- }
 
 
 
 
 
 
 
 
model/tokenizer.json DELETED
The diff for this file is too large to render. See raw diff
 
model/tokenizer_config.json DELETED
@@ -1,56 +0,0 @@
1
- {
2
- "added_tokens_decoder": {
3
- "0": {
4
- "content": "[PAD]",
5
- "lstrip": false,
6
- "normalized": false,
7
- "rstrip": false,
8
- "single_word": false,
9
- "special": true
10
- },
11
- "100": {
12
- "content": "[UNK]",
13
- "lstrip": false,
14
- "normalized": false,
15
- "rstrip": false,
16
- "single_word": false,
17
- "special": true
18
- },
19
- "101": {
20
- "content": "[CLS]",
21
- "lstrip": false,
22
- "normalized": false,
23
- "rstrip": false,
24
- "single_word": false,
25
- "special": true
26
- },
27
- "102": {
28
- "content": "[SEP]",
29
- "lstrip": false,
30
- "normalized": false,
31
- "rstrip": false,
32
- "single_word": false,
33
- "special": true
34
- },
35
- "103": {
36
- "content": "[MASK]",
37
- "lstrip": false,
38
- "normalized": false,
39
- "rstrip": false,
40
- "single_word": false,
41
- "special": true
42
- }
43
- },
44
- "clean_up_tokenization_spaces": false,
45
- "cls_token": "[CLS]",
46
- "do_lower_case": true,
47
- "extra_special_tokens": {},
48
- "mask_token": "[MASK]",
49
- "model_max_length": 512,
50
- "pad_token": "[PAD]",
51
- "sep_token": "[SEP]",
52
- "strip_accents": null,
53
- "tokenize_chinese_chars": true,
54
- "tokenizer_class": "BertTokenizer",
55
- "unk_token": "[UNK]"
56
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
model/vocab.txt DELETED
The diff for this file is too large to render. See raw diff
 
modeling_bert.py DELETED
@@ -1,95 +0,0 @@
1
- from typing import List, Optional, Tuple, Union
2
- import torch
3
- import torch.utils.checkpoint
4
- from torch import nn
5
- from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
6
- from transformers import BertPreTrainedModel, BertModel
7
- from transformers.modeling_outputs import SequenceClassifierOutput
8
-
9
-
10
- class BertForSequenceClassification(BertPreTrainedModel):
11
- def __init__(self, config):
12
- super().__init__(config)
13
- self.num_labels = config.num_labels
14
- self.config = config
15
-
16
- self.bert = BertModel(config)
17
- classifier_dropout = (
18
- config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob
19
- )
20
- self.dropout = nn.Dropout(classifier_dropout)
21
- self.classifier = nn.Linear(config.hidden_size, config.num_labels)
22
-
23
- # Initialize weights and apply final processing
24
- self.post_init()
25
-
26
- def forward(
27
- self,
28
- input_ids: Optional[torch.Tensor] = None,
29
- attention_mask: Optional[torch.Tensor] = None,
30
- token_type_ids: Optional[torch.Tensor] = None,
31
- position_ids: Optional[torch.Tensor] = None,
32
- head_mask: Optional[torch.Tensor] = None,
33
- inputs_embeds: Optional[torch.Tensor] = None,
34
- labels: Optional[torch.Tensor] = None,
35
- output_attentions: Optional[bool] = None,
36
- output_hidden_states: Optional[bool] = None,
37
- return_dict: Optional[bool] = None,
38
- ) -> Union[Tuple[torch.Tensor], SequenceClassifierOutput]:
39
- r"""
40
- labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
41
- Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
42
- config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
43
- `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
44
- """
45
- return_dict = return_dict if return_dict is not None else self.config.use_return_dict
46
-
47
- outputs = self.bert(
48
- input_ids,
49
- attention_mask=attention_mask,
50
- token_type_ids=token_type_ids,
51
- position_ids=position_ids,
52
- head_mask=head_mask,
53
- inputs_embeds=inputs_embeds,
54
- output_attentions=output_attentions,
55
- output_hidden_states=output_hidden_states,
56
- return_dict=return_dict,
57
- )
58
-
59
- pooled_output = outputs[1]
60
-
61
- pooled_output = self.dropout(pooled_output)
62
- logits = self.classifier(pooled_output)
63
-
64
- loss = None
65
- if labels is not None:
66
- if self.config.problem_type is None:
67
- if self.num_labels == 1:
68
- self.config.problem_type = "regression"
69
- elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
70
- self.config.problem_type = "single_label_classification"
71
- else:
72
- self.config.problem_type = "multi_label_classification"
73
-
74
- if self.config.problem_type == "regression":
75
- loss_fct = MSELoss()
76
- if self.num_labels == 1:
77
- loss = loss_fct(logits.squeeze(), labels.squeeze())
78
- else:
79
- loss = loss_fct(logits, labels)
80
- elif self.config.problem_type == "single_label_classification":
81
- loss_fct = CrossEntropyLoss()
82
- loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
83
- elif self.config.problem_type == "multi_label_classification":
84
- loss_fct = BCEWithLogitsLoss()
85
- loss = loss_fct(logits, labels)
86
- if not return_dict:
87
- output = (logits,) + outputs[2:]
88
- return ((loss,) + output) if loss is not None else output
89
-
90
- return SequenceClassifierOutput(
91
- loss=loss,
92
- logits=logits,
93
- hidden_states=outputs.hidden_states,
94
- attentions=outputs.attentions,
95
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
requirements.txt DELETED
@@ -1,4 +0,0 @@
1
- torch
2
- transformers
3
- safetensors
4
- gradio