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))
- A
2 5 - B
1 5 - C
0 5 - 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 |
- A
誤り。評価用の 5 件に 1 は 1 件(2 割)入る。
- B
正しい。クラスの比率(0 が 8 割、1 が 2 割)を保って分割すると、評価用の 5 件に 1 が 1 件入る。
- C
誤り。
stratifyで比率が保たれる。 - D
誤り。評価用は 5 件。
このサイトの問題は、各試験の公式に示された出題範囲に沿って作ったオリジナルの模擬問題です。本試験の問題ではありません。一般社団法人Pythonエンジニア育成推進協会の公式サービスではありません。