Chapter 30
2. 思维链和自我一致性
第二章 思维链和自我一致性
一、引言
2021 年,提示学习(Prompt Learning)的研究浪潮兴起。而早在 2020 年,OpenAI 在 NeurIPS 2020 发表的一篇论文 Language Models are Few-Shot Learners 中就已经探讨了如何利用提示学习来提升大语言模型(Large Language Models, LLMs)的推理能力。论文中介绍了 Zero-shot、One-shot、Few-shot 三种不同的提示方法,如下图示意。
在提示学习中,Zero-shot、One-shot 和 Few-shot 三者之间的差异为:
-
Zero-shot 学习指的是模型在没有看到任何具体示例的情况下,直接对未知类别进行分类或执行任务的能力。在这种情况下,模型仅依赖于其在训练过程中获得的知识和泛化能力。对于提示学习来说,Zero-shot 场景通常意味着你会给模型一个任务描述或一个问题,但不提供任何具体的示例作为参考。模型需要根据其先前的知识和理解来生成答案。
-
One-shot 学习是指模型在看到一个(或每类一个)具体示例后,就能够执行某项任务或识别新类别的能力。这意味着模型通过观察单一实例就能够学习新概念或任务。在提示学习中,这通常涉及到向模型展示一个示例(包括问题和答案),然后立即要求它处理一个类似但不同的问题。这要求模型能够从极少量的数据中迅速学习并泛化。
-
Few-shot 学习与 One-shot 学习类似,指的是模型在看到少量(通常是几个而非一个,但远少于传统机器学习项目中使用的样本数量)示例后执行任务的能力。这种方法允许模型通过观察几个示例来更好地理解新任务或类别。在提示学习框架下,这意味着你会给模型提供几个相关问题及其答案作为示例,然后让它处理新问题。
小结:Zero-shot、One-shot 和 Few-shot 学习代表了 LLM 处理未知任务时依赖已有知识量级的不同阶段。Zero-shot 依赖于模型的泛化能力;One-shot 要求模型能从单一实例中快速学习;而 Few-shot 则提供了稍微多一些的示例来帮助模型适应新任务。提示学习作为一种灵活的方法,在所有这三种情况下都非常有用,因为它允许研究人员以自然语言形式直接与模型交互,从而更容易地引导模型理解和执行新任务。
然而,即使是 Few-shot 提示方法,也存在一些缺陷。对于一些相对简单且无需逻辑推理的问题,LLM 可能通过检索其参数化知识来得出答案,从而表现出色。然而,对于一些不太复杂但需要推理的问题,例如简单的算术应用题,LLM 往往表现不佳。因此,思维链(Chain-of-Thought,CoT) 方法应运而生。
本章将详细阐述思维链提示、零样本思维链和自我一致性的基础理论。我们通过深入解析关键原理和提供实际代码示例,帮助读者全面理解和掌握思维链以及自我一致性的应用。阅读完本章后,读者将能够专业且准确地理解并应用思维链和自我一致性。
二、CoT 提示方法与代码示例
注意:我使用的测试环境是 UV + Python3.12+。Python 的版本要求 Python3.12+。
开始实验之前,我们需要按照Env-Setup.md中,安装好依赖环境。OpenAI Python 库提供了一个便捷的途径,让任何 Python 3.12+ 应用程序可以访问 OpenAI REST API。
导入此次实验所需的依赖库(原版本使用的是OPENAI,以下我们采用硅基流动的API)
import os
from openai import OpenAI
from dotenv import load_dotenv, find_dotenv
from IPython.display import Markdown
loaded = load_dotenv(find_dotenv(), override=True)
# 从环境变量中获取 OpenAI API Key 或者直接赋值
API_KEY = os.getenv("API_KEY")
# 如果您使用的是官方 API,就直接用 https://api.siliconflow.cn/v1 就行。
BASE_URL = "https://api.siliconflow.cn/v1"
# 如果您使用的不是官方 API,而是通过代理进行请求,请设置您的代理 URL。
# BASE_URL = "https://api.xxx.../v1"# 实例化 OpenAI 对象
# 传入参数:OpenAI API Key(必需)、Base URL 和最大重试次数
client = OpenAI(api_key=API_KEY, base_url=BASE_URL, max_retries=3)# 参数 n,整数或 Null,可选项,默认为 1。为每条输入信息生成多少个聊天完成选项。
# 参数 temperature,实数值或 Null,可选项,默认为 1。使用的采样温度,介于 0 和 2 之间。0.8 等较高值会使输出更加随机,而 0.2 等较低值会使输出更加集中和确定。
def get_completions(llm_prompt, model_endpoint):
extra_body = {}
if "Qwen3" in model_endpoint:
extra_body={
"enable_thinking": False
}
response = client.chat.completions.create(model=model_endpoint,
messages=[
{"role": "user",
"content": llm_prompt
}
],
n=1, temperature=0, seed=42,
presence_penalty=0, frequency_penalty=0,
max_tokens=512, extra_body = extra_body
)
return response.choices[0].message.content.strip()2.1 思维链提示过程
思维链(Chain-of-Thought,CoT)的本质是一种离散式提示学习。OpenAI 在 NeurIPS 2022 发表的一篇论文 Chain-of-Thought Prompting Elicits Reasoning in Large Language Models 探索了如何生成思维链:一系列中间推理步骤,显著提高了 LLM 执行复杂推理的能力。该论文特别展示了,通过一种称为 “思维链提示” 的简单方法,这种推理能力可以在足够大的语言模型中自然地出现。这种方法在提示中提供了一些思维链的示例,如下图示意:
对于特定的任务,我们需要设计一到多个思维链的示例以进行思维链推理,这实际上是上下文学习的应用。如下图所示,这是一些算术、常识和符号推理基准测试的输入、思维链、输出三元组的示例。
这里再提供 3 个简单的中文示例:
问:音乐会原定于 1943 年 6 月 1 日举行,但推迟了一天到今天。10 天前的日期(MM/DD/YYYY)是多少?
答:06/01/1943 后一天是 06/02/1943,所以今天是 06/02/1943。今天的前 10 天是 1943 年 5 月 23 日。所以答案是 05/23/1943。
问:输入 1 到 500 的数字需要击键多少次?答案选项:(a) 1156 (b) 1392 (c) 1480 (d) 1562 (e) 1788
答:1 到 9 有 9 个一位数。10 到 99 有 90 个两位数。100 到 500 有 401 个三位数。9 + 90(2) + 401(3) = 1392。答案是(b)。
问:把 "Lady Gaga" 中单词的最后一个字母连接起来。
答:"Lady" 的最后一个字母是 "y"。"Gaga" 的最后一个字母是 "a"。连接起来就是 "ya"。所以答案是 "ya"。思维链提示使 LLM 能够处理复杂的算术、常识和符号推理任务。在三个大语言模型(LLMs)上的实验结果表明,思维链提示可以显著提高这些任务的成绩。例如,在 GSM8K 数学单词问题基准测试中,仅用 8 个思维链示例提示 PaLM 540B,就达到了最先进的准确度,甚至超过了带有验证器的经过微调的 GPT-3。这种经验上的收获可能是惊人的。此外,模型通过思维链提示过程获得的性能提升可能与模型的大小成正比。
2.2 零样本思维链
Kojima 等人在 NeurIPS 2022 发表的一篇论文 Large Language Models are Zero-Shot Reasoners 提出了零样本思维链(Zero-shot Chain of Thought,Zero-shot-CoT)提示是对上述的思维链提示的进一步研究,它引入了一种简洁的零样本提示方法。如下图所示,研究人员发现,通过在问题的结尾添加 "Let's think step by step." 这个提示,LLM 可以生成一个解答问题的思维链。从这个思维链中,LLM 能够更准确地进行推理。
从技术角度看,完整的零样本思维链过程包含两个独立的提示补全结果。在下图中,左侧的顶部气泡形成了一个思维链,右侧的顶部气泡则接收了第一个提示(包括提示本身)的输出,并从思维链中抽取出答案。第二个提示是一个自我增强的提示。
零样本思维链在改善算术、常识和符号推理任务的结果方面也表现出了有效性。然而,它有时候可能不如思维链提示过程那么有效。由于提取步骤通常需要针对特定任务,因此零样本思维链的泛化能力并不是那么强。Kojima 等人尝试了多种不同的零样本思维链提示,如 “让我们分步解决这个问题(Let's solve this problem by splitting it into steps.)” 或 “让我们从逻辑上思考一下(Let's think about this logically.)”,但他们发现 “让我们一步一步地思考(Let's think step by step.)” 对他们选定的任务最为有效。感兴趣的读者可以参阅论文中的实验分析。
因此,当面临复杂问题或者难以获取思维链提示过程的示例时,零样本思维链可以发挥其作用。
在问题后面加上 "Let's think step by step." (让我们一步一步地思考。)这个提示可以自动激发思维链过程。
以一个算术问题为例,展示直接提问、带 1-shot 演示的思维链提示过程和零样本思维链的生成结果。
# 在 Python 中生成 Markdown 表格可以通过使用字符串拼接和格式化的方法来实现。
# 以下是一个用于生成 Markdown 表格的示例代码:
def generate_markdown_table(headers, rows):
table = "| " + " | ".join(headers) + " |\n"
table += "| " + " | ".join(["---"] * len(headers)) + " |\n"
for row in rows:
table += "| " + " | ".join(row) + " |\n"
return table# 我们使用 Qwen/Qwen3-8B
llm = "Qwen/Qwen3-8B"
# 直接提问
prompt1 = f"""问:输入 1 到 1200 的数字需要击键多少次?不要输出其他格式
答:
"""
# 带 1-shot 演示的思维链推理
prompt2 = f"""问:输入 1 到 500 的数字需要击键多少次?不要输出其他格式
答:1-9 之间有 9 个数字,每个数字按一次键,共需 9 次键。10-99 之间有 90 个数字,每个数字按两次键,共需 180 次键。100-500 之间有 401 个数字,每个数字按三次键,共需 1203 次键。将这些数字相加,得到总共需要按键的次数为 9 + 180 + 1203 = 1392 次。
问:输入 1 到 1200 的数字需要击键多少次?
答:
"""
# 零样本思维链推理
prompt3 = f"""问:输入 1 到 1200 的数字需要击键多少次?不要输出其他格式
答:让我们一步一步地思考。
"""
result1 = get_completions(prompt1, llm)
result2 = get_completions(prompt2, llm)
result_CoT = get_completions(prompt3, llm)
prompt_and_CoT = prompt3 + result_CoT + "所以,最终答案是:"
result3 = get_completions(prompt_and_CoT, llm)
headers = ["直接提问 \u274c", "带 1-shot 演示的思维链推理 \u2705", "零样本思维链推理 \u2705"]
rows = [[result1.replace("\n", ""),
result2.replace("\n", ""),
result_CoT.replace("\n", "") + "所以,最终答案是:" + result3
],
]
markdown_table = generate_markdown_table(headers, rows)
display(Markdown(markdown_table))Output
<IPython.core.display.Markdown object>
中文 Prompt 输入:直接提问的推理过程有部分是错的,导致最终生成的答案不准确,产生了 “幻觉” 问题。带 1-shot 演示的思维链推理和零样本思维链推理的推理过程和生成答案都是正确的。
llm = "Qwen/Qwen3-8B"
# 接下来是英文 Prompt
# 直接提问
prompt1 = f"""Q: How many keystrokes are needed to type the numbers from 1 to 1200? no more other formats
A:
"""
# 带 1-shot 演示的思维链推理
prompt2 = f"""Q: How many keystrokes are needed to type the numbers from 1 to 500? no more other formats
A: To type the numbers from 1 to 9, we need 9 keystrokes (1, 2, 3, 4, 5, 6, 7, 8, 9). To type the numbers from 10 to 99, we need 90 * 2 keystrokes (10-99 = 90 numbers, each number requires 2 keystrokes). To type the numbers from 100 to 500, we need 401 * 3 keystrokes (100-500 = 401 numbers, each number requires 3 keystrokes). Adding all these up, we get: 9 + 90 * 2 + 401 * 3 = 1392 keystrokes.
Q: How many keystrokes are needed to type the numbers from 1 to 1200?
A:
"""
# 零样本思维链推理
prompt3 = f"""Q: How many keystrokes are needed to type the numbers from 1 to 1200? no more other formats
A: Let's think step by step.
"""
result1 = get_completions(prompt1, llm)
result2 = get_completions(prompt2, llm)
result_CoT = get_completions(prompt3, llm)
prompt_and_CoT = prompt3 + result_CoT + "Therefore, the final answer is: "
result3 = get_completions(prompt_and_CoT, llm)
headers = ["直接提问 \u274c", "带 1-shot 演示的思维链推理 \u2705", "零样本思维链推理 \u274c"]
rows = [[result1.replace("\n", " "),
result2.replace("\n", " "),
result_CoT.replace("\n", " ") + " Therefore, the final answer is: " + result3
],
]
markdown_table = generate_markdown_table(headers, rows)
display(Markdown(markdown_table))Output
<IPython.core.display.Markdown object>
英文 Prompt 输入:直接提问的推理过程有部分是错的,导致最终生成的答案不准确,产生了 “幻觉” 问题。零样本思维链推理的推理过程有部分是错的,导致最终生成的答案不准确,也产生了 “幻觉” 问题。零样本思维链推理差一点就能推理正确,只是有一处的推理是错的:"To type the numbers from 1000 to 1200, it would take 603 keystrokes (1000-1200 = 201 numbers, each number requires 4 keystrokes)."。只有带 1-shot 演示的思维链推理的推理过程和生成答案是正确的。零样本思维链的泛化能力并不是那么强,有时候可能不如思维链提示过程那么有效。
此外,实践经验表明,零样本思维链提示有时可以有效地增加生成内容的长度。例如,我们可以考虑一个标准的提示:“数据科学与机器学习之间有什么联系?”
如果在这个提示的末尾添加 “让我们一步一步地思考(Let's think step by step.)”,那么生成的补全结果可能会更长,而且质量可能会更好。代码示例和结果如下:
# 改造一下获得 Completions 的函数,实现返回消耗的 tokens 数量
def get_completions(system_instruction, llm_prompt, model_endpoint):
extra_body = {}
if "Qwen3" in model_endpoint:
extra_body={
"enable_thinking": False
}
response = client.chat.completions.create(model=model_endpoint,
messages=[{"role": "system", "content": system_instruction},
{"role": "user", "content": llm_prompt}
],
n=1, temperature=0.30, seed=42,
presence_penalty=0, frequency_penalty=0,
max_tokens=1024, extra_body = extra_body
)
return response.choices[0].message.content.strip(), response.usagellm = "Qwen/Qwen3-8B"
system_instruction = "您是世界知识专家。"
prompt_standard = "数据科学与机器学习之间有什么联系?"
prompt_cot = "数据科学与机器学习之间有什么联系?让我们一步一步地思考。"
result_standard, tokens_count = get_completions(system_instruction, prompt_standard, llm)
print("-" * 88)
print(f"生成结果-中文-标准提示:\n{result_standard}\n")
print(f"提示的 tokens: {tokens_count.prompt_tokens} \t 补全的 tokens: {tokens_count.completion_tokens}")
print("-" * 88)
result_cot, tokens_count = get_completions(system_instruction, prompt_cot, llm)
print(f"生成结果-中文-零样本思维链:\n{result_cot}\n")
print(f"提示的 tokens: {tokens_count.prompt_tokens} \t 补全的 tokens: {tokens_count.completion_tokens}")
print("-" * 88)Output
---------------------------------------------------------------------------------------- 生成结果-中文-标准提示: 数据科学与机器学习之间有着紧密的联系,它们在很多方面相互依赖、相互促进。下面我将从定义、核心内容、应用场景和相互关系四个方面来详细说明它们之间的联系。 --- ## 一、定义上的联系 ### 1. **数据科学(Data Science)** 数据科学是一门跨学科领域,结合了统计学、计算机科学、领域知识和数据分析技术,旨在从数据中提取有价值的信息、洞察和知识,用于支持决策、预测趋势和优化系统。 ### 2. **机器学习(Machine Learning)** 机器学习是人工智能的一个分支,专注于开发算法和模型,使计算机能够从数据中“学习”并做出预测或决策,而无需显式编程。它是一种数据科学中的核心技术。 --- ## 二、核心内容上的联系 ### 1. **数据科学依赖机器学习** 数据科学的许多任务,如预测、分类、聚类、推荐等,都需要使用机器学习算法来实现。例如: - **预测分析**:使用回归、时间序列模型等; - **模式识别**:使用分类、聚类等机器学习方法; - **自然语言处理(NLP)**:是数据科学在文本数据中的应用,而NLP本身依赖于机器学习模型。 ### 2. **机器学习是数据科学的一部分** 机器学习是数据科学中用于建模和预测的核心工具之一。数据科学家通常会使用机器学习技术来构建预测模型、优化决策系统、发现隐藏模式等。 --- ## 三、应用场景上的联系 ### 1. **数据科学的应用场景** - 商业分析(如客户细分、市场预测) - 金融风控(如信用评分、欺诈检测) - 医疗健康(如疾病预测、影像识别) - 社交媒体分析(如用户行为预测、内容推荐) - 智能推荐系统(如电商推荐、视频推荐) ### 2. **机器学习的应用场景** - 图像识别(如人脸识别、医学影像分析) - 自然语言处理(如情感分析、机器翻译) - 预测模型(如天气预测、股票预测) - 语音识别(如语音助手、语音搜索) - 自动驾驶(如目标检测、路径规划) 可以看到,机器学习是数据科学在实际应用中的重要手段,而数据科学为机器学习提供了数据处理、特征工程、模型评估等支持。 --- ## 四、相互关系 | 数据科学 | 机器学习 | |----------|----------| | 数据收集、清洗、存储、可视化 | 数据建模、算法训练、预测、分类 | | 依赖统计学、编程、领域知识 | 依赖数学、算法、计算能力 | | 用于发现数据中的模式和趋势 | 用于构建自动化的预测和决策系统 | | 是机器学习的“应用层” | 是数据科学的“核心技术层” | | 通常使用机器学习技术 | 是数据科学的重要组成部分 | --- ## 五、总结 数据科学与机器学习是相辅相成的关系: - **数据科学**是更广泛的概念,涵盖数据的整个生命周期,包括数据收集、处理、分析、建模和应用; - **机器学习**是数据科学中用于建模和预测的核心技术,是实现数据价值转化的关键手段。 可以说,**机器学习是数据科学的一个子领域**,而**数据科学是机器学习的应用场景和支撑体系**。两者共同推动了人工智能、大数据、智能系统等前沿技术的发展。 --- 如果你有更具体的问题,比如想了解它们在某个行业中的应用,或者想比较它们的工具和方法,我也可以进一步为你解答。 提示的 tokens: 32 补全的 tokens: 770 ---------------------------------------------------------------------------------------- 生成结果-中文-零样本思维链: 数据科学与机器学习之间有着紧密的联系,它们在很多方面相互依赖、相互促进。我们可以从以下几个方面逐步思考它们之间的关系: --- ### 第一步:理解什么是数据科学? **数据科学**是一门跨学科的领域,结合了统计学、计算机科学、数学、领域知识等,旨在从数据中提取有价值的信息、洞察和知识。它的核心目标是通过分析数据来帮助决策、预测趋势、发现模式、优化流程等。 数据科学的流程通常包括以下几个步骤: 1. **数据收集**:获取原始数据。 2. **数据清洗**:处理缺失值、异常值、格式错误等。 3. **数据探索**:使用统计方法和可视化工具分析数据。 4. **建模**:使用数学模型或算法对数据进行处理。 5. **模型评估与优化**:验证模型的性能并进行调整。 6. **部署与应用**:将模型用于实际业务场景中。 --- ### 第二步:理解什么是机器学习? **机器学习**是数据科学的一个重要分支,专注于让计算机系统通过学习数据中的模式,自动改进其性能,而无需显式编程。它是一种让计算机从数据中“学习”并做出预测或决策的技术。 机器学习的核心是**算法**,这些算法可以分为以下几类: - **监督学习**(如线性回归、决策树、支持向量机、神经网络等) - **无监督学习**(如聚类、降维、关联规则挖掘等) - **强化学习**(如Q-learning、深度强化学习等) - **半监督学习** 和 **自监督学习** 机器学习的目标是构建一个模型,该模型能够从训练数据中学习,并在新的、未见过的数据上做出准确的预测或分类。 --- ### 第三步:找出两者的联系 我们可以从以下几个角度来理解数据科学与机器学习之间的联系: #### 1. **机器学习是数据科学的重要工具** - 数据科学需要处理大量数据,而机器学习提供了强大的工具和算法来从这些数据中提取有用的信息。 - 例如,数据科学家会使用机器学习算法来进行预测建模、分类、聚类等任务。 #### 2. **数据科学为机器学习提供数据基础** - 机器学习依赖于高质量的数据来进行训练和预测。 - 数据科学负责数据的收集、清洗、预处理和特征工程,为机器学习模型提供输入。 #### 3. **两者的目标相似** - 数据科学的目标是通过数据驱动的方式解决问题,而机器学习的目标是通过算法让计算机“学习”并做出预测或决策。 - 两者都关注如何从数据中发现模式、做出预测、优化系统等。 #### 4. **机器学习是数据科学的一个子领域** - 数据科学是一个更广泛的领域,而机器学习是其中的一个重要组成部分。 - 数据科学可能包括数据可视化、数据挖掘、数据库管理、统计分析等,而机器学习专注于模型的构建和训练。 #### 5. **两者在实际应用中常常结合使用** - 在实际项目中,数据科学家通常会使用机器学习技术来解决具体的问题。 - 例如,金融行业使用机器学习进行信用评分,医疗行业使用机器学习进行疾病预测,电商行业使用机器学习进行推荐系统等。 --- ### 第四步:举例说明两者的联系 #### 例子1:客户流失预测 - **数据科学**:收集客户数据(如购买记录、服务使用情况、客户反馈等),清洗数据,进行特征工程,探索客户行为模式。 - **机器学习**:使用分类算法(如逻辑回归、随机森林、XGBoost等)训练模型,预测哪些客户可能流失。 #### 例子2:图像识别 - **数据科学**:收集大量图像数据,进行标注、清洗、增强等处理。 - **机器学习**:使用深度学习模型(如卷积神经网络CNN)来识别图像中的对象或特征。 #### 例子3:销售预测 - **数据科学**:分析历史销售数据,识别季节性、趋势、促销影响等。 - **机器学习**:使用时间序列预测模型(如ARIMA、LSTM)来预测未来的销售情况。 --- ### 第五步:总结两者的联系 | 方面 | 数据科学 | 机器学习 | |------|----------|----------| | 定义 | 从数据中提取知识的跨学科领域 | 通过算法让计算机学习并做出预测或决策 | | 工具 | 使用统计、编程、可视化等工具 | 使用算法(如回归、分类、聚类、神经网络等) | | 数据基础 | 提供数据清洗、预处理、特征工程 | 依赖数据进行模型训练和预测 | | 应用场景 | 用于商业决策、市场分析、风险管理等 | 用于预测、分类、 提示的 tokens: 37 补全的 tokens: 1024 ----------------------------------------------------------------------------------------
llm = "Qwen/Qwen3-8B"
system_instruction = "You are an expert at world knowledge."
prompt_standard = "What is the connection between data science and machine learning?"
prompt_cot = """What is the connection between data science and machine learning? \
Let's think step by step.
"""
result_standard, tokens_count = get_completions(system_instruction, prompt_standard, llm)
print("-" * 88)
print(f"生成结果-英文-标准提示:\n{result_standard}\n")
print(f"Prompt tokens: {tokens_count.prompt_tokens} \t Completion tokens: {tokens_count.completion_tokens}")
print("-" * 88)
result_cot, tokens_count = get_completions(system_instruction, prompt_cot, llm)
print(f"生成结果-英文-零样本思维链:\n{result_cot}\n")
print(f"Prompt tokens: {tokens_count.prompt_tokens} \t Completion tokens: {tokens_count.completion_tokens}")
print("-" * 88)Output
---------------------------------------------------------------------------------------- 生成结果-英文-标准提示: Data science and machine learning are closely related fields, but they have distinct focuses and applications. Here's a breakdown of their connection: ### 1. **Definition and Scope** - **Data Science** is a broad field that involves extracting insights and knowledge from data. It includes data collection, data cleaning, data analysis, data visualization, and building predictive models. - **Machine Learning** is a subset of data science that focuses specifically on building algorithms and models that can learn from and make decisions or predictions based on data. ### 2. **Core Relationship** - **Machine Learning is a tool within Data Science**: Just as a hammer is a tool used in carpentry, machine learning algorithms are tools used in data science to analyze data and make predictions. - **Data Science provides the context and methodology**: Data scientists use machine learning techniques as part of a broader process that includes understanding the problem, gathering and preparing data, and interpreting the results. ### 3. **Common Goals** - Both fields aim to derive value from data by uncovering patterns, trends, and insights. - They often work together to solve real-world problems, such as: - Predicting customer behavior - Detecting fraud - Recommending products - Classifying data - Optimizing business processes ### 4. **Data Science Tasks vs. Machine Learning Tasks** | **Data Science Tasks** | **Machine Learning Tasks** | |-------------------------|-----------------------------| | Data collection and cleaning | Training models on data | | Exploratory data analysis | Feature selection and engineering | | Data visualization | Model evaluation and tuning | | Statistical analysis | Predictive modeling and inference | | Building data-driven solutions | Deploying models for real-time predictions | ### 5. **Interdisciplinary Nature** - Data science draws from statistics, computer science, and domain-specific knowledge. - Machine learning is rooted in artificial intelligence, statistics, and algorithms. - Together, they form a powerful combination for tackling complex data problems. ### 6. **Applications** - **Data Science**: Used in business intelligence, market research, and data-driven decision-making. - **Machine Learning**: Used in areas like image recognition, natural language processing, and recommendation systems. ### 7. **Overlap and Integration** - Many data science projects incorporate machine learning to make predictions or classifications. - Machine learning models are often evaluated and refined using data science techniques like data visualization and statistical analysis. ### 8. **Tools and Technologies** - Both fields use similar tools and technologies, such as Python, R, SQL, TensorFlow, PyTorch, and Jupyter Notebooks. - Data scientists may use machine learning libraries and frameworks as part of their toolkit. ### 9. **Data Science without Machine Learning** - While machine learning is a powerful component, data science can also involve traditional statistical methods, data visualization, and reporting without the use of machine learning. ### 10. **Machine Learning without Data Science** - Machine learning requires data to train models, and data science helps in preparing and understanding that data. So, while it's possible to build a machine learning model without a full data science approach, the results are often more effective when integrated with data science practices. ### Summary In short, **machine learning is a core component of data science**, and the two fields are deeply intertwined. Data science provides the broader framework and context for working with data, while machine learning offers the specific techniques and algorithms to derive predictive insights from it. Together, they enable organizations to make data-driven decisions and automate complex tasks. Prompt tokens: 36 Completion tokens: 721 ---------------------------------------------------------------------------------------- 生成结果-英文-零样本思维链: The connection between **data science** and **machine learning** is both **interdisciplinary** and **functional**. Let's break this down step by step to understand how they relate: --- ### 1. **Definitions** - **Data Science** is a broad field that involves extracting insights and knowledge from data using various techniques, including statistics, data analysis, data visualization, and machine learning. - **Machine Learning** is a subset of **artificial intelligence (AI)** that focuses on developing algorithms and models that allow computers to learn from and make decisions based on data. --- ### 2. **Core Purpose** - **Data Science** aims to **analyze data** to understand patterns, make predictions, and support decision-making. - **Machine Learning** is specifically about **building models** that can **learn from data** without being explicitly programmed, often to make predictions or decisions. --- ### 3. **Tools and Techniques** - **Data Science** uses a wide range of tools, such as SQL, Python, R, Tableau, and various data processing and visualization libraries. - **Machine Learning** is a part of data science that uses **algorithms** (e.g., decision trees, neural networks, support vector machines) to **train models** on data and make predictions. --- ### 4. **Data Science Workflow** A typical data science workflow includes: - **Data Collection**: Gathering raw data from various sources. - **Data Cleaning**: Preparing the data for analysis by removing inconsistencies and missing values. - **Exploratory Data Analysis (EDA)**: Understanding the data through visualization and summary statistics. - **Feature Engineering**: Selecting and transforming variables to improve model performance. - **Model Building**: Applying machine learning algorithms to create predictive models. - **Model Evaluation**: Testing the model's accuracy and performance. - **Deployment and Interpretation**: Using the model in real-world applications and interpreting results. In this workflow, **machine learning** is used in the **model building** and **evaluation** stages. --- ### 5. **Machine Learning as a Tool in Data Science** - Machine learning is a **key tool** in the data science toolkit. - It enables data scientists to **automate decision-making**, **predict future outcomes**, and **identify complex patterns** in data that might be difficult to detect through traditional analysis methods. --- ### 6. **Overlap and Integration** - Many data science tasks **require machine learning** to extract meaningful insights. - Conversely, **machine learning** often relies on **data science** for data preparation, feature selection, and model interpretation. --- ### 7. **Examples of Connection** - A data scientist might use **machine learning algorithms** (like regression, classification, or clustering) to build a predictive model for customer churn. - They might also use **data science techniques** (like EDA or data visualization) to understand the data before applying machine learning. --- ### 8. **Conclusion** - **Machine learning is a subset of data science**, but not all data science involves machine learning. - **Data science encompasses machine learning**, using it as one of many tools to analyze and interpret data. - The two fields are **closely intertwined**, with machine learning playing a central role in predictive analytics and decision support within data science. --- ### Summary Table | Aspect | Data Science | Machine Learning | |--------|--------------|------------------| | Scope | Broad field | Subset of AI | | Purpose | Extract insights from data | Build models that learn from data | | Tools | SQL, Python, R, Tableau | Algorithms (e.g., SVM, Random Forest, Neural Networks) | | Workflow Stage | Model building, evaluation | Part of model building and evaluation | | Relationship | Encompasses machine learning | Is a key component of data science | --- Let me know if you'd like to explore a specific area like supervised vs. unsupervised learning, or how they apply in real-world scenarios! Prompt tokens: 43 Completion tokens: 806 ----------------------------------------------------------------------------------------
关于零样本思维链,再分享几个我在看论文时发现的跟 "Let's think step by step." 同样行之有效的提示:
-
"Let's work this out in a step by step way to be sure we have the right answer." | ICLR 2023 - Large Language Models are Human-Level Prompt Engineers,https://openreview.net/forum?id=92gvk82DE-
-
"Let's think things through one step at a time." | Google Inc - Automatic Engineering of Long Prompts,https://arxiv.org/abs/2311.10117
-
"Let's think step by step, you must think more steps." | The Impact of Reasoning Step Length on Large Language Models,https://arxiv.org/abs/2401.04925
💻 因此,对于零样本思维链提示,我们不必局限于只使用 "Let's think step by step."。
2.3 自我一致性
Google 在 ICLR 2023 发表的一篇论文 Self-Consistency Improves Chain of Thought Reasoning in Language Models 提出了一种新的解码策略:自我一致性(Self-consistency),以替代思维链提示中的朴素贪婪解码。
如下图所示。自一致性方法包括三个步骤:(1)使用思维链提示的大语言模型;(2)通过从语言模型的解码器中采样来生成不同的推理路径集合,以取代 CoT 提示中的 “贪心解码”;以及(3)边缘化推理路径,并通过选择最终答案集中最一致的答案进行聚合。
自我一致性扩展了思维链的构建,它能生成多个思维链,而不仅仅是一个,并通过多数投票选择最终答案。 自我一致性策略利用了这样一种理念,即一个复杂的推理问题通常可以通过多种不同的思维方式得出同一个正确答案。具体实现是通过少样本 CoT 采样多个不同的推理路径,并从生成结果中选择最一致的答案。
# 改造一下获得 Completions 的函数 设置参数 n=3,temperature=0.80,实现生成多个不尽相同的思维链
def get_completions(system_instruction, llm_prompt, model_endpoint):
extra_body = {}
if "Qwen3" in model_endpoint:
extra_body={
"enable_thinking": False
}
response = client.chat.completions.create(model=model_endpoint,
messages=[{"role": "system", "content": system_instruction},
{"role": "user", "content": llm_prompt}
],
n=3, temperature=0.80, seed=42,
presence_penalty=0, frequency_penalty=0,
max_tokens=1024, extra_body = extra_body
)
return response.choices, response.usagellm = "Qwen/Qwen3-8B"
system_instruction = "您是世界知识专家。"
# Few-shot 思维链提示过程
prompt = f"""问:罗杰有 5 个网球。他又买了 2 罐网球。每罐有 3 个网球。他现在有多少个网球?
答:罗杰开始有 5 个球。每罐有 3 个网球,两罐共有 6 个网球。5 + 6 = 11。答案是 11。
问:森林中开始有 15 棵树。林业工人今天将在林中种树。完成后,将有 21 棵树。林业工人今天种了多少棵树?
答:我们从 15 棵树开始。后来我们有 21 棵树。差异必须是他们种树的数量。因此,他们必须种了 21 - 15 = 6 棵树。答案是 6。
问:杰克有 23 美元。他以每个 3 美元的价格买了 5 个小蛋糕。他还剩下多少钱?
答:他以每个 3 美元的价格买了 5 个小蛋糕,总共花费了 3 * 5 = 15 美元。所以,他还剩下 23 - 15 = 8 美元。答案是 8 美元。
问:当我 6 岁时,我的妹妹的年龄是我的一半。现在我已经 24 岁了,那么我的妹妹现在的年龄是多少?
答:当你 6 岁时,你妹妹的年龄是 6 / 2 = 3 岁。现在你 24 岁,所以你妹妹的年龄是 24 - (6 - 3) = 21 岁。
问:李莉的鸭子每天下 16 个蛋。她每天早餐吃 3 个,每天用 4 个给朋友烤松饼。剩下的蛋她以每个 2 美元的价格出售。她每天能赚多少钱?
答:
"""
result_Chinese, tokens_count = get_completions(system_instruction, prompt, llm)
for response_num, con in enumerate(result_Chinese, start=1):
result = con.message.content.strip()
print(f"思维链-中文-{response_num}:\n{result}\n")Output
思维链-中文-1: 李莉的鸭子每天下 16 个蛋。她每天早餐吃 3 个,用 4 个给朋友烤松饼,那么总共用了 3 + 4 = 7 个蛋。剩下的蛋是 16 - 7 = 9 个。 她以每个 2 美元的价格出售这些蛋,因此她每天能赚的钱是 9 × 2 = 18 美元。 **答案是 18 美元。** 思维链-中文-2: 李莉的鸭子每天下 16 个蛋。她每天早餐吃掉 3 个,用 4 个给朋友烤松饼,所以总共用了 $3 + 4 = 7$ 个蛋。 剩下的蛋是 $16 - 7 = 9$ 个。她以每个 2 美元的价格出售,因此她每天能赚 $9 \times 2 = 18$ 美元。 **答案是 18 美元。** 思维链-中文-3: 李莉的鸭子每天下 16 个蛋。她每天早餐吃掉 3 个,用 4 个给朋友烤松饼,那么总共消耗了 3 + 4 = 7 个蛋。剩下的蛋是 16 - 7 = 9 个。 她以每个 2 美元的价格出售这些蛋,因此每天能赚的钱是 9 × 2 = 18 美元。 **答案是 18 美元。**
llm = "Qwen/Qwen3-8B"
system_instruction = "You are an expert at world knowledge."
prompt = f"""Q: Roger has 5 tennis balls. He bought 2 more cans of tennis balls. Each can has 3 tennis balls. How many tennis balls does he have now?
A: Roger starts with 5 balls. With 3 tennis balls in each can, there are 6 tennis balls in the two cans. 5 + 6 = 11. The answer is 11.
Q: There are 15 trees in the forest to begin with. Forest workers will plant trees in the forest today. When finished, there will be 21 trees. How many trees did the foresters plant today?
A: We started with 15 trees. Later we had 21 trees. The difference must be the number of trees they planted. Therefore, they must have planted 21 - 15 = 6 trees. The answer is 6.
Q: Jack has 23 dollars. He bought 5 cupcakes for $3 each. How much money does he have left?
A: He bought 5 cupcakes for $3 each and spent a total of 3 * 5 = $15. So, he has 23 - 15 = $8 left. The answer is $8.
Q: When I was 6 years old, my sister was half my age. Now that I am 24 years old, what is my sister's age now?
A: When you were 6 years old, your sister was 6 / 2 = 3 years old. Now you are 24, so your sister's age is 24 - (6 - 3) = 21.
Q: Lily's duck lays 16 eggs a day. She eats 3 each day for breakfast and uses 4 each day to bake muffins for her friends. She sells the remaining eggs for $2 each. How much money does she make each day?
A:
"""
result_English, tokens_count = get_completions(system_instruction, prompt, llm)
for response_num, con in enumerate(result_English, start=1):
result = con.message.content.strip()
print(f"思维链-英文-{response_num}:\n{result}\n")Output
思维链-英文-1: Lily's duck lays 16 eggs a day. She eats 3 eggs for breakfast and uses 4 eggs to bake muffins. So, the number of eggs she uses is 3 + 4 = 7 eggs. Therefore, the number of eggs left is 16 - 7 = 9 eggs. She sells each remaining egg for $2, so she makes 9 * $2 = $18 each day. The answer is $18. 思维链-英文-2: Lily's duck lays 16 eggs a day. She eats 3 eggs for breakfast and uses 4 eggs to bake muffins, so she uses a total of 3 + 4 = 7 eggs. This leaves 16 - 7 = 9 eggs. She sells these 9 eggs for $2 each, so she makes 9 * 2 = $18 each day. **The answer is $18.** 思维链-英文-3: Lily's duck lays **16 eggs a day**. She eats **3 eggs** each day for breakfast. She uses **4 eggs** each day to bake muffins. So, the total number of eggs used or eaten per day is: 3 (eaten) + 4 (used) = **7 eggs**. This leaves: 16 (laid) - 7 (used/eaten) = **9 eggs** remaining. She sells the remaining eggs for **$2 each**, so her daily earnings are: 9 × $2 = **$18**. **The answer is $18.**
三、总结与讨论
要点总结:
-
思维链(Chain-of-Thought,CoT)的本质是一种离散式提示学习。通过生成一系列中间推理步骤,以提高大语言模型执行复杂推理的能力。
-
当获取思维链提示的示例较少或存在困难时,零样本思维链可以发挥作用。然而,它有时候不如思维链提示过程那么有效。由于提取步骤通常需要针对特定任务,因此零样本思维链的泛化能力并不是那么强。
-
自我一致性扩展了思维链的构建,它生成多个思维链,并通过多数投票选择最终答案。 自我一致性策略利用了这样一种理念,即一个复杂的推理问题通常可以通过多种不同的思维方式得出同一个正确答案。这种方法通常具有良好的性能。研究发现,自我一致性也能提升在算术、常识和符号推理任务上的表现。即使原始的思维链无效,自我一致性也能改善结果。
📚 主要参考资料:
-
NeurIPS 2020 - Language Models are Few-Shot Learners,https://arxiv.org/abs/2005.14165
-
NeurIPS 2022 - Chain-of-Thought Prompting Elicits Reasoning in Large Language Models,https://openreview.net/forum?id=_VjQlMeSB_J
-
NeurIPS 2022 - Large Language Models are Zero-Shot Reasoners,https://openreview.net/forum?id=e2TBb5y0yFf
-
ICLR 2023 - Self-Consistency Improves Chain of Thought Reasoning in Language Models,https://arxiv.org/abs/2203.11171
-
哈工大 & 华为团队发布的思维链推理综述,A Survey of Chain of Thought Reasoning: Advances, Frontiers and Future,https://arxiv.org/abs/2309.15402
