

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

# BlazingText 演算法
<a name="blazingtext"></a>

Amazon SageMaker AI BlazingText 演算法提供高度最佳化的 Word2vec 和文字分類演算法實作。Word2vec 演算法對許多下游自然語言處理 (NLP) 任務來說非常有用，例如情感分析、具名實體辨識、機器翻譯等。文字分類對執行 web 搜尋、資訊擷取、排名和文件分類的應用程式來說，是一項非常重要的任務。

Word2vec 演算法會將文字映射到高品質的分散式向量。其產生的文字向量表示稱為*文字內嵌*。語意上相似的文字會對應到彼此較為靠近的向量。透過這種方式，文字內嵌便能擷取文字之間的語意關係。

許多自然語言處理 (NLP) 的應用程式會透過在大量文件集合上進行訓練，來學習文字內嵌。這種預先訓練過的向量表示，可提供語意和文字分布的相關資訊，通常可以改善後續以更有限資料訓練的其他模型一般性。大多數 Word2vec 演算法的實作並未針對多核心 CPU 架構進行最佳化處理。因此難以擴展至大型資料集。

使用 BlazingText 演算法，您可以輕鬆擴展至大型資料集。與 Word2vec 類似，BlazingText 提供了 Skip-gram 和連續性詞袋 (CBOW) 訓練架構。BlazingText 的監督式多類別實作及多標籤文字分類演算法，可延伸 fastText 文字分類器，搭配自訂 [CUDA](https://docs.nvidia.com/cuda/index.html) 核心使用 GPU 加速。您可以使用多核心 CPU 或 GPU，在幾分鐘之內於超過十億個文字上訓練模型。並且，您可以達到與最先進深度學習文字分類演算法相同的效能。

BlazingText 演算法不可平行化。有關訓練相關參數的詳細資訊，請參閱[SageMaker 內建演算法的碼頭註冊表路徑](https://docs.aws.amazon.com/en_us/sagemaker/latest/dg/sagemaker-algo-docker-registry-paths.html)。

 SageMaker AI BlazingText 演算法提供下列功能：
+ 使用高度最佳化的 CUDA 核心，加速在多核心 CPU 或 GPU 上的 fastText 文字分類器訓練，或是 GPU 上的 Word2Vec。如需詳細資訊，請參閱 [BlazingText: Scaling and Accelerating Word2Vec using Multiple GPUs](https://dl.acm.org/citation.cfm?doid=3146347.3146354)。
+ 透過學習字元 n-grams 的向量表示達到的 [Enriched Word Vectors with Subword Information](https://arxiv.org/abs/1607.04606)。這種方法可讓 BlazingText 透過將其向量做為字元 n-gram (部分字組) 向量的總和表示，為詞彙不足 (out-of-vocabulary, OOV) 產生有意義的向量。
+ Word2Vec 演算法的 `batch_skipgram` `mode`，允許更快速的訓練和跨越多個 CPU 節點的分散式運算。`batch_skipgram` `mode` 會使用負面樣本共享 (Negative Sample Sharing) 策略進行迷你批次處理，將 1 級的 BLAS 操作轉換成 3 級的 BLAS 操作。這可有效地運用現代架構的乘加指令。如需詳細資訊，請參閱 [Parallelizing Word2Vec in Shared and Distributed Memory](https://arxiv.org/pdf/1604.04661.pdf)。

就摘要而言，BlazingText 在不同類型的執行個體上支援下列模式：


| 模式 |  Word2Vec (無監督學習)  |  文字分類 (監督式學習)  | 
| --- | --- | --- | 
| 單一 CPU 執行個體 | `cbow`<br />`Skip-gram`<br />`Batch Skip-gram` | `supervised` | 
| 單一 GPU 執行個體 (具備一或多個 GPU) | `cbow`<br />`Skip-gram` | `supervised`，具備一個 GPU | 
| 多 CPU 執行個體 | Batch Skip-gram  | 無 | 

如需 BlazingText 背後數學機制的詳細資訊，請參閱 [BlazingText: Scaling and Accelerating Word2Vec using Multiple GPUs](https://dl.acm.org/citation.cfm?doid=3146347.3146354)。

**Topics**
+ [BlazingText 演算法的輸入/輸出介面](#bt-inputoutput)
+ [適用於 BlazingText 演算法的 EC2 執行個體建議事項](#blazingtext-instances)
+ [BlazingText 範例筆記本](#blazingtext-sample-notebooks)
+ [BlazingText 超參數](blazingtext_hyperparameters.md)
+ [調校 BlazingText 模型](blazingtext-tuning.md)

## BlazingText 演算法的輸入/輸出介面
<a name="bt-inputoutput"></a>

BlazingText 演算法會預期收到一個使用空白分隔權杖的單一預先處理文字檔案。檔案中的每一行都應包含一個句子。若您需要在多個文字檔案上進行訓練，請將他們串連成一個檔案，並在個別通道中上傳檔案。

### 訓練及驗證資料格式
<a name="blazingtext-data-formats"></a>

#### Word2Vec 演算法的訓練及驗證資料格式
<a name="blazingtext-data-formats-word2vec"></a>

針對 Word2Vec 訓練，請在*訓練*通道下上傳檔案。不支援其他通道。檔案中的每一行都應包含一個訓練句子。

#### 文字分類 (Text Classification) 演算法的訓練及驗證資料格式
<a name="blazingtext-data-formats-text-class"></a>

針對監督式模式，您可以使用檔案模式或擴增資訊清單文字格式進行訓練。

##### 使用檔案模式訓練
<a name="blazingtext-data-formats-text-class-file-mode"></a>

針對 `supervised` 模式，訓練/驗證檔案中的每一行應包含一個訓練句子及標籤。標籤是加上字串 *\_\_label\_\_* 做為字首的文字。以下是訓練/驗證檔案的範例：

```
__label__4  linux ready for prime time , intel says , despite all the linux hype , the open-source movement has yet to make a huge splash in the desktop market . that may be about to change , thanks to chipmaking giant intel corp .

__label__2  bowled by the slower one again , kolkata , november 14 the past caught up with sourav ganguly as the indian skippers return to international cricket was short lived .
```

**注意**  
句子中標籤的順序不重要。

在訓練通道下上傳訓練檔案，然後選擇性地在驗證通道下上傳驗證檔案。

##### 以擴增資訊清單文字格式進行訓練
<a name="blazingtext-data-formats-text-class-augmented-manifest"></a>

CPU 執行個體監督式模式也支援擴增資訊清單格式，可讓您在管道模式中進行訓練，而無需建立 RecordIO 檔案。使用此格式時，需要產生 S3 資訊清單檔案，其中包含句子清單及其對應的標籤。資訊清單檔案格式應為 [JSON Lines](http://jsonlines.org/) 格式，其中每一行都代表一個範例。句子會使用 `source` 標籤指定，標籤則使用 `label` 標籤指定。`source` 和 `label` 標籤都應在請求中所指定的 `AttributeNames` 參數值下提供。

```
{"source":"linux ready for prime time , intel says , despite all the linux hype", "label":1}
{"source":"bowled by the slower one again , kolkata , november 14 the past caught up with sourav ganguly", "label":2}
```

指定標籤的 JSON 陣列也支援多標籤訓練。

```
{"source":"linux ready for prime time , intel says , despite all the linux hype", "label": [1, 3]}
{"source":"bowled by the slower one again , kolkata , november 14 the past caught up with sourav ganguly", "label": [2, 4, 5]}
```

如需擴增資訊清單檔案的詳細資訊，請參閱[訓練任務中的擴增的資訊清單檔案](augmented-manifest.md)。

### 模型成品和推論
<a name="blazingtext-artifacts-inference"></a>

#### Word2Vec 演算法的模型成品
<a name="blazingtext--artifacts-inference-word2vec"></a>

針對 Word2Vec 訓練，模型成品由 *vectors.txt* (包含文字對向量的映射) 和 *vectors.bin* (由 BlazingText 用來進行託管、推論或兩者的二進位檔) 組成。*vectors.txt* 會將向量以和其他工具 (例如 Gensim 和 Spacy) 相容的格式存放。例如，Gensim 使用者可執行下列命令來載入 vectors.txt 檔案：

```
from gensim.models import KeyedVectors
word_vectors = KeyedVectors.load_word2vec_format('vectors.txt', binary=False)
word_vectors.most_similar(positive=['woman', 'king'], negative=['man'])
word_vectors.doesnt_match("breakfast cereal dinner lunch".split())
```

若評估參數設為 `True`，則會建立額外的檔案 *eval.json*。此檔案包含 WS-353 資料集的相似性評估結果 (使用 Spearman 的排名關聯係數)。訓練主體中沒有的 WS-353 資料集的文字數會進行報告。

針對推論請求，模型接受包含字串清單的 JSON 檔案，並會傳回向量清單。若在詞彙中找不到文字，則推論會傳回零的向量。若部分字組在訓練期間設為 `True`，則模型可以為詞彙不足 (OOV) 文字產生向量。

##### 範例 JSON 請求
<a name="word2vec-json-request"></a>

Mime-type：` application/json`

```
{
"instances": ["word1", "word2", "word3"]
}
```

#### 文字分類演算法的模型成品
<a name="blazingtext-artifacts-inference-text-class"></a>

使用監督式輸出進行的訓練會建立 *model.bin* 檔案，該檔案可由 BlazingText 主機使用。針對推論，BlazingText 模型接受包含句子清單的 JSON 檔案，並會傳回對應預測標籤清單和可能性分數。每個句子都預期是使用空白分隔權杖、文字或兩者的字串。

##### 範例 JSON 請求
<a name="text-class-json-request"></a>

Mime-type：` application/json`

```
{
 "instances": ["the movie was excellent", "i did not like the plot ."]
}
```

根據預設，伺服器只會傳回一個預測，即可能性最高的預測。若要擷取頂端的 *k* 預設，您可以在組態中設定 *k*，如下所示：

```
{
 "instances": ["the movie was excellent", "i did not like the plot ."],
 "configuration": {"k": 2}
}
```

針對 BlazingText，` content-type` 和 `accept` 參數必須相等。針對批次轉換，他們都必須是 `application/jsonlines`。如果不同，則會忽略 `Accept` 欄位。輸入的格式如下：

```
content-type: application/jsonlines

{"source": "source_0"}
{"source": "source_1"}

if you need to pass the value of k for top-k, then you can do it in the following way:

{"source": "source_0", "k": 2}
{"source": "source_1", "k": 3}
```

輸出的格式如下：

```
accept: application/jsonlines


{"prob": [prob_1], "label": ["__label__1"]}
{"prob": [prob_1], "label": ["__label__1"]}

If you have passed the value of k to be more than 1, then response will be in this format:

{"prob": [prob_1, prob_2], "label": ["__label__1", "__label__2"]}
{"prob": [prob_1, prob_2], "label": ["__label__1", "__label__2"]}
```

針對監督式 (文字分類) 和無監督 (Word2Vec) 模式，BlazingText 產生的二進位檔 (*\*.bin*) 可以和 fastText 互相使用，反之亦然。您可以使用 fastText 的 BlazingText 所產生的二進位檔。同樣地，您可以託管使用 BlazingText 建立的 fastText 模型二進位檔。

以下是如何使用搭載 fastText 的 BlazingText 產生的模型的範例：

```
#Download the model artifact from S3
aws s3 cp s3://<YOUR_S3_BUCKET>/<PREFIX>/model.tar.gz model.tar.gz

#Unzip the model archive
tar -xzf model.tar.gz

#Use the model archive with fastText
fasttext predict ./model.bin test.txt
```

但是，只有在 CPU 和單一 GPU 上進行訓練時才支援二進位檔；多 GPU 上的訓練將不會產生二進位檔。

## 適用於 BlazingText 演算法的 EC2 執行個體建議事項
<a name="blazingtext-instances"></a>

針對 `cbow` 和 `skipgram` 模式，BlazingText 支援單一 CPU 和單一 GPU 的執行個體。這兩種模式都支援學習 `subwords` 內嵌。為了達到最高的速度，同時不犧牲準確度，我們建議您使用 ml.p3.2xlarge 執行個體。

針對 `batch_skipgram` 模式，BlazingText 可支援單一或多個 CPU 執行個體。在多個執行個體上進行訓練時，請將您要傳給 [https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_CreateTrainingJob.html](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_CreateTrainingJob.html) 的 [https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_S3DataSource.html](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_S3DataSource.html) 物件的 `S3DataDistributionType` 欄位設為 `FullyReplicated`。BlazingText takes 會負責處理跨機器的資料分佈。

針對監督式文字分類模式，若訓練資料集小於 2 GB，則建議使用 C5 執行個體。對於較大的資料集，請使用具有單一 GPU 的執行個體。BlazingText 支援 P2、P3、G4dn 和 G5 執行個體，以進行訓練和推論。

## BlazingText 範例筆記本
<a name="blazingtext-sample-notebooks"></a>

如需訓練和部署 SageMaker AI BlazingText 演算法以產生文字向量的範例筆記本，請參閱[使用 BlazingText 學習 Word2Vec 文字表示法](https://sagemaker-examples.readthedocs.io/en/latest/introduction_to_amazon_algorithms/blazingtext_word2vec_text8/blazingtext_word2vec_text8.html)。如需建立和存取您可以用來在 SageMaker AI 中執行範例的 Jupyter 筆記本執行個體說明，請參閱[Amazon SageMaker 筆記本執行個體](nbi.md)。建立並開啟筆記本執行個體後，請選擇 **SageMaker AI 範例**索引標籤，查看所有 SageMaker AI 範例的清單。使用 Blazing Text 模組化範例筆記本的主題位於 **Amazon 演算法簡介**一節。若要開啟筆記本，請選擇其**使用**標籤，然後選擇**建立複本**。