Skip to content

第 4 章 ソースコード一覧

書籍第 4 章「機械学習の基礎」に掲載しているソースコードの一覧です。番号は書籍の「入力」番号と対応しています。上のバッジから、この章のコードをまとめた Google Colab ノートブックを開けます。

入力 4.1: train_test_splitによるデータ分割

from sklearn.model_selection import train_test_split
import numpy as np

# サンプルデータ
X = np.array([[1], [2], [3], [4], [5],
              [6], [7], [8], [9], [10]])
y = np.array([2, 4, 6, 8, 10, 12, 14, 16, 18, 20])

# 基本的な使い方
X_train, X_test, y_train, y_test = train_test_split(
    X, y,
    test_size=0.2,     # テストデータの割合(20%)
    random_state=42    # 乱数シード(再現性のため)
)

print(f"訓練データ数: {len(X_train)}")  # 8
print(f"テストデータ数: {len(X_test)}")  # 2

入力 4.2: k-means法によるクラスタリング

from sklearn.cluster import KMeans
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np

# データの読み込み(seaborn 版 iris。ラベルは使わない)
df = sns.load_dataset("iris")
X = df[["sepal_length", "sepal_width",
        "petal_length", "petal_width"]].values

# k-means法によるクラスタリング(3クラスタ)
kmeans = KMeans(n_clusters=3, random_state=42, n_init=10)
kmeans.fit(X)

# クラスタのラベルを取得
labels = kmeans.labels_
print(f"各クラスタのデータ数: {np.bincount(labels)}")

入力 4.3: クラスタリング結果の可視化

import matplotlib.pyplot as plt

# クラスタリング結果の可視化
plt.figure(figsize=(8, 5))
scatter = plt.scatter(X[:, 2], X[:, 3],
                      c=labels, cmap="viridis", alpha=0.6)

# 重心の表示
centers = kmeans.cluster_centers_
plt.scatter(centers[:, 2], centers[:, 3],
            c="red", marker="x", s=200, linewidths=3,
            label="重心")

plt.xlabel("花弁の長さ (cm)")
plt.ylabel("花弁の幅 (cm)")
plt.title("k-means法によるクラスタリング(Irisデータセット)")
plt.legend()
plt.colorbar(scatter, label="クラスタ")
plt.tight_layout()
plt.show()

入力 4.4: scikit-learnによる実装の基本パターン

import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error

# 1. データの準備(X: 特徴量[面積, 築年数], y: ラベル[価格])
X = [[80, 5], [60, 15], [100, 2], [75, 8],
     [90, 3], [50, 20], [110, 1], [65, 12]]
y = [4500, 3200, 5800, 4200, 5100, 2800, 6200, 3500]

# 2. データの分割(再現性のため random_state を固定)
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.2, random_state=42
)

# 3. モデルの作成
model = LinearRegression()

# 4. モデルの学習
model.fit(X_train, y_train)

# 5. モデルの予測
y_pred = model.predict(X_test)

# 6. モデルの評価(誤差の指標 RMSE。第6章で詳しく学びます)
rmse = np.sqrt(mean_squared_error(y_test, y_pred))
print(f"誤差(RMSE): {rmse:.1f}")

入力 4.5: Estimatorインタフェースの利用パターン

from sklearn.モジュール名 import モデル名

# 1. モデルの作成
model = モデル名()

# 2. モデルの学習
model.fit(X_train, y_train)

# 3. モデルの予測
y_pred = model.predict(X_test)

# 4. モデルの評価
score = model.score(X_test, y_test)

入力 4.6: fit_transformによる標準化

from sklearn.preprocessing import (
    StandardScaler)
import numpy as np

X = np.array([[1, 100], [2, 200],
              [3, 300], [4, 400]])

# StandardScaler: 平均0、分散1に標準化する
scaler = StandardScaler()

# fit_transform で学習と変換を同時に行う
X_scaled = scaler.fit_transform(X)
print(X_scaled)

入力 4.7: load_irisによるデータセットの読み込み

from sklearn.datasets import load_iris

# データセットの読み込み
iris = load_iris()

# 特徴量とラベルの取得
X = iris.data          # 特徴量(150×4の配列)
y = iris.target        # ラベル(150個の配列)

print(f"特徴量の形状: {X.shape}")
print(f"ラベルの形状: {y.shape}")
print(f"特徴量名: {iris.feature_names[:2]}")
print(f"          {iris.feature_names[2:]}")
print(f"クラス名: {iris.target_names}")