优秀的python库_一个优秀Python库,轻松吟诗作对写文章!
公眾號:深度學(xué)習(xí)視覺
前言
該工具追求著這樣的一個目標(biāo),幾行代碼調(diào)用最先進(jìn)的模型,加載訓(xùn)練好的模型參數(shù),來完成自然語言項目,比如機器翻譯、文本摘要、問答系統(tǒng)等。Transformers 同時支持 PyTorch 和TensorFlow2.0,用戶可以將這些工具放在一起使用。
支持模型
transformers目前提供以下NLU / NLG體系結(jié)構(gòu):BERT、GPT、GPT-2、Transformer-XL、XLNet、XLM、RoBERTa、DistilBERT、CTRL、CamemBERT、ALBERT、T5、XLM-RoBERTa、MMBT、FlauBERT、其他社區(qū)的模型
安裝PyTorch-Transformers
pip install pytorch-transformers
使用GPT-2預(yù)測下一個單詞
GPT-2是一種于基于transformer的生成語言模型,其語言生成能力優(yōu)秀到被討論禁止開源。該模型是在40GB的文本下進(jìn)行無監(jiān)督訓(xùn)練。
# 導(dǎo)入必要的庫
import torch
from pytorch_transformers import GPT2Tokenizer, GPT2LMHeadModel
# 加載預(yù)訓(xùn)練模型tokenizer (vocabulary)
tokenizer = GPT2Tokenizer.from_pretrained('gpt2')
# 對文本輸入進(jìn)行編碼
text = "What is the fastest car in the"
indexed_tokens = tokenizer.encode(text)
# 在PyTorch張量中轉(zhuǎn)換indexed_tokens
tokens_tensor = torch.tensor([indexed_tokens])
# 加載預(yù)訓(xùn)練模型 (weights)
model = GPT2LMHeadModel.from_pretrained('gpt2')
#將模型設(shè)置為evaluation模式,關(guān)閉DropOut模塊
model.eval()
# 如果你有GPU,把所有東西都放在cuda上
tokens_tensor = tokens_tensor.to('cuda')
model.to('cuda')
# 預(yù)測所有的tokens
with torch.no_grad():
outputs = model(tokens_tensor)
predictions = outputs[0]
# 得到預(yù)測的單詞
predicted_index = torch.argmax(predictions[0, -1, :]).item()
predicted_text = tokenizer.decode(indexed_tokens + [predicted_index])
# 打印預(yù)測單詞
print(predicted_text)
預(yù)測長文本
!git clone https://github.com/huggingface/pytorch-transformers.git
# 啟動模型
!python pytorch-transformers/examples/run_generation.py \
--model_type=gpt2 \
--length=100 \
--model_name_or_path=gpt2 \
輸入(本來是英文)
在一個令人震驚的發(fā)現(xiàn)中,科學(xué)家發(fā)現(xiàn)了一群獨角獸,它們生活在安第斯山脈一個偏遠(yuǎn)的,以前未被開發(fā)的山谷中。對于研究人員而言,更令人驚訝的是,獨角獸會說完美的英語。
輸出(本來是英文)
獨角獸似乎和普通人一樣了解彼此。該研究于5月6日發(fā)表在《科學(xué)轉(zhuǎn)化醫(yī)學(xué)》上。此外,研究人員發(fā)現(xiàn),百分之五的獨角獸彼此之間具有很好的識別性。研究團(tuán)隊認(rèn)為,這可能會轉(zhuǎn)化為未來,使人類能夠與稱為超級獨角獸的人進(jìn)行更清晰的交流。如果我們要朝著那個未來前進(jìn),我們至少必須做到
除了GPT-2以外,還有諸如XLNet,一個在包括問答、自然語言推理、情感分析和文檔排序等18項任務(wù)上取得了最先進(jìn)結(jié)果的模型。
!python pytorch-transformers/examples/run_generation.py \
--model_type=xlnet \
--length=50 \
--model_name_or_path=xlnet-base-cased \
還有能夠?qū)W習(xí)長期依賴的Transformer-XL,比標(biāo)準(zhǔn)Transformer快1800倍。
!python pytorch-transformers/examples/run_generation.py \
--model_type=transfo-xl \
--length=100 \
--model_name_or_path=transfo-xl-wt103 \
Transformers API調(diào)用示例代碼(收藏)
import torch
from transformers import *
# transformer有一個統(tǒng)一的API
# 有10個Transformer結(jié)構(gòu)和30個預(yù)訓(xùn)練權(quán)重模型。
#模型|分詞|預(yù)訓(xùn)練權(quán)重
MODELS = [(BertModel, BertTokenizer, 'bert-base-uncased'),
(OpenAIGPTModel, OpenAIGPTTokenizer, 'openai-gpt'),
(GPT2Model, GPT2Tokenizer, 'gpt2'),
(CTRLModel, CTRLTokenizer, 'ctrl'),
(TransfoXLModel, TransfoXLTokenizer, 'transfo-xl-wt103'),
(XLNetModel, XLNetTokenizer, 'xlnet-base-cased'),
(XLMModel, XLMTokenizer, 'xlm-mlm-enfr-1024'),
(DistilBertModel, DistilBertTokenizer, 'distilbert-base-cased'),
(RobertaModel, RobertaTokenizer, 'roberta-base'),
(XLMRobertaModel, XLMRobertaTokenizer, 'xlm-roberta-base'),
]
# 要使用TensorFlow 2.0版本的模型,只需在類名前面加上“TF”,例如。“TFRobertaModel”是TF2.0版本的PyTorch模型“RobertaModel”
# 讓我們用每個模型將一些文本編碼成隱藏狀態(tài)序列:
for model_class, tokenizer_class, pretrained_weights in MODELS:
# 加載pretrained模型/分詞器
tokenizer = tokenizer_class.from_pretrained(pretrained_weights)
model = model_class.from_pretrained(pretrained_weights)
# 編碼文本
input_ids = torch.tensor([tokenizer.encode("Here is some text to encode", add_special_tokens=True)]) # 添加特殊標(biāo)記
with torch.no_grad():
last_hidden_states = model(input_ids)[0] # 模型輸出是元組
# 每個架構(gòu)都提供了幾個類,用于對下游任務(wù)進(jìn)行調(diào)優(yōu),例如。
BERT_MODEL_CLASSES = [BertModel, BertForPreTraining, BertForMaskedLM, BertForNextSentencePrediction,
BertForSequenceClassification, BertForTokenClassification, BertForQuestionAnswering]
# 體系結(jié)構(gòu)的所有類都可以從該體系結(jié)構(gòu)的預(yù)訓(xùn)練權(quán)重開始
#注意,為微調(diào)添加的額外權(quán)重只在需要接受下游任務(wù)的訓(xùn)練時初始化
pretrained_weights = 'bert-base-uncased'
tokenizer = BertTokenizer.from_pretrained(pretrained_weights)
for model_class in BERT_MODEL_CLASSES:
# 載入模型/分詞器
model = model_class.from_pretrained(pretrained_weights)
# 模型可以在每一層返回隱藏狀態(tài)和帶有注意力機制的權(quán)值
model = model_class.from_pretrained(pretrained_weights,
output_hidden_states=True,
output_attentions=True)
input_ids = torch.tensor([tokenizer.encode("Let's see all hidden-states and attentions on this text")])
all_hidden_states, all_attentions = model(input_ids)[-2:]
#模型與Torchscript兼容
model = model_class.from_pretrained(pretrained_weights, torchscript=True)
traced_model = torch.jit.trace(model, (input_ids,))
# 模型和分詞的簡單序列化
model.save_pretrained('./directory/to/save/') # 保存
model = model_class.from_pretrained('./directory/to/save/') # 重載
tokenizer.save_pretrained('./directory/to/save/') # 保存
tokenizer = BertTokenizer.from_pretrained('./directory/to/save/') # 重載
import tensorflow as tf
import tensorflow_datasets
from transformers import *
# 從預(yù)訓(xùn)練模型/詞匯表中加載數(shù)據(jù)集、分詞器、模型
tokenizer = BertTokenizer.from_pretrained('bert-base-cased')
model = TFBertForSequenceClassification.from_pretrained('bert-base-cased')
data = tensorflow_datasets.load('glue/mrpc')
# 準(zhǔn)備數(shù)據(jù)集作為tf.data.Dataset的實例
train_dataset = glue_convert_examples_to_features(data['train'], tokenizer, max_length=128, task='mrpc')
valid_dataset = glue_convert_examples_to_features(data['validation'], tokenizer, max_length=128, task='mrpc')
train_dataset = train_dataset.shuffle(100).batch(32).repeat(2)
valid_dataset = valid_dataset.batch(64)
# 準(zhǔn)備訓(xùn)練:編寫tf.keras模型與優(yōu)化,損失和學(xué)習(xí)率調(diào)度
optimizer = tf.keras.optimizers.Adam(learning_rate=3e-5, epsilon=1e-08, clipnorm=1.0)
loss = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True)
metric = tf.keras.metrics.SparseCategoricalAccuracy('accuracy')
model.compile(optimizer=optimizer, loss=loss, metrics=[metric])
# 用tf.keras.Model.fit進(jìn)行測試和評估
history = model.fit(train_dataset, epochs=2, steps_per_epoch=115,
validation_data=valid_dataset, validation_steps=7)
# 在PyTorch中加載TensorFlow模型進(jìn)行檢查
model.save_pretrained('./save/')
pytorch_model = BertForSequenceClassification.from_pretrained('./save/', from_tf=True)
#讓我們看看我們的模型是否學(xué)會了這個任務(wù)
sentence_0 = "This research was consistent with his findings."
sentence_1 = "His findings were compatible with this research."
sentence_2 = "His findings were not compatible with this research."
inputs_1 = tokenizer.encode_plus(sentence_0, sentence_1, add_special_tokens=True, return_tensors='pt')
inputs_2 = tokenizer.encode_plus(sentence_0, sentence_2, add_special_tokens=True, return_tensors='pt')
pred_1 = pytorch_model(inputs_1['input_ids'], token_type_ids=inputs_1['token_type_ids'])[0].argmax().item()
pred_2 = pytorch_model(inputs_2['input_ids'], token_type_ids=inputs_2['token_type_ids'])[0].argmax().item()
print("sentence_1 is", "a paraphrase" if pred_1 else "not a paraphrase", "of sentence_0")
print("sentence_2 is", "a paraphrase" if pred_2 else "not a paraphrase", "of sentence_0")
總結(jié)
以上是生活随笔為你收集整理的优秀的python库_一个优秀Python库,轻松吟诗作对写文章!的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 不求人,手把手教你学会微信WIFI!
- 下一篇: python 下载qq群文件_pytho