File size: 2,718 Bytes
f70bfaf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
import torch
from torch import nn
import transformers
from transformers import DistilBertForSequenceClassification, DistilBertTokenizer

def create_distilbert_model(num_classes: int = 2, seed: int = 42):
    """

    Creates a DistilBERT model for sentiment analysis with a customized classification head.



    Args:

        num_classes (int): Number of output classes.

        seed (int): Random seed for reproducibility.



    Returns:

        model (torch.nn.Module): DistilBERT model with a custom classification head.

        tokenizer (transformers.PreTrainedTokenizer): Tokenizer for text preprocessing.

    """
    # Set random seed for reproducibility
    torch.manual_seed(seed)

    # Load pre-trained DistilBERT model
    model = DistilBertForSequenceClassification.from_pretrained(
        "distilbert-base-uncased",
        num_labels=num_classes  # Output layer matches the number of classes
    )

    # Freeze base model parameters (optional)
    for param in model.distilbert.parameters():
        param.requires_grad = False

    # Customize the classification head
    model.classifier = nn.Sequential(
        nn.Dropout(p=0.5),           # Add dropout to prevent overfitting
        nn.Linear(768, 256),         # Add a hidden layer (768 -> 256)
        nn.ReLU(),                   # Non-linear activation function
        nn.Dropout(p=0.3),           # Add another dropout layer
        nn.Linear(256, num_classes)  # Output layer (256 -> num_classes)
    )

    # model.classifier = nn.Sequential(
    #     nn.Dropout(p=0.6),
    #     nn.Linear(768, 256),
    #     nn.ReLU(),
    #     nn.Dropout(p=0.4),
    #     nn.Linear(256, 2)
    # )

    # Load DistilBERT tokenizer
    tokenizer = DistilBertTokenizer.from_pretrained("distilbert-base-uncased")

    return model, tokenizer

def tokenize_texts_and_labels(tokenizer, texts, labels=None, max_length=128):
    """

    將文本數據進行分詞,並處理標籤(如果提供)。

    Args:

        tokenizer: 分詞器,用於將文本轉換為模型輸入格式。

        texts (list[str]): 文本數據列表。

        labels (list[int], optional): 標籤列表,可選。

        max_length (int): 最大文本長度。

    Returns:

        dict: 包含分詞結果的字典,包括 input_ids、attention_mask 和 labels(如果提供)。

    """
    encodings = tokenizer(
        list(texts),
        padding="max_length",
        truncation=True,
        max_length=max_length,
        return_tensors="pt"
    )
    if labels is not None:
        encodings["labels"] = torch.tensor(labels)  # 將標籤轉為 PyTorch 張量
    return encodings