AutoGen - Build Powerful AI Agents with ChatGPT/GPT-4

原文:AutoGen - Build Powerful AI Agents with ChatGPT/GPT-4 | MLExpert - Crush Your Machine Learning interview

In this tutorial, we'll explore AutoGen1, a Microsoft library that lets you create LLM applications with agents. These agents can communicate and help you solve complex tasks.

Join the AI BootCamp!

Ready to dive deep into the world of AI and Machine Learning? Join our BootCamp to transform your career with the latest skills and real-world project experience. LLMs, ML best practices, and more!

JOIN NOW

We'll begin with an introduction to AutoGen and its benefits. Then, we'll kick off with a basic example of building a single agent for analyzing stock price trends. Afterward, we'll delve into a more advanced demonstration, using four agents to construct a cryptocurrency indicator, drawing insights from historical prices and news.

In this part, we will be using Jupyter Notebook to run the code. If you prefer to follow along, you can find the notebook on GitHub: GitHub Repository(opens in a new tab)

What Makes AutoGen Cool?

  • Flexible Chats: AutoGen can make agents talk to each other to solve problems. This is much more powerful than just one LLM doing everything.

  • Customization: You can create agents to do specific tasks. You can choose which LLM to use, how people can join the conversation, and even bring in tools to help.

  • Human Input: AutoGen lets humans join the conversation, too. They can give their ideas and feedback to help the agents.

AutoGen is like having a bunch of smart friends who work together to get things done, and it's made with help from top-notch researchers.

Setup

You can install AutoGen with pip:

pip install -Uqqq pip --progress-bar offpip install -qqq pyautogen==0.1.10 --progress-bar off

Let's add the required libraries:

import jsonfrom getpass import getpass import autogenimport pandas as pdimport requestsfrom autogen import AssistantAgent, UserProxyAgentfrom IPython.display import Image

Next, you need to enter your API key for OpenAI (get yours from https://platform.openai.com/account/api-keys(opens in a new tab)):

OPENAI_API_KEY = getpass()

We'll get news and historical prices for Bitcoin and Ethereum from Alpha Vantage2. You can get your API key from https://www.alphavantage.co/support/#api-key(opens in a new tab). Let's enter it:

ALPHA_VANTAGE_API_KEY = getpass()

You can also load the data for this tutorial (if you want to reproduce the results) from my Google Drive:

gdown 1YIw3kRmPmWPeVu-wJlG3uNtJ4YjBVDEqgdown 1zBz5qC1TmweDOKsmFo2AXSjk8uI6jT7dgdown 1BpCOBIz-3OVgW2s337n9lgxgL5z8G4mG

Simple Agent

Let's start with a simple example. We'll create an agent that can fetch historical prices for Bitcoin, Ethereum, Tesla stock and plot them.

First, we need to create a configuration for our agent:

gpt_config_list = [    {        "model": "gpt-4", # or use "gpt-3.5-turbo"        "api_key": OPENAI_API_KEY,    }] llm_config = {"config_list": gpt_config_list, "use_cache": False, "temperature": 0}

The important part is the selection of model and the API key. We'll use GPT-4 for this example. You can also use GPT-3.5 Turbo (ChatGPT). Let's create the agent:

assistant = AssistantAgent(    name="assistant",    llm_config=llm_config,)

To start the conversation, we need another agent that will represent the user (you). We'll use the UserProxyAgent for this:

def is_termination_msg(data):    has_content = "content" in data and data["content"] is not None    return has_content and "TERMINATE" in data["content"] user_proxy = UserProxyAgent(    name="user_proxy",    human_input_mode="NEVER",    max_consecutive_auto_reply=10,    is_termination_msg=is_termination_msg,    code_execution_config={"work_dir": "coding"},)

We'll use the is_termination_msg function to stop the conversation when the agent replies with TERMINATE anywhere in the text. The code_execution_config will tell the agent to save any assets (code, images etc) in the coding directory. Let's start the conversation:

user_proxy.initiate_chat(    assistant,    message="What is the current year? Compare the year-to-date gain for BTC, ETH and TESLA.",)

The assistant goes through a couple of rounds of fixing code and replying with the results (check the Colab notebook for the complete output). Here's the final report:

assistant

The code has successfully fetched the year-to-date (YTD) gain for BTC (Bitcoin),ETH (Ethereum), and TSLA (Tesla). Here are the results: - The YTD gain for BTC (Bitcoin) is approximately 61.25%- The YTD gain for ETH (Ethereum) is approximately 29.91%- The YTD gain for TSLA (Tesla) is not available (NaN) The NaN result for Tesla could be due to various reasons such as lack of datafor the specified period or issues with the data source. It's recommended tocheck the data source or try a different one if necessary. TERMINATE

Isn't that cool? For some reason, the Tesla stock price is unavailable. We can even ask the agent to plot the data for us:

user_proxy.send(    recipient=assistant,    message="Plot a chart of their price change YTD and save to price_ytd.png.",)

Here's the final message from the assistant:

assistant

Great! The code has successfully fetched the data and created the plot. The plothas been saved to a file named 'price_ytd.png'. You can find this file in thecurrent directory. Please open the 'price_ytd.png' file to view the plot. It shows the price changeyear-to-date (YTD) for BTC (Bitcoin), ETH (Ethereum), and TSLA (Tesla). TERMINATE

Let's look at the plot:

Starting plot from the assistant

Starting plot from the assistant

The plot is not very useful because the price of Bitcoin is much higher than the price of Ethereum and Tesla stock. We can ask the assistant to scale the prices for us:

user_proxy.send(    recipient=assistant,    message="I can't see the ETH stock price on the chart",)

assistant

Great! The code has successfully fetched the data and created the plot. The plothas been saved to a file named 'price_ytd.png'. You can find this file in thecurrent directory. Please open the 'price_ytd.png' file to view the plot. It shows the cumulativepercentage change in price year-to-date (YTD) for BTC (Bitcoin), ETH (Ethereum),and TSLA (Tesla). This should make it easier to compare the performance of theseassets over the same period. TERMINATE

Scaled prices

Scaled prices

Much better! We now even have the Tesla prices showing. Though, the dates are not properly showing. We can ask the assistant to fix that:

user_proxy.send(    recipient=assistant,    message="The dates overlap, increase the plot size",)

assistant

Great! The code has successfully fetched the data and created the plot with alarger size and rotated date labels. The plot has been saved to a file named'price_ytd.png'. You can find this file in the current directory. Please open the 'price_ytd.png' file to view the plot. It shows the cumulativepercentage change in price year-to-date (YTD) for BTC (Bitcoin), ETH (Ethereum),and TSLA (Tesla). The dates on the x-axis should now be more readable. TERMINATE

Final plot from the assistant

Final plot from the assistant

I am impressed. After a couple of rounds of fixing code, the assistant was able to produce a nice plot for us and save it to a file.

Build AI Agent Workforce for Cryptocurrency Analysis

Your first agent was very useful, but the AutoGen library shines when you have multiple agents working together. Let's build a cryptocurrency indicator that can analyze historical prices and news to give us recommended trading actions for Bitcoin and Ethereum.

Let's start with getting the latest news and prices for cryptocurrencies. We'll use the Alpha Vantage API to get the data:

def fetch_prices_for_symbol(symbol: str, days: int, use_cache: bool = False) -> str:    if use_cache:        if symbol == "BTC":            price_df = pd.read_csv("btc_price.csv")        else:            price_df = pd.read_csv("eth_price.csv")        return price_df[["date", "close", "volume"]].head(days)     url = f"https://www.alphavantage.co/query?function=DIGITAL_CURRENCY_DAILY&symbol={symbol}&market=USD&apikey={ALPHA_VANTAGE_API_KEY}"    r = requests.get(url)    price_data = r.json()     rows = []    for key, day_data in price_data["Time Series (Digital Currency Daily)"].items():        rows.append(            {                "date": key,                "high": day_data["2a. high (USD)"],                "low": day_data["3b. low (USD)"],                "close": day_data["4a. close (USD)"],                "volume": day_data["5. volume"],            }        )    df = pd.DataFrame(rows)    return df[["date", "close", "volume"]].head(days)

The fetch_prices_for_symbol function will fetch the latest prices for a given symbol (BTC or ETH). We can also use the cache to reproduce the results from this tutorial. Let's create a helper function that will fetch the prices for both cryptocurrencies and convert it to a string:

def fetch_prices(days: int) -> str:    btc_df = fetch_prices_for_symbol("BTC", days, use_cache=True)    eth_df = fetch_prices_for_symbol("ETH", days, use_cache=True)     btc_txt = btc_df.to_string(index=None)    eth_txt = eth_df.to_string(index=None)     return f"""$BTC prices (last {days} days){btc_txt} $ETH prices (last {days} days){eth_txt}    """.strip()

Next, we'll create a function that will fetch the latest news for the blockchain topic:

def fetch_news(latest_n: int) -> str:    news_df = pd.read_csv("news.csv", sep=";")    return news_df[["summary", "sentiment_score"]].head(latest_n).to_string(index=None)    url = f"https://www.alphavantage.co/query?function=NEWS_SENTIMENT&sort=LATEST&topics=blockchain&apikey={ALPHA_VANTAGE_API_KEY}"    r = requests.get(url)    data = r.json()     rows = []    for item in data["feed"]:        rows.append(            {                "title": item["title"],                "summary": item["summary"],                "time_published": item["time_published"],                "sentiment_score": item["overall_sentiment_score"],            }        )    df = pd.DataFrame(rows)    return df[["summary", "sentiment_score"]].head(latest_n).to_string(index=None)

Again, this can use the cache to reproduce the results from this tutorial. Let's try out the fetch_prices function to fetch the 14 latest prices for Bitcoin and Ethereum:

prices_txt = fetch_prices(days=14)print(prices_txt)

$BTC prices (last 14 days) date close volume 2023-10-11 27420.00 422.773042023-10-10 27390.12 22776.84383 2023-10-09 27590.12 31534.74639 2023-10-0827917.05 19693.56921 2023-10-07 27956.67 13348.83825 2023-10-06 27931.0937983.24277 2023-10-05 27410.39 30681.49619 2023-10-04 27778.57 29816.142002023-10-03 27426.46 28928.96555 2023-10-02 27494.51 57071.14241 2023-10-0127992.57 24602.81468 2023-09-30 26962.56 12804.62307 2023-09-29 26906.9628478.76219 2023-09-28 27021.39 44517.83491 $ETH prices (last 14 days) date close volume 2023-10-11 1569.76 3369.10262023-10-10 1567.63 240659.3287 2023-10-09 1580.13 340141.0988 2023-10-08 1632.84149424.6635 2023-10-07 1633.57 101241.5732 2023-10-06 1645.03 220507.92862023-10-05 1611.79 237378.7449 2023-10-04 1646.58 222861.7167 2023-10-03 1656.88198287.1164 2023-10-02 1662.40 378575.6898 2023-10-01 1733.79 225611.58682023-09-30 1670.89 136924.9141 2023-09-29 1667.45 251975.6728 2023-09-28 1652.99331409.7015

We have our functions ready, but who and when will call them? Fortunatelly, we can tell the AutoGen agents to use them. Let's create a configuration:

llm_config = {    "config_list": gpt_config_list,    "use_cache": False,    "temperature": 0,    "functions": [        {            "name": "fetch_prices",            "description": "Fetch daily prices for $BTC and $ETH",            "parameters": {                "type": "object",                "properties": {                    "days": {                        "type": "integer",                        "description": "number of historical days",                    }                },                "required": ["days"],            },        },        {            "name": "fetch_news",            "description": "Fetch the latest news about cryptocurrencies",            "parameters": {                "type": "object",                "properties": {                    "latest_n": {                        "type": "integer",                        "description": "number of latest news articles to get",                    }                },                "required": ["latest_n"],            },        },    ],}

The configuration tells the agents that they can use the fetch_prices and fetch_news functions. Let's start with the first agent, the analyst:

analyst_system_message = """Analyst. You are a senior financial analyst for a cryptocurrency indicator. Follow the plan: - Get news and prices from the engineer - Give the news and prices (in compact format) to the bull and get their opinion - Give the news and prices (in compact format) to the bear and get their opinion - Write a report with BUY, SELL or HODL along with a number between 0 (extremely bearish)and 100 (extremely bullish) based on the discussion with the bear,the bull, and your own opinion for $ETH and $BTC. Add TERMINATE to the end of the message.""" analyst = AssistantAgent(    name="analyst",    system_message=analyst_system_message,    llm_config=llm_config,    is_termination_msg=is_termination_msg,    code_execution_config=False,)

The analyst will make the final decision about the cryptocurrency indicator. They will get the news and prices from the engineer, then ask the bull and the bear for their opinion. Finally, they will write a report with a recommendation (BUY, SELL or HODL) and a score between 0 and 100. Let's create the engineer:

engineer_system_message = """Engineer. You are a senior software engineer that executes the fetch_prices andfetch_news functions as requested by the analyst.""" engineer = AssistantAgent(    name="engineer",    system_message=engineer_system_message,    llm_config=llm_config,    function_map={"fetch_prices": fetch_prices, "fetch_news": fetch_news},    code_execution_config=False,)

The engineer will be the only one to execute the fetch_prices and fetch_news functions. It knows how to call them based on the llm_config and the function_map. Note that the code_execution_config=False disallows calling other functions. Let's create the bull and the bear:

bull_system_message = """Bull. You receive news and prices for $ETH and $BTC from the analyst.You're always on the bullish side for cryptocurrencies and try to find sentiment thatsupports explosive price increases in the short and long term.You reply to the senior analyst with 1-2 sentences why the data suggests bullish times ahead.""" bull = AssistantAgent(    name="bull",    system_message=bull_system_message,    code_execution_config=False,    llm_config=llm_config,)

The bull creates a short message that explains why the data suggests bullish times ahead and passes it back to the analyst. The bear searches for proof of bearish times ahead:

bear_system_message = """Bear. You receive news and prices for $ETH and $BTC from the analyst.You're always on the bearish side for cryptocurrencies and try to find sentiment thatsupports explosive price drops in the short and long term.You reply to the senior analyst with 1-2 sentences why the data suggests bearish times ahead.""" bear = AssistantAgent(    name="bear",    system_message=bear_system_message,    code_execution_config=False,    llm_config=llm_config,)

The final agent is the user_proxy that will represent you. It will initiate the chat with the analyst and send the message that will start the conversation:

admin_system_message = """A human admin. Interact with the analyst to discuss the cryptocurrency report.The final report needs to be approved by this admin.""" user_proxy = UserProxyAgent(    name="admin",    system_message=admin_system_message,    code_execution_config=False,    human_input_mode="NEVER",    is_termination_msg=is_termination_msg,)

Note that of all agents, only the engineer can execute code. The rest of the agents can only send messages to each other. Let's create the group chat and the manager:

groupchat = autogen.GroupChat(    agents=[user_proxy, analyst, engineer, bear, bull], messages=[], max_round=20)manager = autogen.GroupChatManager(groupchat=groupchat, llm_config=llm_config)

The max_round parameter tells the manager to stop the conversation after 20 rounds. We're ready to start the conversation. Let's pass our message to the manager:

message = """Analyze $ETH and $BTC based on the latest 20 news articles and prices for thelast 14 days."""user_proxy.initiate_chat(manager, clear_history=True, message=message)

The Analyst tells the Engineer to fetch the historical prices for the last 14 days. Here's the discussion after that:

Bear

The recent price data for both $BTC and $ETH shows a downward trend, indicatingbearish sentiment. The consistent decrease in prices over the past 14 dayssuggests that investors are selling off their holdings, which could lead tofurther price drops.

Bull

While it's true that there's been a slight decrease in prices over the past 14days, this could be seen as a healthy correction in a broader bullish trend. Thehigh trading volumes for both $BTC and $ETH suggest strong market interest,which could fuel a price surge in the near future.

The Analyst tells the Engineer to fetch the latest 20 news articles. Here's the discussion after that:

Bull

The latest news articles show a positive sentiment overall, with developmentslike Circle's initiative to make USDC accessible on Polygon PoS, Immutable'scollaboration with Amazon Web Services, and Binance's commitment to invest inpromising crypto startups. These advancements suggest a bullish future forcryptocurrencies as they gain more mainstream acceptance and infrastructuresupport.

Bear

The latest news articles show a mix of sentiment, but there are several bearishindicators. For instance, Bitfinex's parent company is considering a $150million share repurchase amidst rising regulatory attention, suggestingpotential instability. Additionally, the collapse of crypto exchange FTX and thehalted cryptocurrency accounts associated with Hamas indicate potential risksand volatility in the market. These factors could contribute to a bearishoutlook for cryptocurrencies.

Analyst

Based on the discussion with the bull and the bear, as well as my own analysisof the price data and news sentiment, here is my report: $BTC: The recent price trend is slightly bearish, but the overall news sentimentis positive. The high trading volumes suggest strong market interest. However,potential regulatory issues and market volatility could pose risks. Myrecommendation is HODL with a score of 50, indicating a neutral outlook. $ETH: Similar to $BTC, the price trend for $ETH is slightly bearish, but thenews sentiment is generally positive. The high trading volumes and developmentslike the collaboration between Immutable and Amazon Web Services suggest abullish future. My recommendation is HODL with a score of 60, indicating aslightly bullish outlook. TERMINATE.

The conversation went well. The analyst was able to get the latest news and prices from the engineer, then ask the bull and the bear for their opinion. Finally, you got a report with a recommendation (HODL) for both cryptocurrencies and a related score. The analyst also gave a short explanation for their decision.

Conclusion

Honestly, I am impressed with the AutoGen library. It's a great way to build AI agents and solve tasks that a single prompt can't. I hope you enjoyed this tutorial and learned something new. If you want to learn more about AutoGen, check out the official documentation(opens in a new tab).

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/816144.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

PostgreSQL入门到实战-第二十四弹

PostgreSQL入门到实战 PostgreSQL中表连接操作(八)官网地址PostgreSQL概述PostgreSQL中CROSS JOIN命令理论PostgreSQL中CROSS JOIN命令实战更新计划 PostgreSQL中表连接操作(八) 使用PostgreSQL CROSS JOIN从连接的表中生成行的笛卡尔乘积。 官网地址 声明: 由于操作系统, 版…

数据库(3)

目录 11.那你知道什么是覆盖索引和回表吗? 12.什么是MVCC?说说MySQL实现MVCC的原理? 13.MySQL的锁的类型有哪些呢? 14.你们数据量级多大?分库分表是怎么做的? 15.分表后非分库字段sharding_key的查询怎…

C语言学习笔记之结构体(一)

目录 什么是结构体? 结构体的声明 结构体变量的定义和初始化 结构体成员的访问 结构体传参 什么是结构体? 在现实生活中的很多事物无法用单一类型的变量就能描述清楚,如:描述一个学生,需要姓名,年龄&a…

复旦新出!大规模语言模型:从理论到实践,书籍PDF分享

自2018年以来&#xff0c;包含Google、OpenAI、Meta、百度、华为等公司和研究机构都纷纷发布了包括BERT&#xff0c; GPT等在内多种模型&#xff0c;并在几乎所有自然语言处理任务中都表现出色。 今天给大家推荐一本大模型方面的书籍<大规模语言模型&#xff1a;从理论到实…

jupyter切换不同的内核(虚拟环境)(anaconda 24.1.2)

jupyter切换不同的内核&#xff08;anaconda 24.1.2&#xff09; 主要的两条命令&#xff1a; conda install ipykernel python -m ipykernel install --user --name 环境名称 anaconda的版本号 conda --version实例&#xff1a; 一、首先可以看到已经创…

【Linux】进程学习① (进程的PCB(task_struct)进程的标识符详解进程的创建fork函数)

目录 ​编辑 1.进程的概念 1.1进程的描述与组织&#xff1a;进程的PCB 进程&#xff1a;进程是 内核pcb对象可执行程序/内核数据结构可执行程序进程 1.3 task_struct 2.PCB内部属性 3 查看进程 4.获取进程标识符&#xff1a;getpid函数&#xff08;4-6主要围绕进程的标识符展开…

音频变速python版

音频变速 如何能在不改变音频其他特点的情况下&#xff0c;只改变语速呢&#xff1f; 有几个python的库可以实现该功能&#xff0c;下面一一介绍。 pydub库 首先&#xff0c;确保安装了pydub和ffmpeg。 下面是一个简单的Python脚本&#xff0c;展示如何改变音频的播放速度&a…

韩顺平Java | C25 JDBC和连接池(上)

概述 JDBC概述&#xff1a;JDBC为访问不同数据库提供统一接口&#xff0c;为使用者屏蔽细节问题。Java程序员使用JDBC可以连接任何提供了JDBC驱动程序的数据库系统&#xff0c;从而完成对数据库的各种操作。 // 模拟代码 //JdbcInterface.java --Java规定的JDBC接口(方法) p…

redis的设计与实现(五)——独立功能

1. Redis的其他功能 redis 除了简单对对象的增删改查的功能之外&#xff0c;其实还有其他高级功能&#xff0c;了解这些内容有利于我们更灵活的使用 redis 完成我们的业务功能。 2. 发布与订阅 2.1. 基本概念 很多中间件都有发布与订阅功能&#xff0c;但是&#xff0c;作为一…

文献阅读:LESS: Selecting Influential Data for Targeted Instruction Tuning

文献阅读&#xff1a;LESS: Selecting Influential Data for Targeted Instruction Tuning 1. 文章简介2. 方法介绍 1. Overview2. 原理说明 1. SGD上的定义2. Adam上的定义 3. 具体实现 1. Overview1. LoRA使用2. 数据选择3. LESS-T 3. 实验考察 & 结论 1. 实验设计2. 主…

UE5 在骨骼动画模型上绘制贴图

参考&#xff1a;Unreal 5.1 - How to paint damage textures and other effects on skeletal meshes 针对模型&#xff0c;在运行状态下通过射线指定一定范围&#xff0c;添加材质效果。 核心思路 通过射线获取命中点&#xff0c;作为材质参数材质中&#xff0c;命中的世界…

DP练习_P1002 [NOIP2002 普及组] 过河卒_python_蓝桥杯

P1002 [NOIP2002 普及组] 过河卒 - 洛谷 | 计算机科学教育新生态 (luogu.com.cn) 1.DFS做超时40分 n, m, x, y map(int,input().split())flag [[0]*(n10) for _ in range(m10)] maps [[0]*(n10) for _ in range(m10)] d [[2,1],[2,-1],[-2,1],[-2,-1],[1,2],[1,-2],[-1,2]…

matlab 安装 mingw64(6.3.0),OPENEXR

matlab安装openexr 1. matlab版本与对应的mingw版本选择2. mingw&#xff08;6.3.0&#xff09;下载地址&#xff1a;3. matlab2020a配置mingw&#xff08;6.3.0&#xff09;流程“4. matlab 安装openexr方法一&#xff1a;更新matlab版本方法二&#xff1a;其他博文方法方法三…

【算法刷题 | 二叉树 06】4.10( 路径总和、路径总和 || )

文章目录 13.路径总和13.1问题13.2解法一&#xff1a;递归13.2.1递归思路&#xff08;1&#xff09;确定递归函数参数以及返回值&#xff08;2&#xff09;确定终止条件&#xff08;3&#xff09;确定递归逻辑 13.2.2代码实现 14.路径总和 ||14.1问题14.2解法一&#xff1a;递归…

HarmonyOS鸿蒙端云一体化开发--适合小白体制

端云一体化 什么是“端”&#xff0c;什么是“云”&#xff1f; 答&#xff1a;“端“&#xff1a;手机APP端 “云”:后端服务端 什么是端云一体化&#xff1f; 端云一体化开发支持开发者在 DevEco Studio 内使用一种语言同时完成 HarmonyOS 应用的端侧与云侧开发。 …

探索NDVI:了解植被指数的意义与应用

随着科技的进步和遥感技术的发展&#xff0c;我们能够更深入地了解地球上的植被覆盖情况&#xff0c;而其中一项重要的工具就是NDVI&#xff08;Normalized Difference Vegetation Index&#xff0c;归一化植被指数&#xff09;。NDVI不仅仅是一个数值&#xff0c;更是一扇窥探…

Keil开启代码提示功能

本文介绍Keil5开启代码提示功能。 进入这个 如此设置&#xff1a; 有的电脑的左边是空白栏&#xff0c;没有设置选项。应该如何解决呢&#xff1f; 找到MDK525安装包&#xff0c;其他版本的 Keil5 应该也可以。 用你的解压软件把它打开&#xff1a; 解压后会多出这些文…

python之字符串操作

1、切片操作 跟列表的切片很相似 代码示例 str1 chengxianzi996 print(str1[0:2]) print(str1[:10]) 代码解释&#xff1a;第一行&#xff1a;创建了一个字符串对象&#xff08;其中单引号和双引号都可以创建字符串&#xff09; 第二行提取前两个字符并输出 第三行输出s…

Linux LVM磁盘扩容

1、查看磁盘情况 df -h df -h2、查看逻辑卷 lvdisplay lvdisplay3、查看逻辑组 vgdisplay vgdisplay4、查看物理卷 pvdisplay pvdisplay5、查看磁盘 fdisk -l fdisk -l6、磁盘分区fdisk /dev/磁盘名 # 上一步查看到的新硬盘路径 fdisk /dev/vdb7、格式化磁盘mkfs -t ext4…

梯度提升树(Gradient Boosting Trees)

通过5个条件判定一件事情是否会发生&#xff0c;5个条件对这件事情是否发生的影响力不同&#xff0c;计算每个条件对这件事情发生的影响力多大&#xff0c;写一个梯度提升树&#xff08;Gradient Boosting Trees&#xff09;模型程序,最后打印5个条件分别的影响力。 示例一 梯…