Python 模擬試験

Pythonデータ分析 模擬試験 第2回 問37・4章4節 scikit-learn(モデルの評価)

stratify を指定した分割

次のコードを実行したときの出力として、正しいものを1つ選べ。

import numpy as np
from sklearn.model_selection import train_test_split
y = np.array([0] * 8 + [1] * 2)
X = np.arange(10).reshape(10, 1)
_, _, _, y_test = train_test_split(X, y, test_size=0.5, stratify=y, random_state=0)
print(int(y_test.sum()), len(y_test))
  1. A

    2 5

  2. B

    1 5

  3. C

    0 5

  4. D

    1 10

正解と解説を見る

正解:B

stratify=y を指定すると、分割後もクラスの比率が保たれる。クラスが偏ったデータで重要。

順実行する行実行後の変数
1`import numpy as np`—
2`from sklearn.model_selection import train_tes…`—
3`y = np.array([0] * 8 + [1] * 2)`y = [0, 0, 0, 0, 0, 0, 0, 0, 1, 1]
4`X = np.arange(10).reshape(10, 1)`X = [[0], [1], [2], [3], [4], [5], [6], [7]…
5`_, _, _, y_test = train_test_split(X, y, test…`y_test = [0, 0, 0, 1, 0], X = [[0], [1], [2], [3], [4], [5], [6], [7]…
6`print(int(y_test.sum()), len(y_test))`y_test = [0, 0, 0, 1, 0]
結果実際の出力1 5

学習のポイント:分割の再現には random_state を指定する。

この問題を演習で解く →

問題一覧へ

このサイトの問題は、各試験の公式に示された出題範囲に沿って作ったオリジナルの模擬問題です。本試験の問題ではありません。一般社団法人Pythonエンジニア育成推進協会の公式サービスではありません。