自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

通過PyTorch來創(chuàng)建一個文本分類的Bert模型

開發(fā) 后端
在本文中,介紹了一種稱為BERT(帶轉(zhuǎn)換器Transformers的雙向編碼Encoder 器表示)的語言模型,該模型在問答、自然語言推理、分類和通用語言理解評估或 (GLUE)等任務(wù)中取得了最先進(jìn)的性能.

[[420285]]

2018 年,谷歌發(fā)表了一篇題為《Pre-training of deep bidirectional Transformers for Language Understanding》的論文。

在本文中,介紹了一種稱為BERT(帶轉(zhuǎn)換器Transformers的雙向編碼Encoder 器表示)的語言模型,該模型在問答、自然語言推理、分類和通用語言理解評估或 (GLUE)等任務(wù)中取得了最先進(jìn)的性能.

BERT全稱為Bidirectional Encoder Representation from Transformers[1],是一種用于語言表征的預(yù)訓(xùn)練模型。

它基于谷歌2017年發(fā)布的Transformer架構(gòu),通常的Transformer使用一組編碼器和解碼器網(wǎng)絡(luò),而BERT只需要一個額外的輸出層,對預(yù)訓(xùn)練進(jìn)行fine-tune,就可以滿足各種任務(wù),根本沒有必要針對特定任務(wù)對模型進(jìn)行修改。

BERT將多個Transformer編碼器堆疊在一起。Transformer基于著名的多頭注意力(Multi-head Attention)模塊,該模塊在視覺和語言任務(wù)方面都取得了巨大成功。

在本文中,我們將使用 PyTorch來創(chuàng)建一個文本分類的Bert模型。

筆者介今天紹一個python庫 --- simpletransformers,可以很好的解決高級預(yù)訓(xùn)練語言模型使用困難的問題。

simpletransformers使得高級預(yù)訓(xùn)練模型(BERT、RoBERTa、XLNet、XLM、DistilBERT、ALBERT、CamemBERT、XLM-RoBERTa、FlauBERT)的訓(xùn)練、評估和預(yù)測變得簡單,每條只需3行即可初始化模型。

數(shù)據(jù)集來源:https://www.kaggle.com/jrobischon/wikipedia-movie-plots

該數(shù)據(jù)集包含對來自世界各地的 34,886 部電影的描述。列描述如下:

  • 發(fā)行年份:電影發(fā)行的年份
  • 標(biāo)題:電影標(biāo)題
  • 起源:電影的起源(即美國、寶萊塢、泰米爾等)
  • 劇情:主要演員
  • 類型:電影類型
  • 維基頁面- 從中抓取情節(jié)描述的維基百科頁面的 URL
  • 情節(jié):電影情節(jié)的長篇描述
  1. import numpy as np 
  2. import pandas as pd 
  3. import os, json, gc, re, random 
  4. from tqdm.notebook import tqdm 
  5. import torch, transformers, tokenizers 
  6. movies_df = pd.read_csv("wiki_movie_plots_deduped.csv"
  7. from sklearn.preprocessing import LabelEncoder 
  8.  
  9. movies_df = movies_df[(movies_df["Origin/Ethnicity"]=="American") | (movies_df["Origin/Ethnicity"]=="British")] 
  10. movies_df = movies_df[["Plot""Genre"]] 
  11. drop_indices = movies_df[movies_df["Genre"] == "unknown" ].index 
  12. movies_df.drop(drop_indices, inplace=True
  13.  
  14. # Combine genres: 1) "sci-fi" with "science fiction" &  2) "romantic comedy" with "romance" 
  15. movies_df["Genre"].replace({"sci-fi""science fiction""romantic comedy""romance"}, inplace=True
  16.  
  17. # 根據(jù)頻率選擇電影類型 
  18. shortlisted_genres = movies_df["Genre"].value_counts().reset_index(name="count").query("count > 200")["index"].tolist() 
  19. movies_df = movies_df[movies_df["Genre"].isin(shortlisted_genres)].reset_index(drop=True
  20.  
  21. # Shuffle  
  22. movies_df = movies_df.sample(frac=1).reset_index(drop=True
  23.  
  24. #從不同類型中抽取大致相同數(shù)量的電影情節(jié)樣本(以減少階級不平衡問題) 
  25. movies_df = movies_df.groupby("Genre").head(400).reset_index(drop=True
  26. label_encoder = LabelEncoder() 
  27. movies_df["genre_encoded"] = label_encoder.fit_transform(movies_df["Genre"].tolist()) 
  28. movies_df = movies_df[["Plot""Genre""genre_encoded"]] 
  29. movies_df 

使用 torch 加載 BERT 模型,最簡單的方法是使用 Simple Transformers 庫,以便只需 3 行代碼即可初始化、在給定數(shù)據(jù)集上訓(xùn)練和在給定數(shù)據(jù)集上評估 Transformer 模型。

  1. from simpletransformers.classification import ClassificationModel 
  2.  
  3. # 模型參數(shù) 
  4. model_args = { 
  5.     "reprocess_input_data"True
  6.     "overwrite_output_dir"True
  7.     "save_model_every_epoch"False
  8.     "save_eval_checkpoints"False
  9.     "max_seq_length": 512, 
  10.     "train_batch_size": 16, 
  11.     "num_train_epochs": 4, 
  12.  
  13. Create a ClassificationModel 
  14. model = ClassificationModel('bert''bert-base-cased', num_labels=len(shortlisted_genres), args=model_args) 

訓(xùn)練模型

  1. train_df, eval_df = train_test_split(movies_df, test_size=0.2, stratify=movies_df["Genre"], random_state=42) 
  2.  
  3. # Train the model 
  4. model.train_model(train_df[["Plot""genre_encoded"]]) 
  5.  
  6. # Evaluate the model 
  7. result, model_outputs, wrong_predictions = model.eval_model(eval_df[["Plot""genre_encoded"]]) 
  8. print(result) 
  9.  
  10. {'mcc': 0.5299659404649717, 'eval_loss': 1.4970421879083518} 
  11. CPU times: user 19min 1s, sys: 4.95 s, total: 19min 6s 
  12. Wall time: 20min 14s 

關(guān)于simpletransformers的官方文檔:https://simpletransformers.ai/docs

Github鏈接:https://github.com/ThilinaRajapakse/simpletransformers

 

責(zé)任編輯:姜華 來源: Python之王
相關(guān)推薦

2024-10-16 10:41:36

2020-09-25 09:58:37

谷歌Android開發(fā)者

2021-03-06 07:00:00

awk文本分析工具Linux

2022-10-09 08:00:00

機(jī)器學(xué)習(xí)文本分類算法

2018-07-04 15:17:07

CNNNLP模型

2020-06-04 12:55:44

PyTorch分類器神經(jīng)網(wǎng)絡(luò)

2020-09-22 15:17:59

谷歌Android技術(shù)

2018-12-17 09:10:52

機(jī)器學(xué)習(xí)TensorFlow容器

2017-08-04 14:23:04

機(jī)器學(xué)習(xí)神經(jīng)網(wǎng)絡(luò)TensorFlow

2020-03-23 08:00:00

開源數(shù)據(jù)集文本分類

2024-10-30 16:59:57

Python機(jī)器學(xué)習(xí)

2017-06-20 11:00:13

大數(shù)據(jù)自然語言文本分類器

2010-09-25 15:46:58

帳戶管理舊賬戶

2024-12-20 16:00:00

Python文本分類聚類

2023-12-31 16:35:31

Pytorch函數(shù)深度學(xué)習(xí)

2023-02-27 09:31:00

streamlitst.sidebar菜單

2025-01-23 16:13:35

RAG

2023-11-28 09:00:00

機(jī)器學(xué)習(xí)少樣本學(xué)習(xí)SetFit

2017-08-25 14:23:44

TensorFlow神經(jīng)網(wǎng)絡(luò)文本分類
點贊
收藏

51CTO技術(shù)棧公眾號