LoginSignup
8
14

More than 1 year has passed since last update.

GPT-3の概要と使い方のコツ

Last updated at Posted at 2021-04-27

GPT-3の使い方をまとめたページは下記に移動しました.
https://np-sys.com/gpt-3-introduction/



















Introduction

  • GPT-3は汎用の「テキスト入力、テキスト出力」インターフェースなので事実上すべての言語タスクに適用可能
  • APIを使用するには、テキストプロンプト(APIに提供するテキストベースの入力または「指示」)を指定するだけで、指定したコンテキストまたはパターンに一致させようとして、テキストの補完が返される
  • 実行したいことのほんの数例を書くことで、それを「プログラム」することができる
  • モデルのトレーニングデータは2019年10月で打ち切りとなっており,継続的なデータの追加は現在検討中

重要な概念

  • APIの中核となる概念は、プロンプト、 完了、トークンの3つ
  • 「プロンプト」はAPIへのテキスト入力であり、「完了」はAPIがプロンプトに基づいて生成するテキスト
  • APIの探索を開始する最良の方法は、Playgroundを使用すること
  • デフォルトでは,テキストプロンプトと生成された補完を組み合わせると、2048トークン(約1500ワード)未満に制限されている
  • モデルはdavinci、curie、babbageとadaの4つ

プロンプトの与え方の基本

  • APIは、オリジナルストーリーの生成から複雑なテキスト分析の実行まであらゆることを実行できる.が,ゆえにしたいことを明確にAPIに伝える必要がある
  • 伝える」だけでなく、見せることが良いプロンプトの秘訣.APIは、プロンプトから必要なものを推測しようとする
  • 「猫の品種のリストを教えてください」という言葉を送信しても、APIは、猫の品種のリストを要求していると自動的に想定しない
  • 最初の単語が「猫の品種のリストを教えて」で、次の単語が「好きなものを教えてあげる」という会話を続けるようにAPIに簡単に依頼するのが良い

プロンプト利用のガイドライン

  • 指示、例、または2つの組み合わせのいずれかを通じて、必要なものをAPIに明確に。APIでアイテムのリストをアルファベット順にランク付けしたり、段落を感情で分類したりする場合はそれを表示。
  • 高品質のデータを提供する.分類子を構築しようとしている場合、またはAPIをパターンに従わせようとしている場合は十分な例があることを確認
  • temperatureとtop_pの設定は、APIが応答を生成する際の決定論性を制御する。この2つが重要.正解が1つしかない応答を提供するようにAPIに要求している場合は、これらを低く設定する必要がある。明らかでない応答を探している場合は、それらをより高く設定

Classification

例はこちら

これはツイート感情分類子です
ツイート:「新しいバットマン映画が大好きでした!」
感情:ポジティブ
###
ツイート:「携帯電話のバッテリーがなくなると嫌いです。」 
感情:否定的
###
ツイート:「私の一日は👍」
感情:ポジティブ
###
ツイート:「これは記事へのリンクです」
感情:ニュートラル
###
ツイート:「この新しいミュージックビデオは私の心を吹き飛ばしました」
感情: 
import os
import openai

openai.api_key = os.getenv("OPENAI_API_KEY")

response = openai.Completion.create(
  engine="davinci",
  prompt="This is a tweet sentiment classifier\n\nTweet: \"I loved the new Batman movie!\"\nSentiment: Positive\n###\nTweet: \"I hate it when my phone battery dies.\"\nSentiment: Negative\n###\nTweet: \"My day has been 👍\"\nSentiment: Positive\n###\nTweet: \"This is the link to the article\"\nSentiment: Neutral\n###\nTweet: \"This new video blew my mind\"\nSentiment: Positive",
  temperature=0.7,
  max_tokens=64,
  top_p=1,
  frequency_penalty=0,
  presence_penalty=0
)
  • プロンプトが最初に何をするかを述べる例の始めに、分類子が何をするかを平易な言葉で述べます.最初に伝えることで例が少なくてすむ.平易な言葉で伝える.
  • 簡単で平易な例を示す
  • 例を区切るマークとして「###」を使用する.
  • APIに任意のケースに対応する方法を示す.これでいうとニュートラルという答えを用意してあげる
  • テキストと絵文字を使用可能

応用例はこんな感じ

This is a tweet sentiment classifier\
Tweet: "I loved the new Batman movie!"\
Sentiment: Positive\
###\
Tweet: "I hate it when my phone battery dies"\
Sentiment: Negative\
###\
Tweet: "My day has been 👍"\
Sentiment: Positive\
###\
Tweet: "This is the link to the article"\
Sentiment: Neutral\
###\
Tweet text

"I loved the new Batman movie!"
"I hate it when my phone battery dies"
"My day has been 👍"
"This is the link to the article"
"This new music video blew my mind"
Tweet sentiment ratings:
1: Positive
2: Negative
3: Positive
4: Neutral
5: Positive

###
Tweet text

"I can't stand homework"
"This sucks. I'm bored 😠"
"I can't wait for Halloween!!!"
"My cat is adorable ❤️❤️"
"I hate chocolate"

Tweet sentiment ratings:

1.

import os
import openai

openai.api_key = os.getenv("OPENAI_API_KEY")

response = openai.Completion.create(
  engine="davinci",
  prompt="This is a tweet sentiment classifier\n\nTweet: \"I loved the new Batman movie!\"\nSentiment: Positive\n###\nTweet: \"I hate it when my phone battery dies\"\nSentiment: Negative\n###\nTweet: \"My day has been 👍\"\nSentiment: Positive\n###\nTweet: \"This is the link to the article\"\nSentiment: Neutral\n###\n\nTweet text\n1. \"I loved the new Batman movie!\"\n2. \"I hate it when my phone battery dies\"\n3. \"My day has been 👍\"\n4. \"This is the link to the article\"\n5. \"This new music video blew my mind\"\n\nTweet sentiment ratings:\n1: Positive\n2: Negative\n3: Positive\n4: Neutral\n5: Positive\n\n###\n\nTweet text\n1. \"I can't stand homework\"\n2. \"This sucks. I'm bored 😠\"\n3. \"I can't wait for Halloween!!!\"\n4. \"My cat is adorable ❤️❤️\"\n5. \"I hate chocolate\"\n\nTweet sentiment ratings:\n1.",
  temperature=0.2,
  max_tokens=64,
  top_p=1,
  frequency_penalty=0,
  presence_penalty=0,
  stop=["###"]
)

Generation

結構これがすごい.

  • APIにいくつかのストーリーのアイデアのリストを与えると、そのリストに追加しようとする
教育とバーチャルリアリティに関するアイデア

1. 仮想火星
学生はバーチャルリアリティを介して火星を探索し、見たものを収集してカタログ化するミッションに進みます。

2.

import os
import openai

openai.api_key = os.getenv("OPENAI_API_KEY")

response = openai.Completion.create(
  engine="davinci",
  prompt="Ideas involving education and virtual reality\n\n1. Virtual Mars\nStudents get to explore Mars via virtual reality and go on missions to collect and catalog what they see.\n\n2.",
  temperature=0.7,
  max_tokens=64,
  top_p=1,
  frequency_penalty=0,
  presence_penalty=0
)

Conversation

最低限で動かすならこれでもいいが,これは不十分な例.

以下はAIアシスタントとの会話です。アシスタントは親切で、創造的で、賢く、そしてとてもフレンドリーです。

人間:こんにちは、あなたは誰ですか?

AI:私はOpenAIによって作成されたAIです。今日はなんか手伝うことある?

人間: 
  • APIに会話をしてくださいということだけではなく,動作方法も伝える
  • API側の名前をAIではなく,現実に存在した専門家の名前にする

上記を考慮するとより適切にはこのような例になる.

Marvは、しぶしぶ質問に答えるチャットボットです。

###

ユーザー:1キログラムは何ポンドですか?

マーブ:これも?キログラムには2.2ポンドあります。これをメモしてください。

###

ユーザー:HTMLは何の略ですか?

Marv:Googleは忙しすぎましたか?ハイパーテキストマークアップ言語。Tは、将来、より良い質問をしようとするためのものです。

###
ユーザー:最初の飛行機が飛ぶのですか?

マーヴ:1903年12月17日、ウィルバーとオーヴィルライトが初飛行を行いました。彼らが来て私を連れ去ってくれたらいいのにと思います。

###

ユーザー:宇宙で最初の人は誰でしたか?

マーブ: 
import os
import openai

openai.api_key = os.getenv("OPENAI_API_KEY")

response = openai.Completion.create(
  engine="davinci",
  prompt="Marv is a chatbot that reluctantly answers questions.\n\n###\nUser: How many pounds are in a kilogram?\nMarv: This again? There are 2.2 pounds in a kilogram. Please make a note of this.\n###\nUser: What does HTML stand for?\nMarv: Was Google too busy? Hypertext Markup Language. The T is for try to ask better questions in the future.\n###\nUser: When did the first airplane fly?\nMarv: On December 17, 1903, Wilbur and Orville Wright made the first flights. I wish they’d come and take me away.\n###\nUser: Who was the first man in space?\nMarv:",
  temperature=0.8,
  max_tokens=64,
  top_p=1,
  frequency_penalty=0,
  presence_penalty=0,
  stop=["###"]
)

Translation

モデルの学習済みのデータを使えるのでこれでいい

English: I do not speak French.

French: Je ne parle pas français.

English: See you later!

French: À tout à l'heure!

English: Where is a good restaurant?

French: Où est un bon restaurant?

English: What rooms do you have available?

French: Quelles chambres avez-vous de disponible?

English:
import os
import openai

openai.api_key = os.getenv("OPENAI_API_KEY")

start_sequence = "\nFrench:"
restart_sequence = "\n\nEnglish: "

response = openai.Completion.create(
  engine="davinci",
  prompt="English: I do not speak French.\nFrench: Je ne parle pas français.\n\nEnglish: See you later!\nFrench: À tout à l'heure!\n\nEnglish: Where is a good restaurant?\nFrench: Où est un bon restaurant?\n\nEnglish: What rooms do you have available?\nFrench: Quelles chambres avez-vous de disponible?\n\nEnglish: ",
  temperature=0.5,
  max_tokens=100,
  top_p=1,
  frequency_penalty=0,
  presence_penalty=0,
  stop=["\n"]
)

似たような例でこれでもいい.

Back to Future: 👨👴🚗🕒

Batman: 🤵🦇

Transformers: 🚗🤖

Wonder Woman: 👸🏻👸🏼👸🏽👸🏾👸🏿

Spider-Man: 🕸🕷🕸🕸🕷🕸

Winnie the Pooh: 🐻🐼🐻

The Godfather: 👨👩👧🕵🏻‍♂️👲💥

Game of Thrones: 🏹🗡🗡🏹

Spider-Man:
import os
import openai

openai.api_key = os.getenv("OPENAI_API_KEY")

response = openai.Completion.create(
  engine="davinci",
  prompt="Back to Future: 👨👴🚗🕒\n\nBatman: 🤵🦇\n\nTransformers: 🚗🤖\n\nWonder Woman: 👸🏻👸🏼👸🏽👸🏾👸🏿\n\nWinnie the Pooh: 🐻🐼🐻\n\nThe Godfather: 👨👩👧🕵🏻‍♂️👲💥\n\nGame of Thrones: 🏹🗡🗡🏹\n\nSpider-Man:",
  temperature=0.7,
  max_tokens=64,
  top_p=1,
  frequency_penalty=0,
  presence_penalty=0
)

Summarization

  • APIは、テキストのコンテキストを把握し、さまざまな方法で言い換えることが可能
My ten-year-old asked me what this passage means:

"""

A neutron star is the collapsed core of a massive supergiant star, which had a total mass of between 10 and 25 solar masses, possibly more if the star was especially metal-rich.[1] Neutron stars are the smallest and densest stellar objects, excluding black holes and hypothetical white holes, quark stars, and strange stars.[2] Neutron stars have a radius on the order of 10 kilometres (6.2 mi) and a mass of about 1.4 solar masses.[3] They result from the supernova explosion of a massive star, combined with gravitational collapse, that compresses the core past white dwarf star density to that of atomic nuclei.

"""

I rephrased it for him, in plain language a ten-year-old can understand:

"""
  • 要約したい対象をトリプルクオートで囲むのがコツ
import os
import openai

openai.api_key = os.getenv("OPENAI_API_KEY")

response = openai.Completion.create(
  engine="davinci",
  prompt="My ten-year-old asked me what this passage means:\n\"\"\"\nA neutron star is the collapsed core of a massive supergiant star, which had a total mass of between 10 and 25 solar masses, possibly more if the star was especially metal-rich.[1] Neutron stars are the smallest and densest stellar objects, excluding black holes and hypothetical white holes, quark stars, and strange stars.[2] Neutron stars have a radius on the order of 10 kilometres (6.2 mi) and a mass of about 1.4 solar masses.[3] They result from the supernova explosion of a massive star, combined with gravitational collapse, that compresses the core past white dwarf star density to that of atomic nuclei.\n\"\"\"\n\nI rephrased it for him, in plain language a ten-year-old can understand:\n\"\"\"",
  temperature=1,
  max_tokens=64,
  top_p=0.88,
  frequency_penalty=0,
  presence_penalty=0,
  stop=["\"\"\""]
)

tl;dr:を使って要約することもできる.

import os
import openai

openai.api_key = os.getenv("OPENAI_API_KEY")

response = openai.Completion.create(
  engine="davinci",
  prompt="Jupiter is the fifth planet from the Sun and the largest in the Solar System. It is a gas giant with a mass one-thousandth that of the Sun, but two-and-a-half times that of all the other planets in the Solar System combined. Jupiter is one of the brightest objects visible to the naked eye in the night sky, and has been known to ancient civilizations since before recorded history. It is named after the Roman god Jupiter.[19] When viewed from Earth, Jupiter can be bright enough for its reflected light to cast visible shadows,[20] and is on average the third-brightest natural object in the night sky after the Moon and Venus.\n\nJupiter is primarily composed of hydrogen with a quarter of its mass being helium, though helium comprises only about a tenth of the number of molecules. It may also have a rocky core of heavier elements,[21] but like the other giant planets, Jupiter lacks a well-defined solid surface. Because of its rapid rotation, the planet's shape is that of an oblate spheroid (it has a slight but noticeable bulge around the equator).\n\ntl;dr:",
  temperature=0.3,
  max_tokens=64,
  top_p=1,
  frequency_penalty=0,
  presence_penalty=0,
  stop=["\n"]
)
tl;dr: Jupiter is a gas giant, the largest planet in the solar system. It is the fifth planet from the Sun and the largest in the solar system. It is a gas giant with a mass one-thousandth that of the Sun, but two-and-a-half times that of all the other planets in

Completion

ある程度次に来るものが決まっている場合はこれが使える.

import os
import openai

openai.api_key = os.getenv("OPENAI_API_KEY")

response = openai.Completion.create(
  engine="davinci",
  prompt="```\nimport React from 'react';\nconst ThreeButtonComponent=()=>(\n<div>\n<p>Button One</p>\n<button className=\"button-green\" onClick={this.handleButtonClick}>Button One</button>\n<p>Button Two</p>\n<button className=\"button-green\" onClick={this.handleButtonClick}>Button Two</button>\n<p>Button Three</p>\n<button className=\"button-green\" onClick={this.handleButtonClick}>Button Three</button>\n</div>\n)\n''''\nimport React from 'react';\nconst HeaderComponent=()=>(",
  temperature=0.7,
  max_tokens=64,
  top_p=1,
  frequency_penalty=0,
  presence_penalty=0
)

自動で

<div>
<h1>Header</h1>
</div>

を追加してくれる

import os
import openai

openai.api_key = os.getenv("OPENAI_API_KEY")

response = openai.Completion.create(
  engine="davinci",
  prompt="Vertical farming provides a novel solution for producing food locally, reducing transportation costs and",
  temperature=0.29,
  max_tokens=64,
  top_p=1,
  frequency_penalty=0,
  presence_penalty=0
)

生成されるものはこちら

(Vertical farming provides a novel solution for producing food locally, reducing transportation costs and) energy use, and reducing the environmental impact of agriculture.

The vertical farm is a controlled environment where crops are grown indoors, usually in stacked layers.

The vertical farm is a controlled environment where crops are grown indoors, usually in stacked layers.

Vertical farming provides a novel solution for producing food locally

Factual responses

  • Wikipediaの記事のようなものをそのまま渡すとQAの流れを理解しないので会話形式が良い
  • 低い割合でわららないという例を入れておく
Q:バットマンとは誰ですか?

A:バットマンは架空の漫画のキャラクターです。

###

Q:torsalplexityとは何ですか?
A:?
###
Q:Devz9とは何ですか?
A:?
###
Q:ジョージ・ルーカスとは誰ですか?
A:ジョージ・ルーカスは、スターウォーズの作成で有名なアメリカの映画監督兼プロデューサーです。
###
Q:カリフォルニアの首都はどこですか?
A:サクラメント。
###
Q:地球を周回するのは何ですか?
A:月。
###
Q:フレッドリッカーソンとは誰ですか?
A:?
###
Q:アトムとは何ですか?
A:原子は、すべてを構成する小さな粒子です。
###
Q:Alvan Muntzとは誰ですか?
A:?
###
Q:Kozar-09とは何ですか?
A:?
###
Q:火星にはいくつの衛星がありますか?
A:2つ、フォボスとデイモス。
###
Q:
import os
import openai

openai.api_key = os.getenv("OPENAI_API_KEY")

response = openai.Completion.create(
  engine="davinci",
  prompt="Q: Who is Batman?\nA: Batman is a fictional comic book character.\n###\nQ: What is torsalplexity?\nA: ?\n###\nQ: What is Devz9?\nA: ?\n###\nQ: Who is George Lucas?\nA: George Lucas is American film director and producer famous for creating Star Wars.\n###\nQ: What is the capital of California?\nA: Sacramento.\n###\nQ: What orbits the Earth?\nA: The Moon.\n###\nQ: Who is Fred Rickerson?\nA: ?\n###\nQ: What is an atom?\nA: An atom is a tiny particle that makes up everything.\n###\nQ: Who is Alvan Muntz?\nA: ?\n###\nQ: What is Kozar-09?\nA: ?\n###\nQ: How many moons does Mars have?\nA: Two, Phobos and Deimos.\n###\nQ:\n",
  temperature=0,
  max_tokens=64,
  top_p=1,
  frequency_penalty=0,
  presence_penalty=0,
  stop=["###"]
)

8
14
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
14