ポケモンデータセット(CSVファイル)の読み込みと散布図(Python, pandas, matplotlib, seaborn を使用)
前準備
Python 3.12 のインストール
以下のいずれかの方法で Python 3.12 をインストールする。
方法1:winget によるインストール
Python がインストール済みの場合、この手順は不要である。管理者権限のコマンドプロンプトで以下を実行する。管理者権限のコマンドプロンプトを起動するには、Windows キーまたはスタートメニューから「cmd」と入力し、表示された「コマンドプロンプト」を右クリックして「管理者として実行」を選択する。
winget install -e --id Python.Python.3.12 --scope machine --silent --accept-source-agreements --accept-package-agreements --override "/quiet InstallAllUsers=1 PrependPath=1 AssociateFiles=1 InstallLauncherAllUsers=1"
--scope machine を指定することで、システム全体(全ユーザー向け)にインストールされる。このオプションの実行には管理者権限が必要である。インストール完了後、コマンドプロンプトを再起動すると PATH が自動的に設定される。
方法2:インストーラーによるインストール
- Python 公式サイト(https://www.python.org/downloads/)にアクセスし、「Download Python 3.x.x」ボタンから Windows 用インストーラーをダウンロードする。
- ダウンロードしたインストーラーを実行する。
- 初期画面の下部に表示される「Add python.exe to PATH」に必ずチェックを入れてから「Customize installation」を選択する。このチェックを入れ忘れると、コマンドプロンプトから
pythonコマンドを実行できない。 - 「Install Python 3.xx for all users」にチェックを入れ、「Install」をクリックする。
インストールの確認
コマンドプロンプトで以下を実行する。
python --version
バージョン番号(例:Python 3.12.x)が表示されればインストール成功である。「'python' は、内部コマンドまたは外部コマンドとして認識されていません。」と表示される場合は、インストールが正常に完了していない。
AIエディタ Windsurf のインストール
Pythonプログラムの編集・実行には、AIエディタの利用を推奨する。ここでは、Windsurfのインストールを説明する。
Windsurf がインストール済みの場合、この手順は不要である。管理者権限のコマンドプロンプトで以下を実行する。管理者権限のコマンドプロンプトを起動するには、Windows キーまたはスタートメニューから「cmd」と入力し、表示された「コマンドプロンプト」を右クリックして「管理者として実行」を選択する。
winget install -e --id Codeium.Windsurf --scope machine --accept-source-agreements --accept-package-agreements --override "/VERYSILENT /NORESTART /MERGETASKS=!runcode,addtopath,associatewithfiles,!desktopicon"
powershell -Command "$env:Path=[System.Environment]::GetEnvironmentVariable('Path','Machine')+';'+[System.Environment]::GetEnvironmentVariable('Path','User'); windsurf --install-extension MS-CEINTL.vscode-language-pack-ja --force; windsurf --install-extension ms-python.python --force"
--scope machine を指定することで、システム全体(全ユーザー向け)にインストールされる。このオプションの実行には管理者権限が必要である。インストール完了後、コマンドプロンプトを再起動すると PATH が自動的に設定される。
【関連する外部ページ】
Windsurf の公式ページ: https://windsurf.com/
Gitのインストール
以下のコマンドを管理者権限のコマンドプロンプトで実行する
(手順:Windowsキーまたはスタートメニュー → cmd と入力 → 右クリック → 「管理者として実行」)。管理者権限は、wingetの--scope machineオプションでシステム全体にソフトウェアをインストールするために必要となる。
REM Git をシステム領域にインストール
winget install --scope machine --id Git.Git -e --silent --accept-source-agreements --accept-package-agreements
REM Git のパス設定
set "GIT_PATH=C:\Program Files\Git\cmd"
for /f "skip=2 tokens=2*" %a in ('reg query "HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" /v Path') do set "SYSTEM_PATH=%b"
if exist "%GIT_PATH%" (
echo "%SYSTEM_PATH%" | find /i "%GIT_PATH%" >nul
if errorlevel 1 setx PATH "%GIT_PATH%;%SYSTEM_PATH%" /M >nul
)
Pokemon データセットの準備
謝辞:Pokemon データセットの作者に感謝します.
Windows の場合
Windows を使用する場合は,次のように操作する.
- データディレクトリの作成
mkdir /p c:\data
- カレントディレクトリの移動とデータのダウンロードと展開(解凍)
cd C:\data git clone https://gist.github.com/armgilles/194bcff35001e7eb53a2a8b441e8b2c6 move 194bcff35001e7eb53a2a8b441e8b2c6\pokemon.csv .
CSV ファイル pokemon.csv が,データディレクトリにできる
Ubuntu, Debian 系(Ubuntu や RaspyerryPi など)のとき
- 前準備
wget, p7zip-full のインストール
# パッケージリストの情報を更新 sudo apt update sudo apt -y install wget p7zip-full - データディレクトリの作成と,カレントディレクトリの移動
sudo mkdir /usr/local/dt sudo chown -R ${USER}:${USER} /usr/local/dt cd /usr/local/dt
- データのダウンロードと展開(解凍)
CSV ファイル pokemon.csv が,データディレクトリにできる
wget https://gist.github.com/armgilles/194bcff35001e7eb53a2a8b441e8b2c6/archive/92200bc0a673d5ce2110aaad4544ed6c4010f687.zip "c:\Program Files\7-Zip\7z.exe" x -o/usr/local/dt 92200bc0a673d5ce2110aaad4544ed6c4010f687.zip rm -f 92200bc0a673d5ce2110aaad4544ed6c4010f687.zip mv 194bcff35001e7eb53a2a8b441e8b2c6-92200bc0a673d5ce2110aaad4544ed6c4010f687/pokemon.csv . rmdir 194bcff35001e7eb53a2a8b441e8b2c6-92200bc0a673d5ce2110aaad4544ed6c4010f687 ls -la pokemon.csv
Python のデータフレームで扱ってみる
- CSV ファイルの読み込み
import pandas as pd pokemon = pd.read_csv("C:/data/pokemon.csv")
- データの確認
print(pokemon.head())
- 基本的な情報の表示
- head: 先頭部分の表示
- shape: サイズ
- ndim: 次元数
- columns: 属性名
- info(): 各属性のデータ型
print(pokemon.head()) print(pokemon.info()) print(pokemon.shape) print(pokemon.ndim) print(pokemon.columns)
4. pokemon データセットの主成分分析プロット
- 主成分分析プロットの前準備
import numpy as np import sklearn.decomposition %matplotlib inline import matplotlib.pyplot as plt import warnings warnings.filterwarnings('ignore') # Suppress Matplotlib warnings # 主成分分析 def prin(A, n): pca = sklearn.decomposition.PCA(n_components=n) return pca.fit_transform(A) # 主成分分析で2つの成分を得る def prin2(A): return prin(A, 2) # M の最初の2列を,b で色を付けてプロット.b はラベル def scatter_label_plot(M, b, alpha): a12 = pd.DataFrame( M[:,0:2], columns=['a1', 'a2'] ) f = pd.factorize(b) a12['target'] = f[0] g = sns.scatterplot(x='a1', y='a2', hue='target', data=a12, palette=sns.color_palette("hls", np.max(f[0]) + 1), legend="full", alpha=alpha) # lenend を書き換え labels=f[1] for i, label in enumerate(labels): g.legend_.get_texts()[i].set_text(label) plt.show() # 主成分分析プロット def pcaplot(A, b, alpha): scatter_label_plot(prin2(A), b, alpha)
- 主成分分析プロット
X = pokemon.iloc[:,4:7].to_numpy() y = pokemon.iloc[:,2] pcaplot(X, y, 0.4)