在本教程中,我們將學習如何利用Google的雙子座模型的力量以及熊貓的靈活性。我們將對經典泰坦尼克號數據集進行直接和復雜的數據分析。通過將ChatGoogleGenerativeAi客戶端與Langchain的實驗Pandas DataFrame代理相結合,我們將設置一個可以解釋自然語言查詢的交互式“代理”。它將檢查數據,計算統計信息,發現相關性並生成視覺見解,而無需為每個任務編寫手動代碼。我們將瀏覽基本的探索步驟(例如計算行或計算生存率)。我們將通過人口統計細分和票價相關性來深入研究諸如生存率之類的高級分析。然後,我們將比較跨多個數據范圍的修改。最後,我們將建立自定義評分和圖案挖掘程序來提取新穎的見解。
!pip install langchain_experimental langchain_google_genai pandas
import os
import pandas as pd
import numpy as np
from langchain.agents.agent_types import AgentType
from langchain_experimental.agents.agent_toolkits import create_pandas_dataframe_agent
from langchain_google_genai import ChatGoogleGenerativeAI
os.environ("GOOGLE_API_KEY") = "Use Your Own API Key"
首先,我們使用PIP安裝了所需的庫,Langchain_exprementim,Langchain_google_genai和Pandas,啟用DataFrame Agent和Google Gemini集成。然後導入核心模塊。接下來,設置您的Google_api_key環境變量,我們隨時準備實例化雙子座驅動的熊貓代理進行對話數據分析。
def setup_gemini_agent(df, temperature=0, model="gemini-1.5-flash"):
llm = ChatGoogleGenerativeAI(
model=model,
temperature=temperature,
convert_system_message_to_human=True
)
agent = create_pandas_dataframe_agent(
llm=llm,
df=df,
verbose=True,
agent_type=AgentType.OPENAI_FUNCTIONS,
allow_dangerous_code=True
)
return agent
該輔助功能通過我們選擇的模型和溫度來初始化雙子座驅動的LLM客戶端。然後,它將其包裹在蘭班潘達(Langchain Pandas DataFrame)代理中,該代理可以針對我們的數據框架執行自然語言查詢(包括“危險”代碼)。只需傳遞我們的數據框架即可返回一個交互式代理,準備對話分析即可。
def load_and_explore_data():
print("Loading Titanic Dataset...")
df = pd.read_csv(
"https://raw.githubusercontent.com/pandas-dev/pandas/main/doc/data/titanic.csv"
)
print(f"Dataset shape: {df.shape}")
print(f"Columns: {list(df.columns)}")
return df
此功能直接從熊貓Github儲備金中獲取泰坦尼克號CSV。它還打印出其尺寸和列的名稱,以進行快速的理智檢查。然後,它返回加載的數據框,因此我們可以立即開始探索性分析。
def basic_analysis_demo(agent):
print("\nBASIC ANALYSIS DEMO")
print("=" * 50)
queries = (
"How many rows and columns are in the dataset?",
"What's the survival rate (percentage of people who survived)?",
"How many people have more than 3 siblings?",
"What's the square root of the average age?",
"Show me the distribution of passenger classes"
)
for query in queries:
print(f"\nQuery: {query}")
try:
result = agent.invoke(query)
print(f"Result: {result('output')}")
except Exception as e:
print(f"Error: {e}")
此演示例程通過打印標頭開始了“基本分析”會話。然後,它通過一組常見的探索性查詢(例如數據集維度,生存率,家庭計數和班級分佈)來迭代。對於每個自然語言提示,它都會調用代理。後來,它捕獲其輸出並打印結果或錯誤。
def advanced_analysis_demo(agent):
print("\nADVANCED ANALYSIS DEMO")
print("=" * 50)
advanced_queries = (
"What's the correlation between age and fare?",
"Create a survival analysis by gender and class",
"What's the median age for each passenger class?",
"Find passengers with the highest fares and their details",
"Calculate the survival rate for different age groups (0-18, 18-65, 65+)"
)
for query in advanced_queries:
print(f"\nQuery: {query}")
try:
result = agent.invoke(query)
print(f"Result: {result('output')}")
except Exception as e:
print(f"Error: {e}")
此“高級分析”功能打印一個標題,然後運行一系列更複雜的查詢。它計算相關性,執行分層的生存分析,計算中位數統計數據,並針對我們的雙子座驅動的數據幀代理進行詳細的過濾。它循環瀏覽每個自然語言提示,捕獲代理的響應並打印結果(或錯誤)。因此,它證明了我們可以輕鬆地利用對話式AI來對我們的數據集進行更深入的分段見解。
def multi_dataframe_demo():
print("\nMULTI-DATAFRAME DEMO")
print("=" * 50)
df = pd.read_csv(
"https://raw.githubusercontent.com/pandas-dev/pandas/main/doc/data/titanic.csv"
)
df_filled = df.copy()
df_filled("Age") = df_filled("Age").fillna(df_filled("Age").mean())
agent = setup_gemini_agent((df, df_filled))
queries = (
"How many rows in the age column are different between the two datasets?",
"Compare the average age in both datasets",
"What percentage of age values were missing in the original dataset?",
"Show summary statistics for age in both datasets"
)
for query in queries:
print(f"\nQuery: {query}")
try:
result = agent.invoke(query)
print(f"Result: {result('output')}")
except Exception as e:
print(f"Error: {e}")
該演示說明瞭如何在多個數據范圍內旋轉雙子座驅動的代理。在這種情況下,它包括原始的泰坦尼克號數據和估算年齡缺失的版本。因此,我們可以使用簡單的自然語言提示詢問跨數據庫比較問題(例如行計數的差異,平均年齡比較,缺失百分比和並排摘要統計數據)。
def custom_analysis_demo(agent):
print("\nCUSTOM ANALYSIS DEMO")
print("=" * 50)
custom_queries = (
"Create a risk score for each passenger based on: Age (higher age = higher risk), Gender (male = higher risk), Class (3rd class = higher risk), Family size (alone or large family = higher risk). Then show the top 10 highest risk passengers who survived",
"Analyze the 'deck' information from the cabin data: Extract deck letter from cabin numbers, Show survival rates by deck, Which deck had the highest survival rate?",
"Find interesting patterns: Did people with similar names (same surname) tend to survive together? What's the relationship between ticket price and survival? Were there any age groups that had 100% survival rate?"
)
for i, query in enumerate(custom_queries, 1):
print(f"\nCustom Analysis {i}:")
print(f"Query: {query(:100)}...")
try:
result = agent.invoke(query)
print(f"Result: {result('output')}")
except Exception as e:
print(f"Error: {e}")
此例程通過瀏覽三個複雜的多步提示來開始“自定義分析”會話。它建立了乘客風險計量模型,提取和評估基於甲板的生存率,並基於姓氏的生存模式和票價/年齡異常值。因此,我們可以看到我們的雙子座驅動的代理如何輕鬆地處理定制的定制,特定於域的調查,而自然語言查詢。
def main():
print("Advanced Pandas Agent with Gemini Tutorial")
print("=" * 60)
if not os.getenv("GOOGLE_API_KEY"):
print("Warning: GOOGLE_API_KEY not set!")
print("Please set your Gemini API key as an environment variable.")
return
try:
df = load_and_explore_data()
print("\nSetting up Gemini Agent...")
agent = setup_gemini_agent(df)
basic_analysis_demo(agent)
advanced_analysis_demo(agent)
multi_dataframe_demo()
custom_analysis_demo(agent)
print("\nTutorial completed successfully!")
except Exception as e:
print(f"Error: {e}")
print("Make sure you have installed all required packages and set your API key.")
if __name__ == "__main__":
main()
main()函數是教程的起點。它驗證了我們的雙子座API密鑰是否已設置,加載並探索泰坦尼克號數據集,並初始化對話pandas代理。然後,它依次運行基本,高級,多數據框和自定義分析演示。最後,它將整個工作流程包裝在嘗試/除外,除了塊以外,要捕獲並報告任何錯誤,然後在信號成功完成之前。
df = pd.read_csv("https://raw.githubusercontent.com/pandas-dev/pandas/main/doc/data/titanic.csv")
agent = setup_gemini_agent(df)
agent.invoke("What factors most strongly predicted survival?")
agent.invoke("Create a detailed survival analysis by port of embarkation")
agent.invoke("Find any interesting anomalies or outliers in the data")
最後,我們直接加載泰坦尼克號數據,實例化我們的雙子座驅動的熊貓代理,並發射三個一次性查詢。我們確定關鍵的生存預測因子,通過登陸端口分解生存,並發現異常或異常值。我們實現了所有這些,而無需修改我們的任何演示功能。
總之,通過Langchain DataFrame代理將大熊貓與雙子座結合在一起,將數據探索從編寫樣板代碼轉換為製作清晰的自然語言查詢。無論我們是計算摘要統計數據,構建自定義風險評分,比較多個數據范圍還是鑽入細微的生存分析,轉變都是明顯的。只需幾行設置,我們就會獲得一位交互式分析助理,可以隨時適應新的問題。它可以表面隱藏模式並加速我們的工作流程。
查看筆記本。 這項研究的所有信用都歸該項目的研究人員。另外,請隨時關注我們 嘰嘰喳喳 而且不要忘記加入我們的 99K+ ml子雷迪特 並訂閱 我們的新聞通訊。
Asif Razzaq是Marktechpost Media Inc.的首席執行官。作為一位有遠見的企業家和工程師,ASIF致力於利用人工智能的潛力來實現社會利益。他最近的努力是推出了人工智能媒體平台Marktechpost,該平台的深入覆蓋了機器學習和深度學習新聞,既在技術上都可以聽起來,既可以通過技術上的聲音,又可以被廣泛的受眾理解。該平台每月有超過200萬個觀點,說明了其在受眾中的受歡迎程度。
