LoginSignup
2
5

【Python】Geminiで遊んでみた!

Last updated at Posted at 2023-12-17

はじめに

2024年の初め頃までは無料でGemini Pro APIが使えるらしいので遊んでみました!

初めにGemini APIの使い方を簡単に説明してから質問してみようと思います。

コード全体

PythonでGemini APIを使う

API Keyの作成

以下のサイトからAPI Keyを作成。

SDKのインストール

Python用のSDKをインストール。

pip install -q -U google-generativeai

ライブラリーのインポート

import textwrap
import os
from dotenv import load_dotenv

from IPython.display import display
from IPython.display import Markdown

# PythonのSDK(上でインストール済み)
import google.generativeai as genai

初期設定

関数定義

Geminiクイックスタートのマークダウン形式に変換する関数を定義。

def to_markdown(text):
    text = text.replace('', '  *')
    return Markdown(textwrap.indent(text, '> ', predicate=lambda _: True))

API Keyのセット

genai.configureにAPI Keyをセット。

load_dotenv('./.env')
GEMINI_API_KEY = os.environ['GEMINI_API_KEY']
genai.configure(api_key=GEMINI_API_KEY)

利用できるモデルの確認

現時点では"gemini-pro"と"gemini-pro-vision"のみ。

for m in genai.list_models():
  if 'generateContent' in m.supported_generation_methods:
    print(m.name)

使用例

gemini-pro

テキストプロンプトのみに適用。

question
model = genai.GenerativeModel('gemini-pro')
response = model.generate_content("What is the meaning of life?")
to_markdown(response.text)
answer
The meaning of life is a profound and philosophical question that has fascinated humans for millennia. There is no one definitive answer that satisfies everyone, as the meaning of life is personal and subjective. However, there are several perspectives and common themes that people have explored and discussed throughout history:

1. Purpose and Fulfillment: For many, finding meaning in life involves identifying their purpose and working towards achieving it. This purpose can be personal, such as raising a family or pursuing a creative passion, or it can be broader, like making a positive impact on society or the world. A sense of purpose can provide direction and motivation, leading to a feeling of fulfillment and accomplishment.

2. Relationships and Connections: Humans are social creatures, and strong relationships with family, friends, and loved ones can significantly contribute to a meaningful life. Nurturing these connections, providing support and receiving it in return, and sharing experiences can bring joy, love, and belonging.

3. Personal Growth and Development: Embracing personal growth and development can give life meaning. This could involve learning new skills, facing challenges, overcoming obstacles, and expanding one's knowledge and perspective. Continuously striving to become a better person, physically, mentally, or spiritually, can lead to a sense of accomplishment and fulfillment.

4. Contribution to Society: Many individuals find meaning in contributing to the well-being of others and society as a whole. This could involve volunteering, working in a helping profession, or simply performing acts of kindness. Helping others and making a positive impact can create a sense of purpose and significance.

5. Creativity and Expression: For some, expressing oneself creatively can be a powerful way to find meaning in life. Whether through art, music, writing, or other forms of creative expression, engaging in creative activities can allow individuals to communicate their thoughts, emotions, and unique perspectives.

6. Spiritual and Religious Beliefs: For many people, spiritual or religious beliefs provide a framework for understanding the meaning of life. Different religions and spiritual traditions offer explanations of the origins, purpose, and ultimate destiny of human existence. Following religious or spiritual practices and rituals can bring comfort, guidance, and a sense of connection to a higher power.

7. Unique Experiences and Perspectives: Life's meaning can be found in the unique experiences and perspectives each individual encounters. Embracing diversity, traveling, learning about different cultures, and pushing oneself outside of one's comfort zone can broaden one's horizons and lead to a deeper understanding of the world and one's place in it.

Ultimately, the search for meaning in life is an ongoing personal journey. It is not something that can be attained once and for all, but rather a continuous process of exploration, reflection, and growth.

gemini-pro-vision

テキストと画像プロンプトに適用。

test.jpg
img1.jpg

question
import PIL.Image

img = PIL.Image.open('./test_img/img1.jpg')

model = genai.GenerativeModel('gemini-pro-vision')
response = model.generate_content(img)

# imgとtextの合わせ技も可能
# response = model.generate_content(["Write an article based on this picture. Like a good forest.", img], stream=True)

to_markdown(response.text)
answer ( img )
This is a photo of a foggy forest.
answer( img & text )
# 合わせ技のアンサー
The picture shows a forest on a foggy day. The trees are tall and straight, and the leaves are a deep green. The forest is dense, and the trees are close together. The ground is covered with a thick layer of leaves. The forest is silent, and the only sound is the occasional rustle of leaves in the wind. The picture is peaceful and serene, and it captures the beauty of the natural world.

The forest is an important ecosystem. It provides a home for many different plants and animals. It also helps to clean the air and water, and it provides a place for people to relax and enjoy the outdoors. Forests are important to the health of the planet, and we must do our part to protect them.

質問してみよう!

質問1

「熱があるので会社を休むためのメールを考えて。本当に熱があるわけではありません。」

結果:Geminiは忠実でGPT3.5は真面目なイメージ。

Gemini
件名:本日欠勤のお知らせ

お世話になっております。 [あなたの名前]と申します。

本日は、熱があるため、欠勤させていただきます。 ご迷惑をおかけして申し訳ございません。

また、熱が下がり次第、出社いたします。

何卒ご理解のほど、よろしくお願いいたします。

敬具

[あなたの名前]
GPT3.5

もちろんです。ただし、偽りの情報を伝えることは倫理的に問題があるため、誠実に行動することをお勧めします。以下は、実際に体調が悪いわけではないが、休暇を取るためのメールの例です。こうした状況は正直であり、信頼関係を維持する上で重要です。

件名: 本日の欠勤について

お世話になっております。〇〇(あなたの名前)です。

突然のご連絡となり申し訳ございませんが、本日は体調不良のため出勤できない状況です。

今日はお休みをいただき、明日以降元気を取り戻して復帰できるよう努めます。

ご不便をおかけして申し訳ありませんが、どうぞよろしくお願いいたします。

よろしくお願いいたします。

〇〇(あなたの名前)

このような場合、人によっては会社の方針によっては証明書などを提出するよう求められることもあります。そのようなケースでは、偽りの情報を提供せず、正直に事実を伝えることが大切です。

質問2

「pythonでirisデータを読み込み、簡単な分析を行うプログラムを考えて。」

結果:GPT3.5の方が回答が柔軟?

Gemini
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

# Irisデータを読み込む
iris = pd.read_csv('iris.csv')

# 各特徴の統計量を表示
print(iris.describe())

# 特徴の相関関係を表示
print(iris.corr())

# ヒストグラムを表示
iris.hist()
plt.show()

# 散布図を表示
sns.pairplot(iris, hue='species')
plt.show()

# 各特徴を基準にした箱ひげ図を表示
iris.groupby('species').boxplot()
plt.show()
GPT3.5
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt

# Irisデータセットの読み込み
iris_url = "https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data"
column_names = ['sepal_length', 'sepal_width', 'petal_length', 'petal_width', 'species']
iris_data = pd.read_csv(iris_url, names=column_names)

# データの最初の数行を表示
print(iris_data.head())

# データの基本的な統計情報を表示
print(iris_data.describe())

# データの種類ごとの相関を可視化
sns.pairplot(iris_data, hue='species')
plt.show()

# データの箱ひげ図を作成
plt.figure(figsize=(10, 6))
sns.boxplot(data=iris_data, orient="h")
plt.title("Boxplot of Iris Dataset")
plt.show()

# 種ごとの特徴量の分布を可視化
plt.figure(figsize=(10, 6))
sns.histplot(data=iris_data, x='petal_length', hue='species', kde=True)
plt.title("Petal Length Distribution by Species")
plt.show()

おわりに

最後までご覧いただきありがとうございます!

今回はGeminiで遊んでみました。
次の記事では画像+テキストで何ができるか実験してみようと考えています。

初学者のため情報に誤りがある可能せいがあります。
ご了承ください。

参考文献

2
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
5