問題
ロジスティック回帰は、はい/いいえの問題のための線形モデルです。各サンプルについて確率を計算し、それをクラスに変換します。
- z = x₁×w₁ + … + xₙ×wₙ + bias
- p = 1 / (1 + e^(-z))
- p ≥ threshold ならクラス 1、そうでなければ 0
logistic_predict(samples, weights, bias, threshold) を実装してください。
入力
samples: サンプルごとに n 個の特徴量の行。
weights: n 個の重み。
bias: バイアス。
threshold: クラス 1 と予測するのに必要な確率(0 と 1 の間、両端を含まない)。
出力
各サンプルの予測クラス(0 または 1)を順番に返してください。
制約
1 ≤ サンプル数 ≤ 1,000、1 ≤ n ≤ 50
-100 ≤ 各特徴量、重み、バイアス ≤ 100
0 < threshold < 1
例
例 1
入力:
bias = -1.0
samples = [
[2.0, 1.0],
[0.0, 0.0],
[-1.0, -3.0]
]
weights = [1.5, -0.5]
threshold = 0.5
期待される出力:
expected = [1, 0, 0]
入力:
double bias = -1.0;
std::vector<std::vector<double>> samples = {
{2.0, 1.0},
{0.0, 0.0},
{-1.0, -3.0}
};
std::vector<double> weights = {1.5, -0.5};
double threshold = 0.5;
期待される出力:
std::vector<long long> expected = {1, 0, 0};
入力:
double bias = -1.0;
double[][] samples = new double[][] {
new double[] {2.0, 1.0},
new double[] {0.0, 0.0},
new double[] {-1.0, -3.0}
};
double[] weights = new double[] {1.5, -0.5};
double threshold = 0.5;
期待される出力:
long[] expected = new long[] {1, 0, 0};
解説
サンプル1:z = 3 - 0.5 - 1 = 1.5、p ≈ 0.818 → 1。サンプル2:z = -1、p ≈ 0.269 → 0。サンプル3:z = -1.5 + 1.5 - 1 = -1、p ≈ 0.269 → 0。結果:[1, 0, 0]。
例 2
入力:
bias = -2.0
samples = [
[1.0],
[2.0],
[3.0]
]
weights = [1.0]
threshold = 0.7
期待される出力:
expected = [0, 0, 1]
入力:
double bias = -2.0;
std::vector<std::vector<double>> samples = {
{1.0},
{2.0},
{3.0}
};
std::vector<double> weights = {1.0};
double threshold = 0.7;
期待される出力:
std::vector<long long> expected = {0, 0, 1};
入力:
double bias = -2.0;
double[][] samples = new double[][] {
new double[] {1.0},
new double[] {2.0},
new double[] {3.0}
};
double[] weights = new double[] {1.0};
double threshold = 0.7;
期待される出力:
long[] expected = new long[] {0, 0, 1};
解説
確率は σ(-1) ≈ 0.269、σ(0) = 0.5、σ(1) ≈ 0.731 です。しきい値 0.7 に届くのは最後だけなので、結果は [0, 0, 1] です。
参考資料
この課題はCodeUtility用に調整されています。上記の説明と制約に従ってください。