使用 RetrieveChat 进行检索增强代码生成和问答
AutoGen 提供了由 LLM 提供支持的可对话代理,可以通过自动聊天来共同执行任务,无论是工具还是人类。该框架通过多代理对话允许工具使用和人类参与。有关此功能的文档,请参见此处。
RetrieveChat 是一个用于检索增强代码生成和问答的对话系统。在这个笔记本中,我们演示了如何利用 RetrieveChat 根据不在 LLM 训练数据集中的自定义文档生成代码和回答问题。RetrieveChat 使用 RetrieveAssistantAgent
和 RetrieveUserProxyAgent
,类似于其他笔记本中使用 AssistantAgent
和 UserProxyAgent
的用法(例如,使用代码生成、执行和调试自动解决任务)。实质上,RetrieveAssistantAgent
和 RetrieveUserProxyAgent
实现了与 RetrieveChat 提示相对应的不同自动回复机制。
目录
我们将演示使用 RetrieveChat 进行代码生成和问答的六个示例:
- 示例 1:根据文档字符串生成代码(无人类反馈)
- 示例 2:根据文档字符串回答问题(无人类反馈)
- 示例 3:根据文档字符串生成代码(有人类反馈)
- 示例 4:根据文档字 符串回答问题(有人类反馈)
- 示例 5:使用 RetrieveChat 的独特功能“更新上下文”解决综合性问答问题
- 示例 6:使用自定义提示和少样本学习解决综合性问答问题
设置 API 端点
config_list_from_json
函数从环境变量或json文件中加载配置列表。
import json
import os
import chromadb
import autogen
from autogen.agentchat.contrib.retrieve_assistant_agent import RetrieveAssistantAgent
from autogen.agentchat.contrib.retrieve_user_proxy_agent import RetrieveUserProxyAgent
# 可以存储在向量数据库实例中的接受的文件格式
from autogen.retrieve_utils import TEXT_FORMATS
config_list = [
{"model": "gpt-3.5-turbo-0125", "api_key": "<YOUR_API_KEY>", "api_type": "openai"},
]
assert len(config_list) > 0
print("要使用的模型:", [config_list[i]["model"] for i in range(len(config_list))])
要使用的模型: ['gpt-3.5-turbo-0125']
了解有关为代理配置LLM的更多信息,请点击这里。
为RetrieveChat构建代理
我们首先初始化RetrieveAssistantAgent
和RetrieveUserProxyAgent
。对于RetrieveAssistantAgent
,系统消息需要设置为“您是一个有帮助的助手。”。用户消息中提供了详细的说明。稍后,我们将使用RetrieveUserProxyAgent.message_generator
将说明和检索增强生成任务组合起来,作为初始提示发送给LLM助手。
print("可接受的`docs_path`文件格式:")
print(TEXT_FORMATS)
可接受的`docs_path`文件格式:
['odt', 'xml', 'pdf', 'docx', 'html', 'md', 'htm', 'csv', 'rst', 'org', 'ppt', 'doc', 'log', 'json', 'epub', 'jsonl', 'pptx', 'yml', 'xlsx', 'tsv', 'txt', 'yaml', 'msg', 'rtf']
# 1. 创建一个名为“assistant”的 RetrieveAssistantAgent 实例
assistant = RetrieveAssistantAgent(
name="assistant",
system_message="您是一个乐于助人的助手。",
llm_config={
"timeout": 600,
"cache_seed": 42,
"config_list": config_list,
},
)
# 2. 创建一个名为“ragproxyagent”的 RetrieveUserProxyAgent 实例
# 默认情况下,human_input_mode 是 "ALWAYS",这意味着代理将在每一步都要求人工输入。我们在这里将其设置为 "NEVER"。
# `docs_path` 是文档目录的路径。它也可以是单个文件的路径,或者是单个文件的 URL。默认情况下,
# 它设置为 None,仅在集合已经创建的情况下才起作用。
# `task` 表示我们正在处理的任务类型。在这个例子中,是一个 `code` 任务。
# `chunk_token_size` 是用于检索聊天的块令牌大小。默认情况下,它设置为 `max_tokens * 0.6`,这里我们将其设置为 2000。
# `custom_text_types` 是要处理的文件类型列表。默认值为 `autogen.retrieve_utils.TEXT_FORMATS`。
# 这仅适用于 `docs_path` 目录下的文件。无论其类型如何,显式包含的文件和 URL 都将被分块处理。
# 在这个例子中,我们将其设置为 ["non-existent-type"],以仅处理 markdown 文件。由于 `websit/docs` 中没有包含任何 "non-existent-type" 文件,
# 因此那里的文件都不会被处理。但是,显式包含的 URL 仍然会被处理。
ragproxyagent = RetrieveUserProxyAgent(
name="ragproxyagent",
human_input_mode="NEVER",
max_consecutive_auto_reply=3,
retrieve_config={
"task": "code",
"docs_path": [
"https://raw.githubusercontent.com/microsoft/FLAML/main/website/docs/Examples/Integrate%20-%20Spark.md",
"https://raw.githubusercontent.com/microsoft/FLAML/main/website/docs/Research.md",
os.path.join(os.path.abspath(""), "..", "website", "docs"),
],
"custom_text_types": ["non-existent-type"],
"chunk_token_size": 2000,
"model": config_list[0]["model"],
# "client": chromadb.PersistentClient(path="/tmp/chromadb"), # 已弃用,请使用 "vector_db"
"vector_db": "chroma", # 要使用已弃用的 `client` 参数,请将其设置为 None,并取消上面一行的注释
"overwrite": False, # 如果要覆盖现有的集合,请将其设置为 True
},
code_execution_config=False, # 如果不想执行代码,请将其设置为 False
)
示例1
使用 RetrieveChat 来帮助生成示例代码,并自动运行代码并修复错误(如果有的话)。
问题:如果我想在一个分类任务中使用 FLAML,并且想要在30秒内训练模型,使用 spark 进行并行训练。如果达到时间限制,强制取消作业。
# 重置助手。在开始新对话之前,始终重置助手。
assistant.reset()
# 给定一个问题,我们使用 ragproxyagent 生 成一个要发送给助手作为初始消息的提示。
# 助手接收消息并生成回复。回复将发送回 ragproxyagent 进行处理。
# 对话将继续,直到满足终止条件,在 RetrieveChat 中,当没有检测到代码块时,终止条件是没有人在循环中。
# 在有人在循环中的情况下,对话将继续,直到用户说“退出”为止。
code_problem = "如何使用 FLAML 执行分类任务并使用 spark 进行并行训练。训练30秒并在达到时间限制时强制取消作业。"
chat_result = ragproxyagent.initiate_chat(
assistant, message=ragproxyagent.message_generator, problem=code_problem, search_string="spark"
) # search_string 用作嵌入搜索的额外过滤器,在这种情况下,我们只想搜索包含“spark”的文档。
2024-04-07 17:30:56,955 - autogen.agentchat.contrib.retrieve_user_proxy_agent - INFO - 使用现有集合 `autogen-docs`。
尝试创建集合。
2024-04-07 17:30:59,609 - autogen.agentchat.contrib.retrieve_user_proxy_agent - INFO - 找到2个块。
请求的结果数20大于索引中的元素数2,更新 n_results = 2
VectorDB 返回文档ID:[['bdfbc921']]
将文档 bdfbc921 的内容添加到上下文中。
ragproxyagent(给助手):
你是一个增强型的检索编码助手。你根据自己的知识和用户提供的上下文来回答用户的问题。
如果你无法根据当前上下文回答问题,你应该回复“UPDATE CONTEXT”。
对于代码生成,你必须遵守以下规则:
规则1. 你不得安装任何包,因为所需的所有包都已经安装好了。
规则2. 你必须按照下面的格式编写你的代码:
```language
# 你的代码
用户的问题是:如何使用FLAML执行分类任务并使用spark进行并行训练。训练30秒,并在达到时间限制时强制取消作业。
背景是:# 集成 - Spark
FLAML已经集成了Spark进行分布式训练。与Spark的集成有两个主要方面:
- 使用Spark ML估计器进行自动机器学习。
- 使用Spark运行并行spark作业进行训练。
## Spark ML估计器
FLAML集成了基于Spark ML模型的估计器。这些模型使用Spark并行训练,因此我们称之为Spark估计器。要使用这些模型,您首先需要按照所需的格式组织数据。
### 数据
对于Spark估计器,AutoML只能使用Spark数据。FLAML在`flaml.automl.spark.utils`模块中提供了一个方便的函数`to_pandas_on_spark`,用于将数据转换为pandas-on-spark(`pyspark.pandas`)数据帧/系列,这是Spark估计器所需的。
此实用函数接受`pandas.Dataframe`或`pyspark.sql.Dataframe`形式的数据,并将其转换为pandas-on-spark数据帧。它还接受`pandas.Series`或`pyspark.sql.Dataframe`并将其转换为[pandas-on-spark](https://spark.apache.org/docs/latest/api/python/user_guide/pandas_on_spark/index.html)系列。如果传入`pyspark.pandas.Dataframe`,它将不会进行任何更改。
该函数还接受可选参数`index_col`和`default_index_type`。
- `index_col`是要用作索引的列名,默认为None。
- `default_index_type`是默认索引类型,默认为"distributed-sequence"。有关默认索引类型的更多信息,请参阅Spark官方[文档](https://spark.apache.org/docs/latest/api/python/user_guide/pandas_on_spark/options.html#default-index-type)
下面是一个Spark数据的示例代码片段:
```python
```python
import pandas as pd
from flaml.automl.spark.utils import to_pandas_on_spark
# 创建一个字典
data = {
"Square_Feet": [800, 1200, 1800, 1500, 850],
"Age_Years": [20, 15, 10, 7, 25],
"Price": [100000, 200000, 300000, 240000, 120000],
}
# 创建一个 pandas DataFrame
dataframe = pd.DataFrame(data)
label = "Price"
# 转换为 pandas-on-spark DataFrame
psdf = to_pandas_on_spark(dataframe)
```
要使用 Spark ML 模型,您需要适当地格式化数据。具体来说,使用 [`VectorAssembler`](https://spark.apache.org/docs/latest/api/python/reference/api/pyspark.ml.feature.VectorAssembler.html) 将所有特征列合并为一个向量列。
以下是如何使用它的示例:
```python
from pyspark.ml.feature import VectorAssembler
columns = psdf.columns
feature_cols = [col for col in columns if col != label]
featurizer = VectorAssembler(inputCols=feature_cols, outputCol="features")
psdf = featurizer.transform(psdf.to_spark(index_col="index"))["index", "features"]
```
在进行实验时,像处理非 Spark 数据一样使用您的 pandas-on-spark 数据,并使用 `X_train, y_train` 或 `dataframe, label` 进行传递。
### 估计器
#### 模型列表
- `lgbm_spark`:用于微调 Spark 版本 LightGBM 模型的类,使用 [SynapseML](https://microsoft.github.io/SynapseML/docs/features/lightgbm/about/) API。
#### 用法
首先,按照前面部分的描述,将数据准备成所需的格式。
通过将您打算尝试的模型包含在 `estimators_list` 参数中传递给 `flaml.automl`,FLAML 将开始尝试这些模型的配置。如果您的输入是 Spark 数据,则 FLAML 默认还会使用带有 `_spark` 后缀的估计器,即使您没有指定它们。
以下是使用 SparkML 模型的示例代码片段:
```python
import flaml
# 按照前面提到的方法,将数据准备成 pandas-on-spark 格式
automl = flaml.AutoML()
settings = {
"time_budget": 30,
"metric": "r2",
"estimator_list": ["lgbm_spark"], # 这个设置是可选的
"task": "regression",
}
automl.fit(
dataframe=psdf,
label=label,
**settings,
)
[链接到笔记本](https://github.com/microsoft/FLAML/blob/main/notebook/automl_bankrupt_synapseml.ipynb) | [在colab中打开](https://colab.research.google.com/github/microsoft/FLAML/blob/main/notebook/automl_bankrupt_synapseml.ipynb)
## 并行 Spark 作业
您可以在[自动机器学习](/docs/Use-Cases/Task-Oriented-AutoML#parallel-tuning)和[超参数调整](/docs/Use-Cases/Tune-User-Defined-Function#parallel-tuning)中,通过将 `use_spark` 设置为 `true`,将 Spark 激活为并行后端。FLAML 将使用 [`joblib-spark`](https://github.com/joblib/joblib-spark) 将您的作业分发到分布式 Spark 后端。
请注意,当应用于 Spark 数据的自动机器学习和调整时,不应将 `use_spark` 设置为 `true`。这是因为在自动机器学习和调整中,只会使用 SparkML 模型来处理 Spark 数据。由于 SparkML 模型可以并行运行,因此不需要再使用 `use_spark` 进行分发。
下面列出了所有与 Spark 相关的参数。这些参数在超参数调整和自动机器学习中都可用:
- `use_spark`:布尔值,默认为 False | 是否使用 Spark 运行并行 Spark 作业的训练。这可以用于加速大型模型和大型数据集的训练,但会增加时间开销,从而在某些情况下减慢训练速度。当 `use_spark` 为 True 时,不支持 GPU 训练。对于 Spark 集群,默认情况下,我们将为每个执行器启动一个试验。然而,有时我们希望启动的试验数量超过执行器的数量(例如,本地模式)。在这种情况下,我们可以设置环境变量 `FLAML_MAX_CONCURRENT` 来覆盖检测到的 `num_executors`。最终的并发试验数量将是 `n_concurrent_trials` 和 `num_executors` 中较小的那个。
- `n_concurrent_trials`:整数,默认为 1 | 并发试验的数量。当 n_concurrent_trials > 1 时,FLAML 执行并行调整。
- `force_cancel`:布尔值,默认为 False | 如果搜索时间超过时间预算,则是否强制取消 Spark 作业。Spark 作业包括并行调整作业和基于 Spark 的模型训练作业。
使用并行 Spark 作业的示例代码片段:
```python
导入 flaml
automl_experiment = flaml.AutoML()
automl_settings = {
"time_budget": 30,
"metric": "r2",
"task": "regression",
"n_concurrent_trials": 2,
"use_spark": True,
"force_cancel": True, # 激活 force_cancel 选项可以在超过分配的 time_budget 后立即停止 Spark 作业。
}
automl.fit(
dataframe=dataframe,
label=label,
**automl_settings,
)
```
[笔记本链接](https://github.com/microsoft/FLAML/blob/main/notebook/integrate_spark.ipynb) | [在 colab 中打开](https://colab.research.google.com/github/microsoft/FLAML/blob/main/notebook/integrate_spark.ipynb)
--------------------------------------------------------------------------------
assistant to=python code
请注意,上述代码假设数据量小到足以在30秒内训练完成。如果你有一个更大的数据集,你可能需要增加`time_budget`并相应调整并行作业的数量。
--------------------------------------------------------------------------------
ragproxyagent (给助手):
--------------------------------------------------------------------------------
助手 (给ragproxyagent):
更新上下文
--------------------------------------------------------------------------------
更新上下文并重置对话。
``` text
请求的结果数量60大于索引2中的元素数量,更新n_results = 2
请求的结果数量100大于索引2中的元素数量,更新n_results = 2
请求的结果数量140大于索引2中的元素数量,更新n_results = 2
```
``` text
VectorDB返回的doc_ids:[['bdfbc921']]
VectorDB返 回的doc_ids:[['bdfbc921']]
VectorDB返回的doc_ids:[['bdfbc921']]
```
``` text
请求的结果数量180大于索引2中的元素数量,更新n_results = 2
```
``` text
VectorDB返回的doc_ids:[['bdfbc921']]
没有更多的上下文,将终止。
ragproxyagent(对assistant):
终止
--------------------------------------------------------------------------------
```
``` text
ChatResult(chat_id=None, chat_history=[{'content': 'TERMINATE', 'role': 'assistant'}], summary='', cost=({'total_cost': 0.007691, 'gpt-35-turbo': {'cost': 0.007691, 'prompt_tokens': 4242, 'completion_tokens': 664, 'total_tokens': 4906}}, {'total_cost': 0}), human_input=[])
```
### 示例2
[返回顶部](#table-of-contents)
使用RetrieveChat来回答与代码生成无关的问题。
问题:FLAML的作者是谁?
```python
# 重置assistant。在开始新对话之前,始终重置assistant。
assistant.reset()
qa_problem = "FLAML的作者是谁?"
chat_result = ragproxyagent.initiate_chat(assistant, message=ragproxyagent.message_generator, problem=qa_problem)
```
``` text
请求的结果数量20大于索引2中的元素数量,更新n_results = 2
```
```` text
VectorDB返回的doc_ids:[['7968cf3c','bdfbc921']]
将文档7968cf3c的内容添加到上下文中。
将文档bdfbc921的内容添加到上下文中。
ragproxyagent(对assistant):
你是一个检索增强的编码助手。你根据自己的知识和用户提供的上下文来回答用户的问题。
如果你无论是否有当前上下文都无法回答问题,你应该回复“UPDATE CONTEXT”。
对于代码生成,你必须遵守以下规则:
规则1. 你不得安装任何包,因为所有需要的包都已经安装好了。
规则2. 你必须按照下面的格式编写你的代码:
```language
# 你的代码
```
用户的问题是:FLAML的作者是谁?
上下文是:# 研究
有关技术细节,请查看我们的研究出版物。
- [FLAML: A Fast and Lightweight AutoML Library](https://www.microsoft.com/en-us/research/publication/flaml-a-fast-and-lightweight-automl-library/)。Chi Wang,Qingyun Wu,Markus Weimer,Erkang Zhu。MLSys 2021。
```bibtex
@inproceedings{wang2021flaml,
title={FLAML: A Fast and Lightweight AutoML Library},
author={Chi Wang and Qingyun Wu and Markus Weimer and Erkang Zhu},
year={2021},
booktitle={MLSys},
}
```
- [成本相关超参数的节约优化](https://arxiv.org/abs/2005.01571). Qingyun Wu, Chi Wang, Silu Huang. AAAI 2021.
```bibtex
- [与混合搜索策略的经济超参数优化](https://www.microsoft.com/en-us/research/publication/economical-hyperparameter-optimization-with-blended-search-strategy/)。作者:Chi Wang,Qingyun Wu,Silu Huang,Amin Saied。ICLR 2021。
```bibtex
@inproceedings{wang2021blendsearch,
title={与混合搜索策略的经济超参数优化},
author={Chi Wang and Qingyun Wu and Silu Huang and Amin Saied},
year={2021},
booktitle={ICLR},
}
```
- [关于微调预训练语言模型的超参数优化的实证研究](https://aclanthology.org/2021.acl-long.178.pdf)。作者:Susan Xueqing Liu,Chi Wang。ACL 2021。
```bibtex
@inproceedings{liuwang2021hpolm,
title={关于微调预训练语言模型的超参数优化的实证研究},
author={Susan Xueqing Liu and Chi Wang},
year={2021},
booktitle={ACL},
}
```
- [用于在线自动机器学习的ChaCha](https://www.microsoft.com/en-us/research/publication/chacha-for-online-automl/)。作者:Qingyun Wu,Chi Wang,John Langford,Paul Mineiro和Marco Rossi。ICML 2021。
```bibtex
@inproceedings{wu2021chacha,
title={用于在线自动机器学习的ChaCha},
author={Qingyun Wu and Chi Wang and John Langford and Paul Mineiro and Marco Rossi},
year={2021},
booktitle={ICML},
}
```
- [公平的自动机器学习](https://arxiv.org/abs/2111.06495)。作者:Qingyun Wu,Chi Wang。ArXiv预印本arXiv:2111.06495(2021年)。
```bibtex
@inproceedings{wuwang2021fairautoml,
title={公平的自动机器学习},
author={Qingyun Wu and Chi Wang},
year={2021},
booktitle={ArXiv预印本arXiv:2111.06495},
}
```
- [针对资源受限的自动机器学习挖掘稳健的默认配置](https://arxiv.org/abs/2202.09927)。作者:Moe Kayali,Chi Wang。ArXiv预印本arXiv:2202.09927(2022年)。
```bibtex
@inproceedings{kayaliwang2022default,
title={针对资源受限的自动机器学习挖掘稳健的默认配置},
author={Moe Kayali and Chi Wang},
year={2022},
booktitle={ArXiv预印本arXiv:2202.09927},
}
```
- [基于词典偏好的多目标超参数优化](https://openreview.net/forum?id=0Ij9_q567Ma)。作者:Shaokun Zhang,Feiran Jia,Chi Wang,Qingyun Wu。ICLR 2023(显著性前5%)。
```bibtex
@inproceedings{zhang2023targeted,
title={基于词典偏好的多目标超参数优化},
author={Shaokun Zhang and Feiran Jia and Chi Wang and Qingyun Wu},
booktitle={国际学习表示会议},
year={2023},
url={https://openreview.net/forum?id=0Ij9_q567Ma},
}
```
- [大规模语言模型生成推理的成本效益超参数优化](https://arxiv.org/abs/2303.04673)。Chi Wang,Susan Xueqing Liu,Ahmed H. Awadallah。ArXiv预印本arXiv:2303.04673(2023)。
```bibtex
# 集成 - Spark
FLAML已经集成了Spark用于分布式训练。Spark集成主要有两个方面:
- 使用Spark ML估计器进行自动机器学习。
- 使用Spark运行并行的Spark作业进行训练。
## Spark ML估计器
FLAML集成了基于Spark ML模型的估计器。这些模型使用Spark并行训练,因此我们称之为Spark估计器。要使用这些模型,您首先需要按照所需的格式组织数据。
### 数据
对于Spark估计器,AutoML只能使用Spark数据。FLAML在`flaml.automl.spark.utils`模块中提供了一个方便的函数`to_pandas_on_spark`,用于将数据转换为pandas-on-spark(`pyspark.pandas`)的DataFrame/series,这是Spark估计器所需的。
此实用函数接受`pandas.Dataframe`或`pyspark.sql.Dataframe`形式的数据,并将其转换为pandas-on-spark DataFrame。它还接受`pandas.Series`或`pyspark.sql.Dataframe`并将其转换为[pandas-on-spark](https://spark.apache.org/docs/latest/api/python/user_guide/pandas_on_spark/index.html) series。如果传入`pyspark.pandas.Dataframe`,它将不会进行任何更改。
该函数还接受可选参数`index_col`和`default_index_type`。
- `index_col`是要用作索引的列名,默认为None。
- `default_index_type`是默认的索引类型,默认为"distributed-sequence"。有关默认索引类型的更多信息,请参阅Spark官方[文档](https://spark.apache.org/docs/latest/api/python/user_guide/pandas_on_spark/options.html#default-index-type)。
以下是使用Spark数据的示例代码片段:
```python
import pandas as pd
from flaml.automl.spark.utils import to_pandas_on_spark
# 创建一个字典
data = {
"Square_Feet": [800, 1200, 1800, 1500, 850],
"Age_Years": [20, 15, 10, 7, 25],
"Price": [100000, 200000, 300000, 240000, 120000],
}
# 创建一个pandas DataFrame
dataframe = pd.DataFrame(data)
label = "Price"
# 转换为pandas-on-spark DataFrame
psdf = to_pandas_on_spark(dataframe)
```
要使用Spark ML模型,您需要适当地格式化数据。具体来说,使用[`VectorAssembler`](https://spark.apache.org/docs/latest/api/python/reference/api/pyspark.ml.feature.VectorAssembler.html)将所有特征列合并为一个向量列。
以下是如何使用它的示例:
```python
```python
from pyspark.ml.feature import VectorAssembler
# 获取列名
columns = psdf.columns
# 获取特征列,排除标签列
feature_cols = [col for col in columns if col != label]
# 创建特征向量转换器
featurizer = VectorAssembler(inputCols=feature_cols, outputCol="features")
# 对数据进行特征转换
psdf = featurizer.transform(psdf.to_spark(index_col="index"))["index", "features"]
```
在进行实验时,可以像处理非 Spark 数据一样使用你的 pandas-on-spark 数据,并使用 `X_train, y_train` 或 `dataframe, label` 进行传递。
### 估计器
#### 模型列表
- `lgbm_spark`:用于微调 Spark 版本 LightGBM 模型的类,使用 [SynapseML](https://microsoft.github.io/SynapseML/docs/features/lightgbm/about/) API。
#### 用法
首先,按照前面部分所述的要求格式准备你的数据。
通过将你打算尝试的模型包含在 `estimators_list` 参数中传递给 `flaml.automl`,FLAML 将开始尝试这些模型的配置。如果你的输入是 Spark 数据,FLAML 默认还会使用带有 `_spark` 后缀的估计器,即使你没有指定它们。
下面是一个使用 SparkML 模型的示例代码片段:
```python
import flaml
# 按照前面提到的方式准备你的 pandas-on-spark 格式数据
automl = flaml.AutoML()
settings = {
"time_budget": 30,
"metric": "r2",
"estimator_list": ["lgbm_spark"], # 这个设置是可选的
"task": "regression",
}
automl.fit(
dataframe=psdf,
label=label,
**settings,
)
[链接到笔记本](https://github.com/microsoft/FLAML/blob/main/notebook/automl_bankrupt_synapseml.ipynb) | [在Colab中打开](https://colab.research.google.com/github/microsoft/FLAML/blob/main/notebook/automl_bankrupt_synapseml.ipynb)
## 并行 Spark 作业
您可以在[自动机器学习](/docs/Use-Cases/Task-Oriented-AutoML#parallel-tuning)和[超参数调整](/docs/Use-Cases/Tune-User-Defined-Function#parallel-tuning)中,通过将`use_spark`设置为`true`,将Spark激活为并行后端。FLAML将使用[`joblib-spark`](https://github.com/joblib/joblib-spark)将您的作业分发到分布式Spark后端。
请注意,在应用于Spark数据的自动机器学习和调整时,不应将`use_spark`设置为`true`。这是因为自动机器学习和调整中只 会使用SparkML模型来处理Spark数据。由于SparkML模型可以并行运行,因此不需要再次使用`use_spark`进行分发。
下面列出了所有与Spark相关的参数。这些参数在超参数调整和自动机器学习中都可用:
- `use_spark`:布尔值,默认为False | 是否使用Spark在并行Spark作业中运行训练。这可以用于加速大型模型和大型数据集的训练,但会增加时间开销,从而在某些情况下减慢训练速度。当`use_spark`为True时,不支持GPU训练。对于Spark集群,默认情况下,我们将为每个执行器启动一个试验。然而,有时我们希望启动的试验数量超过执行器的数量(例如,本地模式)。在这种情况下,我们可以设置环境变量`FLAML_MAX_CONCURRENT`来覆盖检测到的`num_executors`。最终的并发试验数量将是`n_concurrent_trials`和`num_executors`中的最小值。
- `n_concurrent_trials`:整数,默认为1 | 并发试验的数量。当`n_concurrent_trials`大于1时,FLAML将执行并行调整。
- `force_cancel`:布尔值,默认为False | 如果搜索时间超过时间预算,则是否强制取消Spark作业。Spark作业包括并行调整作业和基于Spark的模型训练作业。
使用并行Spark作业的示例代码片段:
```python
```python
import flaml
automl_experiment = flaml.AutoML()
automl_settings = {
"time_budget": 30,
"metric": "r2",
"task": "regression",
"n_concurrent_trials": 2,
"use_spark": True,
"force_cancel": True, # 激活 force_cancel 选项可以在超过分配的 time_budget 后立即停止 Spark 作业。
}
automl.fit(
dataframe=dataframe,
label=label,
**automl_settings,
)
```
[笔记本链接](https://github.com/microsoft/FLAML/blob/main/notebook/integrate_spark.ipynb) | [在 Colab 中打开](https://colab.research.google.com/github/microsoft/FLAML/blob/main/notebook/integrate_spark.ipynb)
--------------------------------------------------------------------------------
助手(给 ragproxyagent):
FLAML 的作者是王驰(Chi Wang),还有几位与 FLAML 相关的出版物的合著者。
--------------------------------------------------------------------------------
```
``` text
ChatResult(chat_id=None, chat_history=[{'content': 'You\'re a retrieve augmented coding assistant. You answer user\'s questions based on your own knowledge and the\ncontext provided by the user.\nIf you can\'t answer the question with or without the current context, you should reply exactly `UPDATE CONTEXT`.\nFor code generation, you must obey the following rules:\nRule 1. You MUST NOT install any packages because all the packages needed are already installed.\nRule 2. You must follow the formats below to write your code:\n```language\n# your code\n```\n\nUser\'s question is: Who is the author of FLAML?\n\nContext is: # Research\n\nFor technical details, please check our research publications.\n\n- [FLAML: A Fast and Lightweight AutoML Library](https://www.microsoft.com/en-us/research/publication/flaml-a-fast-and-lightweight-automl-library/). Chi Wang, Qingyun Wu, Markus Weimer, Erkang Zhu. MLSys 2021.\n\n```bibtex\n@inproceedings{wang2021flaml,\n title={FLAML: A Fast and Lightweight AutoML Library},\n author={Chi Wang and Qingyun Wu and Markus Weimer and Erkang Zhu},\n year={2021},\n booktitle={MLSys},\n}\n```\n\n- [Frugal Optimization for Cost-related Hyperparameters](https://arxiv.org/abs/2005.01571). Qingyun Wu, Chi Wang, Silu Huang. AAAI 2021.\n\n```bibtex\n@inproceedings{wu2021cfo,\n title={Frugal Optimization for Cost-related Hyperparameters},\n author={Qingyun Wu and Chi Wang and Silu Huang},\n year={2021},\n booktitle={AAAI},\n}\n```\n\n- [Economical Hyperparameter Optimization With Blended Search Strategy](https://www.microsoft.com/en-us/research/publication/economical-hyperparameter-optimization-with-blended-search-strategy/). Chi Wang, Qingyun Wu, Silu Huang, Amin Saied. ICLR 2021.\n\n```bibtex\n@inproceedings{wang2021blendsearch,\n title={Economical Hyperparameter Optimization With Blended Search Strategy},\n author={Chi Wang and Qingyun Wu and Silu Huang and Amin Saied},\n year={2021},\n booktitle={ICLR},\n}\n```\n\n- [An Empirical Study on Hyperparameter Optimization for Fine-Tuning Pre-trained Language Models](https://aclanthology.org/2021.acl-long.178.pdf). Susan Xueqing Liu, Chi Wang. ACL 2021.\n\n```bibtex\n@inproceedings{liuwang2021hpolm,\n title={An Empirical Study on Hyperparameter Optimization for Fine-Tuning Pre-trained Language Models},\n author={Susan Xueqing Liu and Chi Wang},\n year={2021},\n booktitle={ACL},\n}\n```\n\n- [ChaCha for Online AutoML](https://www.microsoft.com/en-us/research/publication/chacha-for-online-automl/). Qingyun Wu, Chi Wang, John Langford, Paul Mineiro and Marco Rossi. ICML 2021.\n\n```bibtex\n@inproceedings{wu2021chacha,\n title={ChaCha for Online AutoML},\n author={Qingyun Wu and Chi Wang and John Langford and Paul Mineiro and Marco Rossi},\n year={2021},\n booktitle={ICML},\n}\n```\n\n- [Fair AutoML](https://arxiv.org/abs/2111.06495). Qingyun Wu, Chi Wang. ArXiv preprint arXiv:2111.06495 (2021).\n\n```bibtex\n@inproceedings{wuwang2021fairautoml,\n title={Fair AutoML},\n author={Qingyun Wu and Chi Wang},\n year={2021},\n booktitle={ArXiv preprint arXiv:2111.06495},\n}\n```\n\n- [Mining Robust Default Configurations for Resource-constrained AutoML](https://arxiv.org/abs/2202.09927). Moe Kayali, Chi Wang. ArXiv preprint arXiv:2202.09927 (2022).\n\n```bibtex\n@inproceedings{kayaliwang2022default,\n title={Mining Robust Default Configurations for Resource-constrained AutoML},\n author={Moe Kayali and Chi Wang},\n year={2022},\n booktitle={ArXiv preprint arXiv:2202.09927},\n}\n```\n\n- [Targeted Hyperparameter Optimization with Lexicographic Preferences Over Multiple Objectives](https://openreview.net/forum?id=0Ij9_q567Ma). Shaokun Zhang, Feiran Jia, Chi Wang, Qingyun Wu. ICLR 2023 (notable-top-5%).\n\n```bibtex\n@inproceedings{zhang2023targeted,\n title={Targeted Hyperparameter Optimization with Lexicographic Preferences Over Multiple Objectives},\n author={Shaokun Zhang and Feiran Jia and Chi Wang and Qingyun Wu},\n booktitle={International Conference on Learning Representations},\n year={2023},\n url={https://openreview.net/forum?id=0Ij9_q567Ma},\n}\n```\n\n- [Cost-Effective Hyperparameter Optimization for Large Language Model Generation Inference](https://arxiv.org/abs/2303.04673). Chi Wang, Susan Xueqing Liu, Ahmed H. Awadallah. ArXiv preprint arXiv:2303.04673 (2023).\n\n```bibtex\n@inproceedings{wang2023EcoOptiGen,\n title={Cost-Effective Hyperparameter Optimization for Large Language Model Generation Inference},\n author={Chi Wang and Susan Xueqing Liu and Ahmed H. Awadallah},\n year={2023},\n booktitle={ArXiv preprint arXiv:2303.04673},\n}\n```\n\n- [An Empirical Study on Challenging Math Problem Solving with GPT-4](https://arxiv.org/abs/2306.01337). Yiran Wu, Feiran Jia, Shaokun Zhang, Hangyu Li, Erkang Zhu, Yue Wang, Yin Tat Lee, Richard Peng, Qingyun Wu, Chi Wang. ArXiv preprint arXiv:2306.01337 (2023).\n\n```bibtex\n@inproceedings{wu2023empirical,\n title={An Empirical Study on Challenging Math Problem Solving with GPT-4},\n author={Yiran Wu and Feiran Jia and Shaokun Zhang and Hangyu Li and Erkang Zhu and Yue Wang and Yin Tat Lee and Richard Peng and Qingyun Wu and Chi Wang},\n year={2023},\n booktitle={ArXiv preprint arXiv:2306.01337},\n}\n```\n# Integrate - Spark\n\nFLAML has integrated Spark for distributed training. There are two main aspects of integration with Spark:\n\n- Use Spark ML estimators for AutoML.\n- Use Spark to run training in parallel spark jobs.\n\n## Spark ML Estimators\n\nFLAML integrates estimators based on Spark ML models. These models are trained in parallel using Spark, so we called them Spark estimators. To use these models, you first need to organize your data in the required format.\n\n### Data\n\nFor Spark estimators, AutoML only consumes Spark data. FLAML provides a convenient function `to_pandas_on_spark` in the `flaml.automl.spark.utils` module to convert your data into a pandas-on-spark (`pyspark.pandas`) dataframe/series, which Spark estimators require.\n\nThis utility function takes data in the form of a `pandas.Dataframe` or `pyspark.sql.Dataframe` and converts it into a pandas-on-spark dataframe. It also takes `pandas.Series` or `pyspark.sql.Dataframe` and converts it into a [pandas-on-spark](https://spark.apache.org/docs/latest/api/python/user_guide/pandas_on_spark/index.html) series. If you pass in a `pyspark.pandas.Dataframe`, it will not make any changes.\n\nThis function also accepts optional arguments `index_col` and `default_index_type`.\n\n- `index_col` is the column name to use as the index, default is None.\n- `default_index_type` is the default index type, default is "distributed-sequence". More info about default index type could be found on Spark official [documentation](https://spark.apache.org/docs/latest/api/python/user_guide/pandas_on_spark/options.html#default-index-type)\n\nHere is an example code snippet for Spark Data:\n\n```python\nimport pandas as pd\nfrom flaml.automl.spark.utils import to_pandas_on_spark\n\n# Creating a dictionary\ndata = {\n "Square_Feet": [800, 1200, 1800, 1500, 850],\n "Age_Years": [20, 15, 10, 7, 25],\n "Price": [100000, 200000, 300000, 240000, 120000],\n}\n\n# Creating a pandas DataFrame\ndataframe = pd.DataFrame(data)\nlabel = "Price"\n\n# Convert to pandas-on-spark dataframe\npsdf = to_pandas_on_spark(dataframe)\n```\n\nTo use Spark ML models you need to format your data appropriately. Specifically, use [`VectorAssembler`](https://spark.apache.org/docs/latest/api/python/reference/api/pyspark.ml.feature.VectorAssembler.html) to merge all feature columns into a single vector column.\n\nHere is an example of how to use it:\n\n```python\nfrom pyspark.ml.feature import VectorAssembler\n\ncolumns = psdf.columns\nfeature_cols = [col for col in columns if col != label]\nfeaturizer = VectorAssembler(inputCols=feature_cols, outputCol="features")\npsdf = featurizer.transform(psdf.to_spark(index_col="index"))["index", "features"]\n```\n\nLater in conducting the experiment, use your pandas-on-spark data like non-spark data and pass them using `X_train, y_train` or `dataframe, label`.\n\n### Estimators\n\n#### Model List\n\n- `lgbm_spark`: The class for fine-tuning Spark version LightGBM models, using [SynapseML](https://microsoft.github.io/SynapseML/docs/features/lightgbm/about/) API.\n\n#### Usage\n\nFirst, prepare your data in the required format as described in the previous section.\n\nBy including the models you intend to try in the `estimators_list` argument to `flaml.automl`, FLAML will start trying configurations for these models. If your input is Spark data, FLAML will also use estimators with the `_spark` postfix by default, even if you haven\'t specified them.\n\nHere is an example code snippet using SparkML models in AutoML:\n\n```python\nimport flaml\n\n# prepare your data in pandas-on-spark format as we previously mentioned\n\nautoml = flaml.AutoML()\nsettings = {\n "time_budget": 30,\n "metric": "r2",\n "estimator_list": ["lgbm_spark"], # this setting is optional\n "task": "regression",\n}\n\nautoml.fit(\n dataframe=psdf,\n label=label,\n **settings,\n)\n```\n\n[Link to notebook](https://github.com/microsoft/FLAML/blob/main/notebook/automl_bankrupt_synapseml.ipynb) | [Open in colab](https://colab.research.google.com/github/microsoft/FLAML/blob/main/notebook/automl_bankrupt_synapseml.ipynb)\n\n## Parallel Spark Jobs\n\nYou can activate Spark as the parallel backend during parallel tuning in both [AutoML](/docs/Use-Cases/Task-Oriented-AutoML#parallel-tuning) and [Hyperparameter Tuning](/docs/Use-Cases/Tune-User-Defined-Function#parallel-tuning), by setting the `use_spark` to `true`. FLAML will dispatch your job to the distributed Spark backend using [`joblib-spark`](https://github.com/joblib/joblib-spark).\n\nPlease note that you should not set `use_spark` to `true` when applying AutoML and Tuning for Spark Data. This is because only SparkML models will be used for Spark Data in AutoML and Tuning. As SparkML models run in parallel, there is no need to distribute them with `use_spark` again.\n\nAll the Spark-related arguments are stated below. These arguments are available in both Hyperparameter Tuning and AutoML:\n\n- `use_spark`: boolean, default=False | Whether to use spark to run the training in parallel spark jobs. This can be used to accelerate training on large models and large datasets, but will incur more overhead in time and thus slow down training in some cases. GPU training is not supported yet when use_spark is True. For Spark clusters, by default, we will launch one trial per executor. However, sometimes we want to launch more trials than the number of executors (e.g., local mode). In this case, we can set the environment variable `FLAML_MAX_CONCURRENT` to override the detected `num_executors`. The final number of concurrent trials will be the minimum of `n_concurrent_trials` and `num_executors`.\n- `n_concurrent_trials`: int, default=1 | The number of concurrent trials. When n_concurrent_trials > 1, FLAML performes parallel tuning.\n- `force_cancel`: boolean, default=False | Whether to forcely cancel Spark jobs if the search time exceeded the time budget. Spark jobs include parallel tuning jobs and Spark-based model training jobs.\n\nAn example code snippet for using parallel Spark jobs:\n\n```python\nimport flaml\n\nautoml_experiment = flaml.AutoML()\nautoml_settings = {\n "time_budget": 30,\n "metric": "r2",\n "task": "regression",\n "n_concurrent_trials": 2,\n "use_spark": True,\n "force_cancel": True, # Activating the force_cancel option can immediately halt Spark jobs once they exceed the allocated time_budget.\n}\n\nautoml.fit(\n dataframe=dataframe,\n label=label,\n **automl_settings,\n)\n```\n\n[Link to notebook](https://github.com/microsoft/FLAML/blob/main/notebook/integrate_spark.ipynb) | [Open in colab](https://colab.research.google.com/github/microsoft/FLAML/blob/main/notebook/integrate_spark.ipynb)\n\n', 'role': 'assistant'}, {'content': 'The author of FLAML is Chi Wang, along with several co-authors for various publications related to FLAML.', 'role': 'user'}], summary='The author of FLAML is Chi Wang, along with several co-authors for various publications related to FLAML.', cost=({'total_cost': 0.004711, 'gpt-35-turbo': {'cost': 0.004711, 'prompt_tokens': 3110, 'completion_tokens': 23, 'total_tokens': 3133}}, {'total_cost': 0}), human_input=[])
```
### 示例 3
[返回目录](#目录)
使用 RetrieveChat 来帮助生成示例代码并请求人工反馈。
问题:如何使用 FLAML 构建股票价格的时间序列预测模型?
```python
# 重置助手。在开始新的对话之前,始终重置助手。
assistant.reset()
# 将 `human_input_mode` 设置为 `ALWAYS`,这样代理将在每一步都要求人工输入。
ragproxyagent.human_input_mode = "ALWAYS"
code_problem = "如何使用 FLAML 构建股票价格的时间序列预测模型?"
chat_result = ragproxyagent.initiate_chat(assistant, message=ragproxyagent.message_generator, problem=code_problem)
```
``` text
WARNING:chromadb.segment.impl.vector.local_persistent_hnsw:Number of requested results 20 is greater than number of elements in index 2, updating n_results = 2
```
```` text
doc_ids: [['doc_0', 'doc_1']]
将 doc_id doc_0 添加到上下文中。
将 doc_id doc_1 添加到上下文中。
ragproxyagent(对助手说):
你是一个带有检索增强的编码助手。你根据自己的知识和用户提供的上下文来回答用户的问题。
如果你无法根据当前上下文回答问题,无论是否有上下文,你都应该回复 `UPDATE CONTEXT`。
对于代码生成,你必须遵守以下规则:
规则 1. 你不得安装任何包,因为所需的所有包已经安装好了。
规则 2. 你必须按照以下格式编写你的代码:
```language
# your code
用户的问题是:如何使用FLAML构建股票价格的时间序列预测模型?
背景是:# 集成 - Spark
FLAML已经集成了Spark进行分布式训练。与Spark的集成有两个主要方面:
- 使用Spark ML估计器进行自动机器学习。
- 使用Spark并行运行训练作业。
## Spark ML估计器
FLAML集成了基于Spark ML模型的估计器。这些模型使用Spark并行训练,因此我们称之为Spark估计器。要使用这些模型,首先需要按照所需的格式组织数据。
### 数据
对于Spark估计器,AutoML只能使用Spark数据。FLAML在`flaml.automl.spark.utils`模块中提供了一个方便的函数`to_pandas_on_spark`,用于将数据转换为pandas-on-spark(`pyspark.pandas`)数据帧/系列,这是Spark估计器所需的。
这个实用函数接受`pandas.Dataframe`或`pyspark.sql.Dataframe`形式的数据,并将其转换为pandas-on-spark数据帧。它还接受`pandas.Series`或`pyspark.sql.Dataframe`并将其转换为[pandas-on-spark](https://spark.apache.org/docs/latest/api/python/user_guide/pandas_on_spark/index.html)系列。如果传入`pyspark.pandas.Dataframe`,它将不会进行任何更改。
该函数还接受可选参数`index_col`和`default_index_type`。
- `index_col`是要用作索引的列名,默认为None。
- `default_index_type`是默认的索引类型,默认为"distributed-sequence"。有关默认索引类型的更多信息,请参阅Spark官方[文档](https://spark.apache.org/docs/latest/api/python/user_guide/pandas_on_spark/options.html#default-index-type)
下面是一个Spark数据的示例代码片段:
```python
```python
import pandas as pd
from flaml.automl.spark.utils import to_pandas_on_spark
# 创建一个字典
data = {"Square_Feet": [800, 1200, 1800, 1500, 850],
"Age_Years": [20, 15, 10, 7, 25],
"Price": [100000, 200000, 300000, 240000, 120000]}
# 创建一个 pandas DataFrame
dataframe = pd.DataFrame(data)
label = "Price"
# 转换为 pandas-on-spark DataFrame
psdf = to_pandas_on_spark(dataframe)
```
要使用 Spark ML 模型,您需要适当地格式化数据。具体来说,使用 [`VectorAssembler`](https://spark.apache.org/docs/latest/api/python/reference/api/pyspark.ml.feature.VectorAssembler.html) 将所有特征列合并为一个向量列。
以下是如何使用的示例:
```python
from pyspark.ml.feature import VectorAssembler
columns = psdf.columns
feature_cols = [col for col in columns if col != label]
featurizer = VectorAssembler(inputCols=feature_cols, outputCol="features")
psdf = featurizer.transform(psdf.to_spark(index_col="index"))["index", "features"]
```
在进行实验时,像处理非 Spark 数据一样使用您的 pandas-on-spark 数据,并使用 `X_train, y_train` 或 `dataframe, label` 进行传递。
### 估计器
#### 模型列表
- `lgbm_spark`:用于微调 Spark 版本 LightGBM 模型的类,使用 [SynapseML](https://microsoft.github.io/SynapseML/docs/features/lightgbm/about/) API。
#### 用法
首先,按照前一节中的描述,将您的数据准备成所需的格式。
通过将您打算尝试的模型包含在 `estimators_list` 参数中传递给 `flaml.automl`,FLAML 将开始尝试这些模型的配置。如果您的输入是 Spark 数据,则 FLAML 默认还会使用带有 `_spark` 后缀的估计器,即使您没有指定它们。
以下是使用 SparkML 模型进行 AutoML 的示例代码片段:
```python
import flaml
# 按照我们之前提到的方式,将数据准备成 pandas-on-spark 格式
automl = flaml.AutoML()
settings = {
"time_budget": 30,
"metric": "r2",
"estimator_list": ["lgbm_spark"], # 这个设置是可选的
"task": "regression",
}
automl.fit(
dataframe=psdf,
label=label,
**settings,
)
[链接到笔记本](https://github.com/microsoft/FLAML/blob/main/notebook/automl_bankrupt_synapseml.ipynb) | [在colab中打开](https://colab.research.google.com/github/microsoft/FLAML/blob/main/notebook/automl_bankrupt_synapseml.ipynb)
## 并行 Spark 作业
您可以在[AutoML](/docs/Use-Cases/Task-Oriented-AutoML#parallel-tuning)和[超参数调整](/docs/Use-Cases/Tune-User-Defined-Function#parallel-tuning)中将 Spark 激活为并行后端,方法是将 `use_spark` 设置为 `true`。FLAML 将使用 [`joblib-spark`](https://github.com/joblib/joblib-spark) 将您的作业分发到分布式 Spark 后端。
请注意,在应用于 Spark 数据的 AutoML 和调整过程中,不应将 `use_spark` 设置为 `true`。这是因为在 AutoML 和调整过程中,只会使用 SparkML 模型来处理 Spark 数据。由于 SparkML 模型可以并行运行,因此不需要再使用 `use_spark` 进行分发。
下面列出了所有与 Spark 相关的参数。这些参数在超参数调整和 AutoML 中都可用:
- `use_spark`:布尔值,默认为 False | 是否使用 Spark 在并行 Spark 作业中运行训练。这可以用于加速大型模型和大型数据集的训练,但会增加时间开销,从而在某些情况下减慢训练速度。当 `use_spark` 为 True 时,不支持 GPU 训练。对于 Spark 集群,默认情况下,我们将为每个执行器启动一个试验。然而,有时我们希望启动的试验数量超过执行器的数量(例如,本地模式)。在这种情况下,我们可以设置环境变量 `FLAML_MAX_CONCURRENT` 来覆盖检测到的 `num_executors`。最终的并发试验数量将是 `n_concurrent_trials` 和 `num_executors` 中的最小值。
- `n_concurrent_trials`:整数,默认为 1 | 并发试验的数量。当 `n_concurrent_trials` 大于 1 时,FLAML 执行并行调整。
- `force_cancel`:布尔值,默认为 False | 如果搜索时间超过时间预算,则是否强制取消 Spark 作业。Spark 作业包括并行调整作业和基于 Spark 的模型训练作业。
使用并行 Spark 作业的示例代码片段:
```python
```python
import flaml
automl_experiment = flaml.AutoML()
automl_settings = {
"time_budget": 30,
"metric": "r2",
"task": "regression",
"n_concurrent_trials": 2,
"use_spark": True,
"force_cancel": True, # 激活 force_cancel 选项可以在超出分配的 time_budget 后立即停止 Spark 作业。
}
automl.fit(
dataframe=dataframe,
label=label,
**automl_settings,
)
```
[Notebook 链接](https://github.com/microsoft/FLAML/blob/main/notebook/integrate_spark.ipynb) | [在 colab 中打开](https://colab.research.google.com/github/microsoft/FLAML/blob/main/notebook/integrate_spark.ipynb)
# 研究
有关技术细节,请查阅我们的研究论文。
* [FLAML: 一个快速且轻量级的 AutoML 库](https://www.microsoft.com/en-us/research/publication/flaml-a-fast-and-lightweight-automl-library/)。Chi Wang, Qingyun Wu, Markus Weimer, Erkang Zhu. MLSys 2021.
```bibtex
@inproceedings{wang2021flaml,
title={FLAML: 一个快速且轻量级的 AutoML 库},
author={Chi Wang and Qingyun Wu and Markus Weimer and Erkang Zhu},
year={2021},
booktitle={MLSys},
}
```
* [面向成本相关超参数的节俭优化](https://arxiv.org/abs/2005.01571)。Qingyun Wu, Chi Wang, Silu Huang. AAAI 2021.
```bibtex
@inproceedings{wu2021cfo,
title={面向成本相关超参数的节俭优化},
author={Qingyun Wu and Chi Wang and Silu Huang},
year={2021},
booktitle={AAAI},
}
```
* [混合搜索策略的经济超参数优化](https://www.microsoft.com/en-us/research/publication/economical-hyperparameter-optimization-with-blended-search-strategy/)。Chi Wang, Qingyun Wu, Silu Huang, Amin Saied. ICLR 2021.
```bibtex
@inproceedings{wang2021blendsearch,
title={混合搜索策略的经济超参数优化},
author={Chi Wang and Qingyun Wu and Silu Huang and Amin Saied},
year={2021},
booktitle={ICLR},
}
```
* [针对微调预训练语言模型的超参数优化的实证研究](https://aclanthology.org/2021.acl-long.178.pdf)。Susan Xueqing Liu, Chi Wang. ACL 2021.
```bibtex
@inproceedings{liuwang2021hpolm,
title={针对微调预训练语言模型的超参数优化的实证研究},
author={Susan Xueqing Liu and Chi Wang},
year={2021},
booktitle={ACL},
}
```
* [在线 AutoML 的 ChaCha](https://www.microsoft.com/en-us/research/publication/chacha-for-online-automl/)。Qingyun Wu, Chi Wang, John Langford, Paul Mineiro 和 Marco Rossi. ICML 2021.
```bibtex
@inproceedings{wu2021chacha,
title={在线 AutoML 的 ChaCha},
author={Qingyun Wu and Chi Wang and John Langford and Paul Mineiro and Marco Rossi},
year={2021},
booktitle={ICML},
}
```
* [公平的 AutoML](https://arxiv.org/abs/2111.06495)。Qingyun Wu, Chi Wang. ArXiv preprint arXiv:2111.06495 (2021).
```bibtex
@inproceedings{wuwang2021fairautoml,
title={公平的 AutoML},
```python
import flaml
import pandas as pd
from flaml.automl.spark.utils import to_pandas_on_spark
# Convert data to pandas-on-spark dataframe/series
data = to_pandas_on_spark(spark_data)
# Merge feature columns into a single vector column
assembler = VectorAssembler(
inputCols=data.columns[:-1],
outputCol="features"
)
data = assembler.transform(data)
# Initialize and run AutoML
automl = flaml.AutoML()
automl.fit(data, label_col=data.columns[-1])
```
This code snippet demonstrates how to use FLAML's `lgbm_spark` estimator for time series forecasting. It converts the Spark dataframe to a pandas-on-spark dataframe/series using the `to_pandas_on_spark` function. Then, it merges the feature columns into a single vector column using `VectorAssembler`. Finally, it initializes and runs the `flaml.AutoML` object to search for the best model configuration.
```python
import flaml
import pandas as pd
from flaml.automl.spark.utils import to_pandas_on_spark
from pyspark.ml.feature import VectorAssembler
# 将股票价格数据加载到 pandas 数据帧中
data = pd.read_csv('stock_price.csv')
# 指定标签列名
label = 'price'
# 将 pandas 数据帧转换为 pandas-on-spark 数据帧
psdf = to_pandas_on_spark(data)
# 将特征列合并为单个向量列
feature_cols = [col for col in psdf.columns if col != label]
featurizer = VectorAssembler(inputCols=feature_cols, outputCol="features")
psdf = featurizer.transform(psdf.to_spark(index_col="index"))["index", "features"]
# 使用 lgbm_spark 评估器开始一个 AutoML 实验
automl = flaml.AutoML()
settings = {
"time_budget": 30,
"metric": "r2",
"estimator_list": ["lgbm_spark"],
"task": "regression",
}
automl.fit(
dataframe=psdf,
label=label,
**settings,
)
```
--------------------------------------------------------------------------------
我希望将 time_budget 设置为 10 分钟
--------------------------------------------------------------------------------
我希望将 time_budget 设置为 10 分钟
--------------------------------------------------------------------------------
您可以将 `settings` 字典中的 `time_budget` 参数设置为 10 分钟(600 秒),如下所示:
```python
import flaml
import pandas as pd
from flaml.automl.spark.utils import to_pandas_on_spark
from pyspark.ml.feature import VectorAssembler
# 将股票价格数据加载到 pandas 数据帧中
data = pd.read_csv('stock_price.csv')
# 指定标签列名
label = 'price'
# 将 pandas 数据帧转换为 pandas-on-spark 数据帧
psdf = to_pandas_on_spark(data)
# 将特征列合并为单个向量列
feature_cols = [col for col in psdf.columns if col != label]
featurizer = VectorAssembler(inputCols=feature_cols, outputCol="features")
psdf = featurizer.transform(psdf.to_spark(index_col="index"))["index", "features"]
# 使用 lgbm_spark 评估器开始一个 AutoML 实验,时间预算为 10 分钟
automl = flaml.AutoML()
settings = {
"time_budget": 600, # 时间预算以秒为单位
"metric": "r2",
"estimator_list": ["lgbm_spark"],
"task": "regression",
}
automl.fit(
dataframe=psdf,
label=label,
**settings,
)
```
在这个例子中,`time_budget` 参数被设置为 600,表示 FLAML AutoML 实验运行的秒数。您可以调整这个值来控制实验所花费的总时间。
--------------------------------------------------------------------------------
>>>>>>>> NO HUMAN INPUT RECEIVED.
>>>>>>>> USING AUTO REPLY...
--------------------------------------------------------------------------------
还有什么我可以帮助您的吗?
--------------------------------------------------------------------------------
>>>>>>>> NO HUMAN INPUT RECEIVED.
示例 4
使用 RetrieveChat 来回答问题并请求人工反馈。
问题:FLAML 中是否有一个名为 tune_automl
的函数?
# 重置助手。在开始新对话之前,始终重置助手。
assistant.reset()
# 将 `human_input_mode` 设置为 `ALWAYS`,这样代理将在每一步都要求人工输入。
ragproxyagent.human_input_mode = "ALWAYS"
qa_problem = "FLAML 中是否有一个名为 `tune_automl` 的函数?"
chat_result = ragproxyagent.initiate_chat(
assistant, message=ragproxyagent.message_generator, problem=qa_problem
) # 输入 "exit" 退出对话
WARNING:chromadb.segment.impl.vector.local_persistent_hnsw:请求的结果数 20 大于索引中的元素数 2,更新 n_results = 2
doc_ids: [['doc_0', 'doc_1']]
将 doc_id doc_0 添加到上下文中。
将 doc_id doc_1 添加到上下文中。
ragproxyagent(对助手):
你是一个带有检索增强的编码助手。你根据自己的知识和用户提供的上下文来回答用户的问题。