0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Pythonで学ぶ機械学習ライブラリ「scikit-learn」徹底解説

Posted at

Pythonで学ぶ機械学習ライブラリ「scikit-learn」徹底解説

目次

  1. scikit-learnとは?
  2. インストール方法
  3. データセットの準備
  4. scikit-learnの基本的な流れ
  5. 分類問題の例
  6. 回帰問題の例
  7. モデルの評価方法
  8. データ前処理・特徴量エンジニアリング
  9. モデル選択とハイパーパラメータ調整
  10. まとめ

1. scikit-learnとは?

scikit-learn はPythonで使える機械学習ライブラリで、簡単にモデル構築・学習・評価ができることが特徴です。

特徴

  • 分類、回帰、クラスタリング、次元削減など幅広いアルゴリズムをサポート
  • データの前処理、交差検証、ハイパーパラメータチューニングも可能
  • pandasやnumpyと相性が良く、データ分析のワークフローに組み込みやすい

代表的な用途:

用途
分類(Classification) スパムメール判定、画像認識
回帰(Regression) 株価予測、住宅価格予測
クラスタリング(Clustering) 顧客分類、マーケティング分析
次元削減(Dimensionality Reduction) 主成分分析、データ圧縮

2. インストール方法

pip install scikit-learn

バージョン確認:

import sklearn
print(sklearn.__version__)

3. データセットの準備

scikit-learnには有名なサンプルデータセットが用意されています。

from sklearn.datasets import load_iris

data = load_iris()
X = data.data  # 説明変数
y = data.target  # 目的変数

print(X.shape, y.shape)  # (150, 4) (150,)

pandasと組み合わせると見やすくなります。

import pandas as pd

df = pd.DataFrame(X, columns=data.feature_names)
df['target'] = y
print(df.head())

4. scikit-learnの基本的な流れ

  1. データの準備
  2. 学習用とテスト用に分割
  3. モデルの選択
  4. 学習(fit
  5. 予測(predict
  6. モデル評価
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)

model = LogisticRegression(max_iter=200)
model.fit(X_train, y_train)
y_pred = model.predict(X_test)

accuracy = accuracy_score(y_test, y_pred)
print(f"Accuracy: {accuracy:.2f}")

5. 分類問題の例(Irisデータセット)

from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import confusion_matrix, classification_report

clf = DecisionTreeClassifier()
clf.fit(X_train, y_train)
y_pred = clf.predict(X_test)

print("Confusion Matrix:\n", confusion_matrix(y_test, y_pred))
print("Classification Report:\n", classification_report(y_test, y_pred))

ポイント

  • confusion_matrix で分類の精度や間違いを確認
  • classification_report で精度、再現率、F1スコアをまとめて確認

6. 回帰問題の例

from sklearn.linear_model import LinearRegression
from sklearn.datasets import make_regression
from sklearn.metrics import mean_squared_error, r2_score

X, y = make_regression(n_samples=100, n_features=1, noise=20, random_state=42)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)

model = LinearRegression()
model.fit(X_train, y_train)
y_pred = model.predict(X_test)

mse = mean_squared_error(y_test, y_pred)
r2 = r2_score(y_test, y_pred)
print(f"MSE: {mse:.2f}, R²: {r2:.2f}")

7. モデル評価方法

タイプ 評価指標 用途
分類 Accuracy, Precision, Recall, F1-score, Confusion Matrix 正解率、誤分類の確認
回帰 MSE, RMSE, R² 予測精度の確認
from sklearn.metrics import f1_score

f1 = f1_score(y_test, y_pred, average='macro')
print(f"F1 Score: {f1:.2f}")

8. データ前処理・特徴量エンジニアリング

機械学習の精度は データ前処理 に大きく依存します。

from sklearn.preprocessing import StandardScaler

scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)  # 平均0、分散1に正規化
  • カテゴリ変数のエンコーディング → OneHotEncoder
  • 欠損値処理 → SimpleImputer

9. モデル選択とハイパーパラメータ調整

from sklearn.model_selection import GridSearchCV
from sklearn.svm import SVC

param_grid = {'C':[0.1,1,10], 'kernel':['linear','rbf']}
grid = GridSearchCV(SVC(), param_grid, cv=5)
grid.fit(X_train, y_train)

print("Best Parameters:", grid.best_params_)
print("Best Score:", grid.best_score_)
  • GridSearchCV で複数パラメータを自動で試し、最適モデルを選択
  • クロスバリデーションで過学習を防ぐ

10. まとめ

  • scikit-learnは 機械学習の入門から応用まで 幅広く使える
  • データ準備 → 学習 → 予測 → 評価 の流れを理解することが重要
  • データ前処理・ハイパーパラメータ調整で精度は大きく変わる
  • 初心者でもサンプルデータや簡単なモデルで機械学習を体験可能

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?