В этом руководстве мы узнаем, как использовать возможности моделей Google Gemini вместе с гибкостью Pandas. Мы выполним как простой, так и сложный анализ данных на классическом наборе данных «Титаник».
Этапы работы
1. Установка необходимых библиотек:
Используем `pip` для установки `langchainexperimental`, `langchaingoogle_genai` и `pandas`.
“`python
!pip install langchainexperimental langchaingoogle_genai pandas
“`
2. Импорт основных модулей:
“`python
import os
import pandas as pd
import numpy as np
from langchain.agents.agent_types import AgentType
from langchainexperimental.agents.agenttoolkits import createpandasdataframe_agent
from langchaingooglegenai import ChatGoogleGenerativeAI
“`
3. Настройка переменной окружения для API-ключа Google:
“`python
os.environ[“GOOGLEAPIKEY”] = “Use Your Own API Key”
“`
4. Создание агента на основе Gemini для анализа данных:
“`python
def setupgeminiagent(df, temperature=0, model=”gemini-1.5-flash”):
llm = ChatGoogleGenerativeAI(
model=model,
temperature=temperature,
convertsystemmessagetohuman=True
)
agent = createpandasdataframe_agent(
llm=llm,
df=df,
verbose=True,
agenttype=AgentType.OPENAIFUNCTIONS,
allowdangerouscode=True
)
return agent
“`
5. Загрузка и исследование данных:
“`python
def loadandexplore_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
“`
6. Демонстрация базового анализа:
“`python
def basicanalysisdemo(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}”)
“`
7. Демонстрация продвинутого анализа:
“`python
def advancedanalysisdemo(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}”)
“`
Этот подход позволяет преобразовать анализ данных из написания стандартного кода в формулирование чётких запросов на естественном языке. Будь то вычисление сводных статистик, построение пользовательских оценок риска, сравнение нескольких DataFrames или детальный анализ выживаемости, трансформация очевидна. С помощью всего нескольких строк настройки мы получаем интерактивного помощника по аналитике, который может адаптироваться к новым вопросам на лету. Он может выявлять скрытые закономерности и ускорять наш рабочий процесс.
Проверьте [Notebook](https://example.com). Все заслуги за это исследование принадлежат исследователям этого проекта. Также подписывайтесь на нас в [Twitter](https://example.com) и присоединяйтесь к нашему [ML SubReddit](https://example.com) и подписывайтесь на [наш Newsletter](https://example.com).