url: https://www.bilibili.com/video/BV1Z14y1Z7LJ?spm_id_from=333.788.videopod.episodes&vd_source=7a1a0bc74158c6993c7355c5490fc600&p=2
別人的筆記 url: https://zhuanlan.zhihu.com/p/626966526
5. 推理任務(Inferring)
這個視頻是關于推理的。我喜歡把這些任務看成是模型將文本作為輸入并進行某種分析。這可以是提取標簽,提取名字,理解文本的情感,等等。
5.1 文本情緒分類
如果你想對一段文本提取正面或負面的情緒,在傳統的機器學習工作流程中,你必須收集標簽數據集,訓練一個模型,將模型部署在云端的某個地方,并進行推斷。這種方法可以很好地工作,但這個過程需要做很多費力的工作。此外,對于每一項任務,例如情感分析、提取姓名或其他任務,你都必須為其訓練和部署一個單獨的模型。
大型語言模型的好處是,對于許多這樣的任務,你只需要編寫一個提示,就可以讓它馬上生成結果,這極大地加快了應用程序開發的速度。而且你可以只使用一個模型、一個API來執行許多不同的任務,而不需要搞清楚如何訓練和部署許多不同的模型。
讓我們進入代碼中,看看如何利用這個優勢。
這里是我們常用迭的初始代碼。運行初始化代碼。
import openai
import os
from openai import OpenAI# 1. 根據環境變量獲取 openai key
from dotenv import load_dotenv, find_dotenv
_ = load_dotenv(find_dotenv())openai.api_key = os.getenv('OPENAI_API_KEY') client = OpenAI()# 2. 定義 get_completion 方法
def get_completion(prompt, instructions=None, model="gpt-3.5-turbo"):response = client.responses.create(model=model,instructions=instructions,input=prompt,temperature=0, # this is the degree of randomness of the model's output)return response.output_text
我使用的最多的例子是關于一盞燈的評論。臥室里需要一盞漂亮的燈,和額外的儲物空間,等等。
lamp_review = """
Needed a nice lamp for my bedroom, and this one had \
additional storage and not too high of a price point. \
Got it fast. The string to our lamp broke during the \
transit and the company happily sent over a new one. \
Came within a few days as well. It was easy to put \
together. I had a missing part, so I contacted their \
support and they very quickly got me the missing piece! \
Lumina seems to me to be a great company that cares \
about their customers and products!!
"""
讓我寫一個提示,對這種情緒進行分類。如果我想讓系統告訴我這是什么情緒,我可以直接寫出提示“下面的產品評論的情緒是什么”,加上通常的分隔符和評論文本等等。
prompt = f"""
What is the sentiment of the following product review,
which is delimited with triple backticks?Review text: '''{lamp_review}'''
"""response = get_completion(prompt)print(response)
然后我們運行這個提示,結果如下。
The sentiment of the product review is positive.
這表明這條產品評論的情緒是積極的,這實際上很正確。這盞燈并不完美,但這位顧客似乎很滿意。這似乎是一家關心客戶和產品的偉大公司。我認為積極的情緒似乎是正確的答案。
現在這打印出了整句話,“產品評論的情緒是積極的”。
5.2 控制輸出的樣式
如果你想給出一個更簡潔的回答,以便后期處理,我可以在這個提示中添加另一條指令,用一個單詞給出答案,無論是正面的還是負面的。
prompt = f"""
What is the sentiment of the following product review,
which is delimited with triple backticks?Give your answer as a single word, either "positive" \
or "negative".Review text: '''{lamp_review}'''
"""
response = get_completion(prompt)
print(response)
那么它將像這樣只是打印出“陽性”,這樣的輸出更容易被接受和處理,便于用來做進一步的處理。
positive
讓我們看看另一個提示,仍然使用關于臺燈的評論。
在這里,我讓它給出這條評論的作者所表達的情緒列表,列表內容不超過五項。
prompt = f"""
Identify a list of emotions that the writer of the \
following review is expressing. Include no more than \
five items in the list. Format your answer as a list of \
lower-case words separated by commas.Review text: '''{lamp_review}'''
"""
response = get_completion(prompt)
print(response)
結果如下。
happy, satisfied, grateful, impressed, content
大型語言模型非常善于從一段文本中提取特定的內容。在這種情況下,我們要表達的是情緒,這有助于了解客戶對特定產品的看法。
對于許多客戶支持部門來說,了解特定用戶是否對產品感到非常不滿是很重要的工作。所以你可能會遇到類似這樣的不同的分類問題:“下面這條評論的作者是否在表達憤怒?”
prompt = f"""
Is the writer of the following review expressing anger?\
The review is delimited with triple backticks. \
Give your answer as either yes or no.Review text: '''{lamp_review}'''
"""
response = get_completion(prompt)
print(response)
結果如下。
No
如果有人真的很生氣,那么這條評論可能值得格外關注,需要為客戶提供支持或幫助,了解發生了什么事,并為客戶把事情做好。在這種情況下,客戶并不會生氣。請注意,如果使用監督學習,如果我想構建所有這些分類器,不可能在幾分鐘內完成監督學習。而現在就像你在視頻中所看到的,我可以快速地實現這個任務。
我鼓勵你暫停視頻,并嘗試更改其中的一些提示。也許可以詢問客戶是否表達了喜悅之情,或者詢問是否有任何缺失的零件,看看你是否能編寫一個提示,對這條臺燈評論進行不同的推理。
5.3 輸出 JSON 格式
讓我展示一下可以用這個系統做的更多事情,特別是從客戶評論中提取更豐富的信息。
信息提取是自然語言處理(NLP)的一部分,它涉及到提取一段文本,并從文本中提取你想知道的某些東西。
在這個提示中,我要求它提取以下信息:購買的物品和制造該物品的公司名稱。同樣,如果你試圖對一個網上購物電子商務網站上的大量評論進行總結,那么對于收集的大量評論來說,找出這些評論所涉及的商品可能會很有用。可以分析評論中的內容,找出涉及產品的制造商,推斷正面或負面的情緒,由此來跟蹤特定商品或特定制造商的正面或負面情緒的變化趨勢。
在這個例子中,我將要求它以 JSON 格式進行格式化的輸出 ,以 item 和 brand 作為關鍵字。
prompt = f"""
Identify the following items from the review text:
- Item purchased by reviewer
- Company that made the itemThe review is delimited with triple backticks. \
Format your response as a JSON object with \
"Item" and "Brand" as the keys.
If the information isn't present, use "unknown" \
as the value.
Make your response as short as possible.Review text: '''{lamp_review}'''
"""
response = get_completion(prompt)
print(response)
如果我這樣做,它會說這個 item 是一盞燈,brand 是 Luminar。
{"Item": "lamp","Brand": "Lumina"
}
于是,你可以很容易地將其加載到Python 字典中,然后對這個輸出結果進行另外的處理。
5.4 集成多個任務
在上面的例子中,你看到了如何寫一個提示來識別情緒,判斷客戶是否生氣,然后提取商品名稱和品牌。提取所有這些信息的方法是,使用 3 個或 4個提示,并調用 3次或 4次 get_completion 函數,每次提取一個不同的字段。
但是,實際上你可以只編寫一個提示來同時提取所有這些信息。例如,識別以下的項目:提取情緒,是否在表達憤怒,購買的商品,商品的制造商。然后,我還將要求它將憤怒情緒表示為布爾值的格式。
prompt = f"""
Identify the following items from the review text:
- Sentiment (positive or negative)
- Is the reviewer expressing anger? (true or false)
- Item purchased by reviewer
- Company that made the itemThe review is delimited with triple backticks. \
Format your response as a JSON object with \
"Sentiment", "Anger", "Item" and "Brand" as the keys.
If the information isn't present, use "unknown" \
as the value.
Make your response as short as possible.
Format the Anger value as a boolean.Review text: '''{lamp_review}'''
"""
response = get_completion(prompt)
print(response)
然后我運行它。這將輸出為 JSON 格式,其中情緒是正面的。憤怒,false 沒有加引號,因為輸出格式是布爾值。商品 item 被提取為“帶有額外存儲的燈”,而不僅僅是“燈”。看起來還不錯。
{"Sentiment": "positive","Anger": false,"Item": "lamp with additional storage","Brand": "Lumina"
}
通過這種方式,你只需要使用一個提示就可以從一段文本中提取多個字段。 像往常一樣,請隨時暫停視頻,自己嘗試修改不同的提示,甚至可以嘗試輸入完全不同的評論,看看你是否仍然可以準確地提取這些內容。
5.5 文本主題推斷
大型語言模型的一個酷炫的應用是推斷主題。
給定一段很長的文本,這段文本是關于什么的?有哪些主題? 這是一篇虛構的報紙文章,關于政府工作人員對他們所工作機構的感受,最近由政府進行了一項調查,結果是 NASA 是一個受歡迎的部門,滿意度很高。
story = """
In a recent survey conducted by the government,
public sector employees were asked to rate their level
of satisfaction with the department they work at.
The results revealed that NASA was the most popular
department with a satisfaction rating of 95%.One NASA employee, John Smith, commented on the findings,
stating, "I'm not surprised that NASA came out on top.
It's a great place to work with amazing people and
incredible opportunities. I'm proud to be a part of
such an innovative organization."The results were also welcomed by NASA's management team,
with Director Tom Johnson stating, "We are thrilled to
hear that our employees are satisfied with their work at NASA.
We have a talented and dedicated team who work tirelessly
to achieve our goals, and it's fantastic to see that their
hard work is paying off."The survey also revealed that the
Social Security Administration had the lowest satisfaction
rating, with only 45% of employees indicating they were
satisfied with their job. The government has pledged to
address the concerns raised by employees in the survey and
work towards improving job satisfaction across all departments.
"""
我是 NASA 的粉絲,我喜歡他們所做的工作,但這是一篇虛構的文章。對于這樣一篇文章,我們可以編寫這個提示,要求它確定以下文本中討論的五個主題,把每一項都寫成一到兩個單詞,表示為用逗號分隔的列表。
prompt = f"""
Determine five topics that are being discussed in the \
following text, which is delimited by triple backticks.Make each item one or two words long. Format your response as a list of items separated by commas.Text sample: '''{story}'''
"""response = get_completion(prompt)
print(response)
我們運行一下,就會得到這樣的結果:這篇文章是關于政府調查的,關于工作滿意度的,關于NASA 的,等等。
government survey, job satisfaction, NASA, Social Security Administration, employee concerns
所以,總的來說,我認為很好地提取了主題列表。當然,你也可以把這個輸出進行拆分,就可以得到,包含這篇文章所涉及的五個主題的 Python 列表。
response.split(sep=',')
結果如下。
['government survey', ' job satisfaction', ' NASA', ' Social Security Administration', ' employee concerns']
5.6 文本主題索引
如果你有一個文章的集合,并提取主題,那么還可以使用大型語言模型來幫助你索引不同的主題。
讓我使用一個稍微不同的主題列表。例如,我們是一個新聞網站或其他什么,這些都是我們跟蹤的話題,NASA,地方政府,工程,員工滿意度,聯邦政府。
topic_list = ["nasa", "local government", "engineering", "employee satisfaction", "federal government"
]
如果你想弄清楚,給定一篇新聞報道,這篇新聞涉及哪些主題。
我可以使用這樣一個提示:確定以下主題列表中的每個項目是否都是下面文本中的主題,將答案表示為每個主題的 0/1 的列表。
prompt = f"""
Determine whether each item in the following list of \
topics is a topic in the text below, which
is delimited with triple backticks.Give your answer as list with 0 or 1 for each topic.\List of topics: {", ".join(topic_list)}Text sample: '''{story}'''
"""
response = get_completion(prompt)
print(response)
這是和前面一樣的故事文本。這是關于 NASA 的,與地方政府無關,也與工程無關。這與員工滿意度有關,也與聯邦政府有關。
nasa: 1 local government: 0 engineering: 0 employee satisfaction: 1 federal government: 1
在機器學習中,這被稱為"零樣本學習算法“,因為我們沒有給它任何標記的訓練數據。所以,這就是零樣本。只需要一個提示,它就可以確定這篇新聞報道涉及了哪些主題。
5.7 主題內容提醒
如果你想生成一個新聞警報,就可以這樣處理新聞。你知道,我真的很喜歡 NASA 做的很多工作。所以,如果你想建立一個系統,可以把這些信息放進字典里,每當 NASA 的新聞出現,就打印輸出進行提醒。可以用這個提示快速地提取任何文章,分析它是關于什么主題的,如果這個主題包括 NASA,讓它打印提醒:新的 NASA 新聞。
# 源代碼,依賴于輸出 "nasa: 1 local government: 0 engineering: 0 employee satisfaction: 1 federal government: 1"
# 但這個輸出并不魯棒,所以注釋掉
# topic_dict = {i.split(': ')[0]: int(i.split(': ')[1]) for i in response.split(sep='\n')}# if topic_dict['nasa'] == 1:
# print("ALERT: New NASA story!") response = [1, 0, 0, 1, 1]
# 之前的代碼定義了 topic_list
# topic_list = [
# "nasa", "local government", "engineering",
# "employee satisfaction", "federal government"
# ] topic_dict = { topic_list[i] : response[i] for i in range(len(topic_list)) }if topic_dict['nasa'] == 1:print("ALERT: New NASA story!")
需要指出的是,我在這里使用的提示中的字典格式,并不是很魯棒。如果我要建立一個生產系統,我會讓它以 JSON 格式而不是列表的形式輸出答案,因為大型語言模型的輸出可能有點不一致。所以,這實際上是一段非常脆弱的代碼。但是,如果你想的話,當你看完這段視頻后,可以看看你是否能修改這個提示,讓它輸出 JSON 格式,而不是像這樣的列表,然后有一個更魯棒的方法來判斷一篇文章是否是關于 NASA 的故事。
ALERT: New NASA story!
5.8 小結
這就是推理的方法。只需要短短的幾分鐘,你就可以構建多個系統來對文本進行推理。而以前對于一個熟練的機器學習開發人員來說,這樣的工作也需要花費幾天甚至幾周的時間才能完成。
我認為無論是對熟練的機器學習開發人員還是對機器學習新手來說,這都是非常令人興奮的事情。你現在可以使用提示來非常快速地構建并開始,對這些非常復雜的自然語言處理任務進行推理。
在下一個視頻中,我們將繼續討論大型語言模型令人興奮的事情。轉換任務,如何將一段文本轉換為不同的文本,例如翻譯成不同的語言?讓我們繼續看下一個視頻。