Views
No views yet
1from transformers import pipeline
2
3label2id = {
4 'Task_Solution': 0,
5 'Creative_Generation': 1,
6 'Knowledge_Explanation': 2,
7 'Analytical_Reasoning': 3,
8 'Information_Extraction': 4,
9 'Step_by_Step_Calculation': 5,
10 'Role_Play_Response': 6,
11 'Opinion_Perspective': 7
12}
13
14def preprocess_text_classification(examples: dict[str, list]) -> BatchEncoding:
15 """バッチ処理用に修正"""
16 encoded_examples = tokenizer(
17 examples["questions"], # バッチ処理なのでリストで渡される
18 max_length=512,
19 padding=True,
20 truncation=True,
21 return_tensors=None # バッチ処理時はNoneを指定
22 )
23
24 # ラベルをバッチで数値に変換
25 encoded_examples["labels"] = [label2id[label] for label in examples["labels"]]
26 return encoded_examples
27
28# 使用するデータセット
29test_data = test_data.to_pandas()
30test_data["labels"] = test_data["labels"].apply(lambda x: label2id[x])
31test_data
32
33model_name = "hiroki-rad/bert-base-classification-ft"
34classify_pipe = pipeline(model=model_name, device="cuda:0")
35
36class_label = dataset["labels"].unique()
37label2id = {label: id for id, label in enumerate(class_label)}
38id2label = {id: label for id, label in enumerate(class_label)}
39
40results: list[dict[str, float | str]] = []
41for i, example in tqdm(enumerate(test_data.itertuples())):
42 # モデルの予測結果を取得
43 model_prediction = classify_pipe(example.questions)[0]
44 # 正解のラベルIDをラベル名に変換
45 true_label = id2label[example.labels]
46 results.append(
47 {
48 "example_id": i,
49 "pred_prob": model_prediction["score"],
50 "pred_label": model_prediction["label"],
51 "true_label": true_label,
52 }
53 )