トップページ ▶ 人工知能,実世界DB ▶ 日本語処理,言語処理 ▶ GPT-2, BERT を使ってみる(huggingface/transformers を利用)(Google Colab あるいは Windows あるいは Ubuntu 上)

GPT-2, BERT を使ってみる(huggingface/transformers を利用)(Google Colab あるいは Windows あるいは Ubuntu 上)

Google Colab へのリンク

このページの内容は,Google Colaboratory でも実行できる.

そのために,次の URL で,Google Colaboratory のノートブックを準備している.

次のリンクをクリックすると,Google Colaboratory のノートブックが開く. そして,Google アカウントでログインすると,Google Colaboratory のノートブック内のコードを実行することができる.Google Colaboratory のノートブックは書き換えて使うこともできる.このとき,書き換え後のものを,各自の Google ドライブ内に保存することもできる.

https://colab.research.google.com/drive/1mBFygBbUk4lBOov7TVyiat441MHwla3j?usp=sharing

(1) 前準備(Google Colaboratory のノートブックを新規作成して使う場合)

自分で,Google Colaboratory のノートブックを新規作成する場合(上のリンクを使わない)のため,手順を説明する.

パソコンを使う場合は,下に「前準備(パソコンを使う場合)」で説明している.

  1. Google Colaboratory のWebページを開く

    https://colab.research.google.com

    Google Colab はオンラインの Python 開発環境. 使用するには Google アカウントが必要

  2. 「ファイル」で、「ノートブックを新規作成」を選ぶ

  3. Google アカウントでのログインが求められたときはログインする

(2) (自分のパソコンで Python を動かす場合)Python の準備

Python のインストール,pip と setuptools の更新,Python 開発環境

Python の URL: http://www.python.org/

【Python, pip の使い方】

Python, pip は,次のコマンドで起動できる.

【Python 開発環境のインストール】

TensorFlow,tensorflow_datasets,numpy,matplotlib, seaborn, scikit-learn のインストール

GraphViz のインストール

huggingface/transformers の GPT-2 を動かしてみる

huggingface/transformers の URL: https://huggingface.co/transformers/ huggingface/transformers の GitHub の URL: https://github.com/huggingface/transformers

  1. transformers のインストール

    次のページに記載の手順に従う:https://huggingface.co/transformers/installation.html

    Windows では,コマンドプロンプトを管理者として実行し,次のコマンドを実行.

    python -m pip install transformers
    

  2. 英語で学習済みの GPT-2 を使ってみる

    次のページに記載のソースコードからビルドして,インストールする.(詳細説明も次のページにある): https://huggingface.co/gpt2

    Python プログラムを動かすために, pythonやpython3などのコマンドを使う. あるいは, 開発環境や Python コンソール(Jupyter Qt Console,Spyder,PyCharm,PyScripter など)も便利である.

    次のプログラムは,テキスト生成(与えられた文章から,続きのトークンを生成)を行っている.

    from transformers import pipeline, set_seed
    generator = pipeline('text-generation', model='gpt2')
    set_seed(42)
    generator("Hello, I'm a language model,", max_length=30, num_return_sequences=5)
    

    次のプログラムは,特徴(features )の取得を行っている.

    from transformers import GPT2Tokenizer, TFGPT2Model
    tokenizer = GPT2Tokenizer.from_pretrained('gpt2')
    model = TFGPT2Model.from_pretrained('gpt2')
    text = "Replace me by any text you'd like."
    encoded_input = tokenizer(text, return_tensors='tf')
    output = model(encoded_input)
    

  3. 英語で学習済みの BERT を使ってみる

    次のページに記載のソースコードからビルドして,インストールする.(詳細説明も次のページにある): https://huggingface.co/bert-base-uncased

    Python プログラムを動かすために, pythonやpython3などのコマンドを使う. あるいは, 開発環境や Python コンソール(Jupyter Qt Console,Spyder,PyCharm,PyScripter など)も便利である.

    次のプログラムは,マスクを埋める(fill mask)ことを行っている.

    from transformers import pipeline
    unmasker = pipeline('fill-mask', model='bert-base-uncased')
    unmasker("Hello I'm a [MASK] model.")