(done) 吴恩达版提示词工程 5. 推理 (情绪分类,控制输出格式,输出 JSON,集成多个任务,文本主题推断和索引,主题内容提醒)
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 小结
这就是推理的方法。只需要短短的几分钟,你就可以构建多个系统来对文本进行推理。而以前对于一个熟练的机器学习开发人员来说,这样的工作也需要花费几天甚至几周的时间才能完成。
我认为无论是对熟练的机器学习开发人员还是对机器学习新手来说,这都是非常令人兴奋的事情。你现在可以使用提示来非常快速地构建并开始,对这些非常复杂的自然语言处理任务进行推理。
在下一个视频中,我们将继续讨论大型语言模型令人兴奋的事情。转换任务,如何将一段文本转换为不同的文本,例如翻译成不同的语言?让我们继续看下一个视频。