-
Notifications
You must be signed in to change notification settings - Fork 790
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
2 changed files
with
337 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,335 @@ | ||
# Transformerlar, ne yapabilirler?[[transformers-what-can-they-do]] | ||
|
||
<CourseFloatingBanner chapter={1} | ||
classNames="absolute z-10 right-0 top-0" | ||
notebooks={[ | ||
{label: "Google Colab", value: "https://colab.research.google.com/github/huggingface/notebooks/blob/master/course/en/chapter1/section3.ipynb"}, | ||
{label: "Aws Studio", value: "https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/master/course/en/chapter1/section3.ipynb"}, | ||
]} /> | ||
|
||
Bu bölümde Transformer modellerinin ne yapabildiğini ve 🤗 Transformers kütüphanesinden ilk özelliğimiz `pipeline()` fonksiyonunu öğreneceğiz. | ||
|
||
<Tip> | ||
👀 Sağ üstteki <em>Open in Colab</em> tuşunu görüyor musun? Ona tıklarsan bu bölümdeki bütün kodların yazılı olduğu bir colab sayfası açılır. Bu tuş kod örneği olan bütün sayfalarda olacak. | ||
|
||
Eğer kodları bilgisayarında çalıştırmak istiyorsan, <a href="/course/chapter0">kurulum</a> bölümüne bakmanı öneririz. | ||
</Tip> | ||
|
||
## Transformerlar her yerde![[transformers-are-everywhere]] | ||
|
||
Transformer modelleri her türlü NLP görevleri için kullanılır. (Önceki bölümde bahsettiğimiz gibi.) İşte HuggingFace ve Transformer kütüphanesini kullanan bazı şirketler ve organizasyonlar. Ayrıca modellerini paylaşarak topluluğa katkı sağlıyorlar! | ||
|
||
<img src="https://huggingface.co/datasets/huggingface-course/documentation-images/resolve/main/en/chapter1/companies.PNG" alt="Companies using Hugging Face" width="100%"> | ||
|
||
[🤗 Transformers kütüphanesi](https://github.com/huggingface/transformers) bu paylaşılan modelleri yaratmak ve kullanmak için özellikler sunuyor. [Model Hub](https://huggingface.co/models) ise herkesin indirip kullanabileceği binlerce pretrained modeli barındırıyor. Ayrıca Hub'a kendi modellerinizi de yükleyebilirsiniz! | ||
|
||
<Tip> | ||
⚠️ Hugging Face Hub sadece Transformer modellerden ibaret değil. Herkes, istediği her türlü modeli ve verisetini paylaşabilir! <a href="https://huggingface.co/join">Bir huggingface.co hesabı oluşturarak</a> bütün özelliklerden faydalanabilirsiniz! | ||
</Tip> | ||
|
||
Hadi Transformer modellerin nasıl çalıştığını görmeden önce bazı ilgi çekici NLP problemlerinde nasıl kullanılabileceklerine bakalım. | ||
|
||
## Pipelinelar (Boru Hatları) ile uğraşmak[[working-with-pipelines]] | ||
|
||
<Youtube id="tiZFewofSLM" /> | ||
|
||
🤗 Transformers kütüphanesindeki en temel şey `pipeline()` fonksiyonudur. Bir modeli gerekli ön işleme ve son işleme adımlarıyla bağlar. bize ise herhangi bir texti yükleyip cevap almak kalır: | ||
|
||
```python | ||
from transformers import pipeline | ||
|
||
classifier = pipeline("sentiment-analysis") | ||
classifier("I've been waiting for a HuggingFace course my whole life.") | ||
``` | ||
|
||
```python out | ||
[{'label': 'POSITIVE', 'score': 0.9598047137260437}] | ||
``` | ||
|
||
Fonksiyona birden fazla cümle de verebiliriz! | ||
|
||
```python | ||
classifier( | ||
["I've been waiting for a HuggingFace course my whole life.", "I hate this so much!"] | ||
) | ||
``` | ||
|
||
```python out | ||
[{'label': 'POSITIVE', 'score': 0.9598047137260437}, | ||
{'label': 'NEGATIVE', 'score': 0.9994558095932007}] | ||
``` | ||
|
||
Varsayılan olarak bu pipeline, İngilizce için sentiment analysis (duygusal analiz) için önceden eğitilmiş bir modeli seçer. Model, `classifier` objesini oluşturduğunuzda indirilir ve önbelleğe (ram'e) alınır. Bu satırı yeniden çalıştırırsanız, önbelleğe alınmış model kullanılır ve modeli tekrar indirmenize gerek kalmaz. | ||
|
||
Bir pipeline'a bir metin verdiğinizde üç ana adım vardır: | ||
|
||
1. Metin, modelin anlayabileceği bir formata dönüştürülmek için ön işleme yapılır. | ||
2. Ön işlenen metin modelin girdisi olarak verilir. | ||
3. Modelin tahminlerine son işleme yapılır ki onları anlayabilesiniz. | ||
|
||
|
||
[Şu anda var olan bazı pipelinelar](https://huggingface.co/transformers/main_classes/pipelines.html): | ||
|
||
- `feature-extraction` (Metnin vektör temsilini üretir) | ||
- `fill-mask` (Boşluk doldurma) | ||
- `ner` (named entity recognition - isimlendirilmiş varlık tanıma) | ||
- `question-answering` (soru-cevaplama) | ||
- `sentiment-analysis` (duygusal analiz) | ||
- `summarization` (özetleme) | ||
- `text-generation` (metin üretme) | ||
- `translation` (çeviri) | ||
- `zero-shot-classification` (Bir sınıflandırma türü modelin daha önce görmediği label'ları tahmin etmesi) | ||
|
||
Hadi bir kaçına bakalım! | ||
|
||
## Zero-shot classification[[zero-shot-classification]] | ||
|
||
Biraz zor bir görevle başlıyoruz. Bu görevde etiketlenmemiş metinleri sınıflandırmamız gerekiyor. Bu gerçek hayatta karşılaşılan bir durum çünkü metinleri etiketlemek genellikle zaman alır ve metnin alanında uzmanlık gerektirir. Bu yüzden `zero-shot-classification` pipeline'ı çok güçlüdür: sınıflandırma için hangi etiketleri kullanacağınızı belirtebilirsiniz. Daha önce modelin iki etiket olan pozitif ve negatif olarak bir cümleyi sınıflandırabildiğini gördünüz ama bununla modeli istediğiniz herhangi bir etiket kümesini kullanarak sınıflandırabilirsiniz. | ||
|
||
```python | ||
from transformers import pipeline | ||
|
||
classifier = pipeline("zero-shot-classification") | ||
classifier( | ||
"This is a course about the Transformers library", | ||
candidate_labels=["education", "politics", "business"], | ||
) | ||
``` | ||
|
||
```python out | ||
{'sequence': 'This is a course about the Transformers library', | ||
'labels': ['education', 'business', 'politics'], | ||
'scores': [0.8445963859558105, 0.111976258456707, 0.043427448719739914]} | ||
``` | ||
|
||
Bu boru hattına _sıfır-atış_ denmesinin sebebi modeli verileriniz üzerinde eğitmenize gerek olmamasıdır. İstediğiniz herhangi etiket listesi için doğrudan olasılık skorları döndürebilir! | ||
|
||
<Tip> | ||
|
||
✏️ **Deneyin!** Kendi cümlelerinizi ve labellarınızı yazın ve moedlin nasıl tepki verdiğine bakın. | ||
|
||
</Tip> | ||
|
||
|
||
## Metin üretme[[text-generation]] | ||
|
||
Şimdi bir pipeline'ı metin üretmek için nasıl kullanacağımıza bakalım. Burada ana fikir: siz bir prompt veriyorsunuz ve model kalan kısmı metin üreterek tamamlıyor. Bu akıllı telefonunuzda bulunan metin tahminleme özelliğine benziyor. Metin üretme rastgelelik içerdiği için aşağıdaki örneklerle aynı sonuçları alamayabilirsiniz. | ||
|
||
```python | ||
from transformers import pipeline | ||
|
||
generator = pipeline("text-generation") | ||
generator("In this course, we will teach you how to") | ||
``` | ||
|
||
```python out | ||
[{'generated_text': 'In this course, we will teach you how to understand and use ' | ||
'data flow and data interchange when handling user data. We ' | ||
'will be working with one or more of the most commonly used ' | ||
'data flows — data flows of various types, as seen by the ' | ||
'HTTP'}] | ||
``` | ||
|
||
Kaç farklı tahmin çıktısı verileceği `num_return_sequences` argümanıyla ve çıktı metnin toplam uzunluğu `max_length` argümanıyla kontrol edilebilir. | ||
|
||
<Tip> | ||
|
||
✏️ **Deneyin!** `num_return_sequences` ve `max_length` argümanlarının kullanarak 15'er cümle uzunluğunda iki cümle üretin. | ||
|
||
</Tip> | ||
|
||
|
||
## Pipeline'da Hub'daki herhangi bir modeli kullanmak[[using-any-model-from-the-hub-in-a-pipeline]] | ||
|
||
The previous examples used the default model for the task at hand, but you can also choose a particular model from the Hub to use in a pipeline for a specific task — say, text generation. Go to the [Model Hub](https://huggingface.co/models) and click on the corresponding tag on the left to display only the supported models for that task. You should get to a page like [this one](https://huggingface.co/models?pipeline_tag=text-generation). | ||
Önceki örneklerde varsayılan modeli kullandık ama Hub'dan bir model seçip onu pipeline'da kullanabilirsiniz. Örneğin metin üretme için bir model seçelim. [Model Hub](https://huggingface.co/models) sayfasına gidin ve sol taraftaki başlıklardan metin üretme başlığını seçin. [Bu sayfaya](https://huggingface.co/models?pipeline_tag=text-generation) benzer bir sayfa göreceksiniz. | ||
|
||
Hadi [`distilgpt2`](https://huggingface.co/distilgpt2) modelini deneyelim! Aynı pipeline fonksiyonunu kullanarak modeli yükleyebiliriz. | ||
|
||
|
||
|
||
|
||
```python | ||
from transformers import pipeline | ||
|
||
generator = pipeline("text-generation", model="distilgpt2") | ||
generator( | ||
"In this course, we will teach you how to", | ||
max_length=30, | ||
num_return_sequences=2, | ||
) | ||
``` | ||
|
||
```python out | ||
[{'generated_text': 'In this course, we will teach you how to manipulate the world and ' | ||
'move your mental and physical capabilities to your advantage.'}, | ||
{'generated_text': 'In this course, we will teach you how to become an expert and ' | ||
'practice realtime, and with a hands on experience on both real ' | ||
'time and real'}] | ||
``` | ||
|
||
Aramanızı dil etiketlerine tıklayarak daraltabilirsiniz. Böylece İngilizceden farllı dillerde metinler üretecek modeller kullanabilirsiniz. Model Hub'da birden fazla dilde çalışan modeller bile bulunuyor! | ||
|
||
Üstüne tıklayarak bir model seçtiğinizde, modeli denemek için bir widget göreceksiniz. Bu sayede modelin yapabildiklerini indirmeden önce hızlıca deneyebilirsiniz. | ||
|
||
<Tip> | ||
|
||
✏️ **Deneyin!** Başka bir dilde metin üretmek için filtreleri kullanın. Widget'ı kullanıp modeli denedikten sonra pipeline'da kullanın! | ||
|
||
|
||
</Tip> | ||
|
||
### The Inference API'ı[[the-inference-api]] | ||
|
||
Bütün modelleri Inference API'ı kullanarak tarayıcınızda deneyebilirsiniz. Bu API Hugging Face [websitesinde](https://huggingface.co/) mevcut. sayfa üzerinden direkt modeli kullanıp kendiniz metin girebilirsiniz. | ||
|
||
The Inference API that powers the widget is also available as a paid product, which comes in handy if you need it for your workflows. See the [pricing page](https://huggingface.co/pricing) for more details. | ||
Bu widgetın arkasındaki Inference API'ı üçretli bir ürün olarak da alabilirsiniz. Eğer iş süreçlerinizde ihtiyaç duyuyorsanız oldukça kullanışlıdır. Detaylı bilgi için [fiyatlandırma](https://huggingface.co/pricing) sayfasına bakabilirsiniz. | ||
|
||
## Mask filling[[mask-filling]] | ||
|
||
The next pipeline you'll try is `fill-mask`. The idea of this task is to fill in the blanks in a given text: | ||
|
||
```python | ||
from transformers import pipeline | ||
|
||
unmasker = pipeline("fill-mask") | ||
unmasker("This course will teach you all about <mask> models.", top_k=2) | ||
``` | ||
|
||
```python out | ||
[{'sequence': 'This course will teach you all about mathematical models.', | ||
'score': 0.19619831442832947, | ||
'token': 30412, | ||
'token_str': ' mathematical'}, | ||
{'sequence': 'This course will teach you all about computational models.', | ||
'score': 0.04052725434303284, | ||
'token': 38163, | ||
'token_str': ' computational'}] | ||
``` | ||
|
||
The `top_k` argument controls how many possibilities you want to be displayed. Note that here the model fills in the special `<mask>` word, which is often referred to as a *mask token*. Other mask-filling models might have different mask tokens, so it's always good to verify the proper mask word when exploring other models. One way to check it is by looking at the mask word used in the widget. | ||
|
||
<Tip> | ||
|
||
✏️ **Try it out!** Search for the `bert-base-cased` model on the Hub and identify its mask word in the Inference API widget. What does this model predict for the sentence in our `pipeline` example above? | ||
|
||
</Tip> | ||
|
||
## Named entity recognition[[named-entity-recognition]] | ||
|
||
Named entity recognition (NER) is a task where the model has to find which parts of the input text correspond to entities such as persons, locations, or organizations. Let's look at an example: | ||
|
||
```python | ||
from transformers import pipeline | ||
|
||
ner = pipeline("ner", grouped_entities=True) | ||
ner("My name is Sylvain and I work at Hugging Face in Brooklyn.") | ||
``` | ||
|
||
```python out | ||
[{'entity_group': 'PER', 'score': 0.99816, 'word': 'Sylvain', 'start': 11, 'end': 18}, | ||
{'entity_group': 'ORG', 'score': 0.97960, 'word': 'Hugging Face', 'start': 33, 'end': 45}, | ||
{'entity_group': 'LOC', 'score': 0.99321, 'word': 'Brooklyn', 'start': 49, 'end': 57} | ||
] | ||
``` | ||
|
||
Here the model correctly identified that Sylvain is a person (PER), Hugging Face an organization (ORG), and Brooklyn a location (LOC). | ||
|
||
We pass the option `grouped_entities=True` in the pipeline creation function to tell the pipeline to regroup together the parts of the sentence that correspond to the same entity: here the model correctly grouped "Hugging" and "Face" as a single organization, even though the name consists of multiple words. In fact, as we will see in the next chapter, the preprocessing even splits some words into smaller parts. For instance, `Sylvain` is split into four pieces: `S`, `##yl`, `##va`, and `##in`. In the post-processing step, the pipeline successfully regrouped those pieces. | ||
|
||
<Tip> | ||
|
||
✏️ **Try it out!** Search the Model Hub for a model able to do part-of-speech tagging (usually abbreviated as POS) in English. What does this model predict for the sentence in the example above? | ||
|
||
</Tip> | ||
|
||
## Question answering[[question-answering]] | ||
|
||
The `question-answering` pipeline answers questions using information from a given context: | ||
|
||
```python | ||
from transformers import pipeline | ||
|
||
question_answerer = pipeline("question-answering") | ||
question_answerer( | ||
question="Where do I work?", | ||
context="My name is Sylvain and I work at Hugging Face in Brooklyn", | ||
) | ||
``` | ||
|
||
```python out | ||
{'score': 0.6385916471481323, 'start': 33, 'end': 45, 'answer': 'Hugging Face'} | ||
``` | ||
|
||
Note that this pipeline works by extracting information from the provided context; it does not generate the answer. | ||
|
||
## Summarization[[summarization]] | ||
|
||
Summarization is the task of reducing a text into a shorter text while keeping all (or most) of the important aspects referenced in the text. Here's an example: | ||
|
||
```python | ||
from transformers import pipeline | ||
|
||
summarizer = pipeline("summarization") | ||
summarizer( | ||
""" | ||
America has changed dramatically during recent years. Not only has the number of | ||
graduates in traditional engineering disciplines such as mechanical, civil, | ||
electrical, chemical, and aeronautical engineering declined, but in most of | ||
the premier American universities engineering curricula now concentrate on | ||
and encourage largely the study of engineering science. As a result, there | ||
are declining offerings in engineering subjects dealing with infrastructure, | ||
the environment, and related issues, and greater concentration on high | ||
technology subjects, largely supporting increasingly complex scientific | ||
developments. While the latter is important, it should not be at the expense | ||
of more traditional engineering. | ||
Rapidly developing economies such as China and India, as well as other | ||
industrial countries in Europe and Asia, continue to encourage and advance | ||
the teaching of engineering. Both China and India, respectively, graduate | ||
six and eight times as many traditional engineers as does the United States. | ||
Other industrial countries at minimum maintain their output, while America | ||
suffers an increasingly serious decline in the number of engineering graduates | ||
and a lack of well-educated engineers. | ||
""" | ||
) | ||
``` | ||
|
||
```python out | ||
[{'summary_text': ' America has changed dramatically during recent years . The ' | ||
'number of engineering graduates in the U.S. has declined in ' | ||
'traditional engineering disciplines such as mechanical, civil ' | ||
', electrical, chemical, and aeronautical engineering . Rapidly ' | ||
'developing economies such as China and India, as well as other ' | ||
'industrial countries in Europe and Asia, continue to encourage ' | ||
'and advance engineering .'}] | ||
``` | ||
|
||
Like with text generation, you can specify a `max_length` or a `min_length` for the result. | ||
|
||
|
||
## Translation[[translation]] | ||
|
||
For translation, you can use a default model if you provide a language pair in the task name (such as `"translation_en_to_fr"`), but the easiest way is to pick the model you want to use on the [Model Hub](https://huggingface.co/models). Here we'll try translating from French to English: | ||
|
||
```python | ||
from transformers import pipeline | ||
|
||
translator = pipeline("translation", model="Helsinki-NLP/opus-mt-fr-en") | ||
translator("Ce cours est produit par Hugging Face.") | ||
``` | ||
|
||
```python out | ||
[{'translation_text': 'This course is produced by Hugging Face.'}] | ||
``` | ||
|
||
Like with text generation and summarization, you can specify a `max_length` or a `min_length` for the result. | ||
|
||
<Tip> | ||
|
||
✏️ **Try it out!** Search for translation models in other languages and try to translate the previous sentence into a few different languages. | ||
|
||
</Tip> | ||
|
||
The pipelines shown so far are mostly for demonstrative purposes. They were programmed for specific tasks and cannot perform variations of them. In the next chapter, you'll learn what's inside a `pipeline()` function and how to customize its behavior. |