آشنایی
پایتکست (PyText) یک چهارچوب پردازش زبان طبیعی بر پایه یادگیری عمیق میباشد. پایتکست قابلیت آزمایش سریع ایدههای مختلف و ارائه مدلهای آموزش دیده را فراهم میکند.
Facebook:
We are using PyText in Facebook to iterate quickly on new modeling ideas and then seamlessly ship them at scale.
برای آشنایی بیشتر با هستهی پایتکست:
- Yoon Kim (2014): Convolutional Neural Networks for Sentence Classification
- Lin et al. (2017): A Structured Self-attentive Sentence Embedding
- Lample et al. (2016): Neural Architectures for Named Entity Recognition
- Zhang et al. (2016): A Joint Model of Intent Determination and Slot Filling for Spoken Language Understanding
نصب
سیستم عامل لینوکس:
1 2 3 4 5 6 |
#!/bin/bash $ sudo apt-get install protobuf-compiler libprotoc-dev $ python3 -m venv pytext_venv $ source pytext_venv/bin/activate (pytext_venv) $ pip install pytext_nlp |
ساختار داده برای ایجاد کلاسبند
ساختار دادهای که در این آموزش به عنوان ورودی به پایتکست میدهیم به شکل TSV میباشد که ستون اول داده و ستون دوم برچسب آن میباشد.
1 2 3 |
#!/bin/bash $ ls ~/Downloads/my_dataset dataset-test.tsv dataset-train.tsv |
ایجاد فایل تنظیمات
پایتکست برای راحتی بیشتر سعی کرده حتیالامکان تمام تنظیمات موجود مانند محل ذخیرهسازی مدل آموزش دیده، فعال سازی GPU، گزارش گیری توسط Tensorboard و یک سری تنظیمات مربوط به ساختار شبکه عصبی که از قبل پیادهسازی شدهاند را با فرمت JSON از ورودی دریافت کند.
حال برای آموزش یک کلاسبند ما به تنظیمات زیر نیاز داریم:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
#!/bin/bash $ ls ~/Projects/pytext/classifier clf.json $ cat clf.json { "task": { "DocClassificationTask": { "trainer": { "epochs": 30, "random_seed": 0, "early_stop_after": 0, "max_clip_norm": null, "report_train_metrics": true }, "data_handler": { "columns_to_read": ["text", "doc_label"], "eval_batch_size": 128, "max_seq_len": -1, "shuffle": true, "sort_within_batch": true, "test_batch_size": 128, "train_batch_size": 128, "train_path": "~/Downloads/my_dataset/dataset-train.tsv", "eval_path": "~/Downloads/my_dataset/dataset-test.tsv", "test_path": "~/Downloads/my_dataset/dataset-test.tsv" } } }, "use_cuda_if_available": false, "distributed_world_size": 1, "load_snapshot_path": "", "save_snapshot_path": "~/Projects/pytext/classifier/dataset-model.pt", "export_caffe2_path": "~/Projects/pytext/classifier/dataset-model.caffe2.predictor", "modules_save_dir": "", "save_module_checkpoints": false, "use_tensorboard": true, "test_out_path": "~/Projects/pytext/classifier/dataset-test_out.txt", "debug_path": "~/Projects/pytext/classifier/dataset-model.debug" } |
همانطور که مشاهده میکنید تنظیماتی همچون تعداد epoch و batch_size نیز قابل تنظیم هستند.
(توجه! در صورت نیاز به افزودن بردار کلمات از پیش آموزش دیده (برای مثال glove) میتوانید مانند تنظیمات زیر مسیر فایل را با عنوان pretrained_embeddings_path
معرفی کنید.)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
{ "task": { "DocClassificationTask": { "trainer": { "epochs": 10, "random_seed": 0, "report_train_metrics": true }, "features": { "char_feat": null, "dense_feat": null, "dict_feat": null, "freeze": false, "load_path": null, "pretrained_model_embedding": null, "save_path": null, "shared_module_key": null, "word_feat": { "embed_dim": 100, "embedding_init_strategy": "random", "export_input_names": ["tokens_vals"], "pretrained_embeddings_path": "~/Downloads/my_word_embedding_100d.txt", "lowercase_tokens": true, "vocab_from_all_data": false, "vocab_from_train_data": true } }, "data_handler": { … |
آموزش کلاسبند
برای آموزش کلاسبند فقط کافیست تنظیمات از پیش تعیین شده را به پایتکست معرفی کنیم:
1 2 |
#!/bin/bash (pytext_venv) $ pytext train < ~/Projects/pytext/classifier/clf.json |
پس از اجرای دستور بالا روند آموزش بصورت کامل گزارش میشود و بصورت خودکار بهترین مدل آموزش دیده ذخیره میشود.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
… … 89 0.00 Label Recall at precision 0.8 89 0.00 Label Recall at precision 0.9 89 0.00 Label Recall at precision 0.2 3861 0.00 Label Recall at precision 0.4 3861 0.00 Label Recall at precision 0.6 3861 0.00 Label Recall at precision 0.8 3861 0.00 Label Recall at precision 0.9 3861 0.00 Rank 0 worker: Found a better model! Saving the model state. Rank 0 worker: Starting epoch #2 Learning rate(s): 0.001, 0.001 Rank 0 worker: Running epoch for Stage.TRAIN Stage.TRAIN loss: 1.712181 Accuracy: 48.35 … |
1 2 3 |
#!/bin/bash $ ls ~/Projects/pytext/classifier dataset-model.pt clf.json |
ذخیره سازی مدل آموزش دیده
برای ذخیره سازی مدل نیز کافیست تنظیمات تعیین شده را به پایتکست معرفی کنید:
1 2 |
#!/bin/bash (pytext_venv) $ pytext export < ~/Projects/pytext/classifier/clf.json |
پس از اجرای دستور بالا یک فایل با نام dataset-model.caffe2.predictor
در مسیر ~/Projects/pytext/classifier
ایجاد میشود.
1 2 3 |
#!/bin/bash $ ls ~/Projects/pytext/classifier dataset-model.caffe2.predictor dataset-model.pt clf.json |
پیشبینی
برای آزمایش و پیشبینی توسط مدل میتوانید از کد زیر کمک بگیرید:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved import re import numpy as np from caffe2.python import workspace from caffe2.python.predictor import predictor_exporter # Load Caffe2 model predict_net = predictor_exporter.prepare_prediction_net( filename="~/Projects/pytext/classifier/dataset-model.caffe2.predictor", db_type="minidb" ) # Pre-processing helper method def tokenize(text): # Split by whitespace, force lowercase tokens = [] token_ranges = [] def add_token(text, start, end): token = text[start:end] if token: tokens.append(token) token_ranges.append((start, end)) start = 0 text = text for sep in re.finditer(r"\s+", text): add_token(text, start, sep.start()) start = sep.end() add_token(text, start, len(text)) if not tokens: # Add PAD_TOKEN in case of empty text tokens = ["<pad>"] tokens = list(map(str.lower, tokens)) return tokens, token_ranges def predict(text): # Pre-process tokens, token_ranges = tokenize(text) # Make prediction workspace.blobs["tokens_vals_str:value"] = np.array([tokens], dtype=str) workspace.blobs["tokens_lens"] = np.array([len(tokens)], dtype=np.int_) workspace.RunNet(predict_net) labels_scores = [ (str(blob), workspace.blobs[blob][0]) for blob in predict_net.external_outputs if 'doc_scores' in str(blob) ] return labels_scores |
رسم ساختار شبکه عصبی
در صورت نیاز به رسم ساختار شبکه خود میتوانید مانند مثال زیر عمل کنید:
1 2 3 4 5 6 7 8 9 10 11 |
#!/usr/bin/env python3 from caffe2.python.predictor import predictor_exporter from caffe2.python import net_drawer # Load Caffe2 model predict_net = predictor_exporter.prepare_prediction_net( filename="~/Projects/pytext/classifier/dataset-model.caffe2.predictor", db_type="minidb" ) ## ploting graph graph = net_drawer.GetPydotGraph(predict_net, rankdir="LR") open('model.png', 'wb').write(graph.create(format='png')) |
تصویر تولید شده در فایلی به نام model.png
ذخیره میشود.
شبکه های اجتماعی