Sequence Classification
1.情感分析
from transformers
import pipeline
nlp
= pipeline
("sentiment-analysis")
result
= nlp
("I hate you")[0]
result
= nlp
("I love you")[0]
2.相似度分析
from transformers
import AutoTokenizer
, AutoModelForSequenceClassification
import torch
tokenizer
= AutoTokenizer
.from_pretrained
("bert-base-cased-finetuned-mrpc")
model
= AutoModelForSequenceClassification
.from_pretrained
("bert-base-cased-finetuned-mrpc")
classes
= ["not paraphrase", "is paraphrase"]
sequence_0
= "The company HuggingFace is based in New York City"
sequence_1
= "Apples are especially bad for your health"
sequence_2
= "HuggingFace's headquarters are situated in Manhattan"
paraphrase
= tokenizer
(sequence_0
, sequence_2
, return_tensors
="pt")
not_paraphrase
= tokenizer
(sequence_0
, sequence_1
, return_tensors
="pt")
paraphrase_classification
= model
(**paraphrase
)
not_paraphrase_classification
= model
(**not_paraphrase
)
paraphrase_results
= torch
.softmax
(paraphrase_classification
[0], dim
=1).tolist
()[0]
not_paraphrase_results
= torch
.softmax
(not_paraphrase_classification
[0], dim
=1).tolist
()[0]
for i
in range(len(classes
)):
print(f
"{classes[i]}: {int(round(paraphrase_results[i] * 100))}%")
for i
in range(len(classes
)):
print(f
"{classes[i]}: {int(round(not_paraphrase_results[i] * 100))}%")
Question Answering
from transformers
import AutoTokenizer
, AutoModelForQuestionAnswering
import torch
tokenizer
= AutoTokenizer
.from_pretrained
("bert-large-uncased-whole-word-masking-finetuned-squad")
model
= AutoModelForQuestionAnswering
.from_pretrained
("bert-large-uncased-whole-word-masking-finetuned-squad")
text
= r
"🤗 Transformers (formerly known as pytorch-transformers and pytorch-pretrained-bert) provides general-purposearchitectures (BERT, GPT-2, RoBERTa, XLM, DistilBert, XLNet…) for Natural Language Understanding (NLU) and NaturalLanguage Generation (NLG) with over 32+ pretrained models in 100+ languages and deep interoperability betweenTensorFlow 2.0 and PyTorch."
questions
= [r
"How many pretrained models are available in 🤗 Transformers?",r
"What does 🤗 Transformers provide?",r
"🤗 Transformers provides interoperability between which frameworks?"]
for question
in questions
:
inputs
= tokenizer
(question
, text
, add_special_tokens
=True, return_tensors
="pt")
input_ids
= inputs
["input_ids"].tolist
()[0]
text_tokens
= tokenizer
.convert_ids_to_tokens
(input_ids
)
answer_start_scores
, answer_end_scores
= model
(**inputs
)
answer_start
= torch
.argmax
(
answer_start_scores
)
answer_end
= torch
.argmax
(answer_end_scores
) + 1
answer
= tokenizer
.convert_tokens_to_string
(tokenizer
.convert_ids_to_tokens
(input_ids
[answer_start
:answer_end
]))
print(f
"Question: {question}")
print(f
"Answer: {answer}")
Language Modeling
Masked Language Modeling
from transformers
import pipeline
nlp
= pipeline
("fill-mask")
from pprint
import pprint
pprint
(nlp
(f
"HuggingFace is creating a {nlp.tokenizer.mask_token} that the community uses to solve NLP tasks."))
Causal Language Modeling
from transformers
import AutoModelWithLMHead
, AutoTokenizer
, top_k_top_p_filtering
import torch
from torch
.nn
import functional
as F
tokenizer
= AutoTokenizer
.from_pretrained
("gpt2")
model
= AutoModelWithLMHead
.from_pretrained
("gpt2")
sequence
= f
"Hugging Face is based in DUMBO, New York City, and "
input_ids
= tokenizer
.encode
(sequence
, return_tensors
="pt")
next_token_logits
= model
(input_ids
).logits
[:, -1, :]
filtered_next_token_logits
= top_k_top_p_filtering
(next_token_logits
, top_k
=50, top_p
=1.0)
probs
= F
.softmax
(filtered_next_token_logits
, dim
=-1)
next_token
= torch
.multinomial
(probs
, num_samples
=1)
generated
= torch
.cat
([input_ids
, next_token
], dim
=-1)
resulting_string
= tokenizer
.decode
(generated
.tolist
()[0])
print(resulting_string
)
Hugging Face
is based
in DUMBO
, New York City
, and has
Text Generation
from transformers
import pipeline
text_generator
= pipeline
("text-generation")
print(text_generator
("As far as I am concerned, I will", max_length
=50, do_sample
=False))
[{'generated_text': 'As far as I am concerned, I will be the first to admit that I am not a fan of the idea of a "free market." I think that the idea of a free market is a bit of a stretch. I think that the idea'}]
Named Entity Recognition
符号描述
OOutside of a named entityB-MISBeginning of a miscellaneous entity right after another miscellaneous entityI-MISMiscellaneous entityB-PERBeginning of a person’s name right after another person’s nameI-PERPerson’s nameB-ORGBeginning of an organisation right after another organisationI-ORGOrganisationB-LOCBeginning of a location right after another locationI-LOCLocation
from transformers
import pipeline
nlp
= pipeline
("ner")
sequence
= "Hugging Face Inc. is a company based in New York City. Its headquarters are in DUMBO, therefore very"
... "close to the Manhattan Bridge which is visible from the window."
print(nlp
(sequence
))
[
{'word': 'Hu', 'score': 0.9995632767677307, 'entity': 'I-ORG'},
{'word': '##gging', 'score': 0.9915938973426819, 'entity': 'I-ORG'},
{'word': 'Face', 'score': 0.9982671737670898, 'entity': 'I-ORG'},
{'word': 'Inc', 'score': 0.9994403719902039, 'entity': 'I-ORG'},
{'word': 'New', 'score': 0.9994346499443054, 'entity': 'I-LOC'},
{'word': 'York', 'score': 0.9993270635604858, 'entity': 'I-LOC'},
{'word': 'City', 'score': 0.9993864893913269, 'entity': 'I-LOC'},
{'word': 'D', 'score': 0.9825621843338013, 'entity': 'I-LOC'},
{'word': '##UM', 'score': 0.936983048915863, 'entity': 'I-LOC'},
{'word': '##BO', 'score': 0.8987102508544922, 'entity': 'I-LOC'},
{'word': 'Manhattan', 'score': 0.9758241176605225, 'entity': 'I-LOC'},
{'word': 'Bridge', 'score': 0.990249514579773, 'entity': 'I-LOC'}
]
Summarization
from transformers
import pipeline
summarizer
= pipeline
("summarization")
ARTICLE
= """ New York (CNN)When Liana Barrientos was 23 years old, she got married in Westchester County, New York.
A year later, she got married again in Westchester County, but to a different man and without divorcing her first husband.
Only 18 days after that marriage, she got hitched yet again. Then, Barrientos declared "I do" five more times, sometimes only within two weeks of each other.
In 2010, she married once more, this time in the Bronx. In an application for a marriage license, she stated it was her "first and only" marriage.
Barrientos, now 39, is facing two criminal counts of "offering a false instrument for filing in the first degree," referring to her false statements on the
2010 marriage license application, according to court documents.
Prosecutors said the marriages were part of an immigration scam.
On Friday, she pleaded not guilty at State Supreme Court in the Bronx, according to her attorney, Christopher Wright, who declined to comment further.
After leaving court, Barrientos was arrested and charged with theft of service and criminal trespass for allegedly sneaking into the New York subway through an emergency exit, said Detective
Annette Markowski, a police spokeswoman. In total, Barrientos has been married 10 times, with nine of her marriages occurring between 1999 and 2002.
All occurred either in Westchester County, Long Island, New Jersey or the Bronx. She is believed to still be married to four men, and at one time, she was married to eight men at once, prosecutors say.
Prosecutors said the immigration scam involved some of her husbands, who filed for permanent residence status shortly after the marriages.
Any divorces happened only after such filings were approved. It was unclear whether any of the men will be prosecuted.
The case was referred to the Bronx District Attorney\'s Office by Immigration and Customs Enforcement and the Department of Homeland Security\'s
Investigation Division. Seven of the men are from so-called "red-flagged" countries, including Egypt, Turkey, Georgia, Pakistan and Mali.
Her eighth husband, Rashid Rajput, was deported in 2006 to his native Pakistan after an investigation by the Joint Terrorism Task Force.
If convicted, Barrientos faces up to four years in prison. Her next court appearance is scheduled for May 18.
"""
print(summarizer
(ARTICLE
, max_length
=130, min_length
=30, do_sample
=False))
[{'summary_text': 'Liana Barrientos, 39, is charged with two counts of "offering a false instrument for filing in the first degree" In total, she has been married 10 times, with nine of her marriages occurring between 1999 and 2002. She is believed to still be married to four men.'}]
Translation
from transformers
import pipeline
translator
= pipeline
("translation_en_to_de")
print(translator
("Hugging Face is a technology company based in New York and Paris", max_length
=40))
[{'translation_text': 'Hugging Face ist ein Technologieunternehmen mit Sitz in New York und Paris.'}]