pandasAIなるpythonライブラリがリリースされていたのでAzure OpenAI、langchainと組み合わせて試してみた。
PandasAIとは
PandasAIは、一般的なデータ分析・操作ツールであるpandasにGenerative AI機能を追加するPythonライブラリ。pandasと組み合わせて使用するように設計されており、pandasを置き換えるものではない。
PandasAIはpandas(および最もよく使われるデータ分析ライブラリ)を会話型にし、自然言語でデータに質問できるようにする。例えば、あるカラムの値が 5 より大きい DataFrame 内のすべての行を検索するよう PandasAI に依頼すると、その行のみを含む DataFrame を返す。
また、PandasAI にグラフの描画、データのクリーンアップ、欠損値のインプット、特徴量の生成を依頼することもできる。
インストール
pip install pandasai[langchain]
langchainのLLM定義(gpt-4モデルを使用)
pandasAIはLangchainのLLM定義をそのまま使うことができる。
https://docs.pandas-ai.com/en/latest/LLMs/langchain/
BASE_URL = "https://[].openai.azure.com/"
API_KEY = ""
DEPLOYMENT_NAME = "gpt-4"
from langchain.chat_models import AzureChatOpenAI
from langchain import LLMChain, PromptTemplate
llm = AzureChatOpenAI(
openai_api_base=BASE_URL,
openai_api_version="2023-07-01-preview",
deployment_name=DEPLOYMENT_NAME,
openai_api_key=API_KEY,
openai_api_type="azure",
)
PandasAIのSmartDataframe定義
pandasDFとlangchainのLLM定義を引数として、SmartDataframeを定義する。
import pandas as pd
from pandasai import SmartDataframe
df = pd.DataFrame({
"country": ["United States", "United Kingdom", "France", "Germany", "Italy", "Spain", "Canada", "Australia", "Japan", "China"],
"gdp": [19294482071552, 2891615567872, 2411255037952, 3435817336832, 1745433788416, 1181205135360, 1607402389504, 1490967855104, 4380756541440, 14631844184064],
"happiness_index": [6.94, 7.16, 6.66, 7.07, 6.38, 6.4, 7.23, 7.22, 5.87, 5.12]
})
df = SmartDataframe(df, config={"llm": llm})
PandasAIへの分析問い合わせ
SmartDataframeのchatメソッドで自然言語で分析の問い合わせを行うことができる。
df.chat('Which are the 5 happiest countries?')
df.chat('最もGDPが高い国はどこですか?')
'The country with the highest GDP is United States.'
df.chat('GPDが高い国は幸せと言えますか?')
"Unfortunately, I was not able to answer your question, because of the following error:\n\nMissing optional dependency 'seaborn'. Use pip or conda to install seaborn.\n"
seabornライブラリをインストールするようエラーが出た。seabornはPythonの可視化ライブラリ。
インストールして再実行。
pip install seaborn
df.chat('GPDが高い国は幸せと言えますか?')
GDPが高いからといって幸せとは言えないらしい。
df.chat('Calculate the sum of the gdp of north american countries')
20901884461056
Canada + United StatesのGDPをちゃんと回答。
まとめ
インストールも簡単で、pandasデータに対して直接自然言語で分析指示できるのは便利。
疑問としては、chatGPTは計算処理が不得意(そのためにCoT等を使う)であるが、それを補えているのかという点。