問題
勾配降下法は、勾配と逆方向に動くことで重みを少しずつ改善します。
w ← w - learning_rate × dL/dw
確率的勾配降下法で sigmoid ニューロンを学習させてください。各エポックでサンプルを与えられた順番どおりに処理し、各サンプルについて:
- z = sample · weights + bias、y = 1 / (1 + e^(-z))
- delta = 2 × (y - target) × y × (1 - y)
- weights[i] ← weights[i] - learning_rate × delta × sample[i](すべての i について)、その後 bias ← bias - learning_rate × delta
train_neuron(samples, targets, weights, bias, learning_rate, epochs) を実装してください。
入力
samples: m 個の学習例。各例は n 個の値を持ちます。
targets: m 個の正しい出力(0 から 1)。
weights, bias: 初期の重み(n 個)とバイアス。
learning_rate, epochs: ステップ幅と、データを何周するか。
出力
学習後の重みと、その後に学習後のバイアス(n + 1 個の数)を返してください。
制約
1 ≤ m ≤ 50、1 ≤ n ≤ 10、1 ≤ epochs ≤ 1,000
0 < learning_rate ≤ 5
-5 ≤ 各値 ≤ 5
例
入力:
bias = 0.0
epochs = 1
samples = [
[1.0]
]
targets = [1.0]
weights = [0.0]
learning_rate = 1.0
期待される出力:
expected = [0.25, 0.25]
入力:
double bias = 0.0;
long long epochs = 1;
std::vector<std::vector<double>> samples = {
{1.0}
};
std::vector<double> targets = {1.0};
std::vector<double> weights = {0.0};
double learning_rate = 1.0;
期待される出力:
std::vector<double> expected = {0.25, 0.25};
入力:
double bias = 0.0;
long epochs = 1;
double[][] samples = new double[][] {
new double[] {1.0}
};
double[] targets = new double[] {1.0};
double[] weights = new double[] {0.0};
double learning_rate = 1.0;
期待される出力:
double[] expected = new double[] {0.25, 0.25};
解説
y = σ(0) = 0.5、delta = 2 × (0.5 - 1) × 0.25 = -0.25。重み:0 - 1 × (-0.25) × 1 = 0.25。バイアス:0 - 1 × (-0.25) = 0.25。結果は [0.25, 0.25] です。
入力:
bias = 0.0
epochs = 500
samples = [
[0.0, 0.0],
[0.0, 1.0],
[1.0, 0.0],
[1.0, 1.0]
]
targets = [0.0, 0.0, 0.0, 1.0]
weights = [0.0, 0.0]
learning_rate = 2.0
期待される出力:
expected = [6.346558, 6.339863, -9.592092]
入力:
double bias = 0.0;
long long epochs = 500;
std::vector<std::vector<double>> samples = {
{0.0, 0.0},
{0.0, 1.0},
{1.0, 0.0},
{1.0, 1.0}
};
std::vector<double> targets = {0.0, 0.0, 0.0, 1.0};
std::vector<double> weights = {0.0, 0.0};
double learning_rate = 2.0;
期待される出力:
std::vector<double> expected = {6.346558, 6.339863, -9.592092};
入力:
double bias = 0.0;
long epochs = 500;
double[][] samples = new double[][] {
new double[] {0.0, 0.0},
new double[] {0.0, 1.0},
new double[] {1.0, 0.0},
new double[] {1.0, 1.0}
};
double[] targets = new double[] {0.0, 0.0, 0.0, 1.0};
double[] weights = new double[] {0.0, 0.0};
double learning_rate = 2.0;
期待される出力:
double[] expected = new double[] {6.346558, 6.339863, -9.592092};
解説
これは論理 AND ゲートです。500 エポック後、2つの重みはどちらも大きな正の値になり、バイアスは大きな負の値になるため、入力 [1, 1] だけが 0.5 を超える出力になります。
解き方のヒント
まずは自分で考えてから、ヒントを 1 つずつ開いてみましょう。
ヒント 1
各 epoch で training sample を順番に処理し、各例の直後に weight を更新する。
ヒント 2
各 sample について sigmoid 出力を計算し、その gradient で weight と bias を下降方向に動かす。
ヒント 3
online 更新なので、同じ epoch の後半の sample は前半の更新の影響を受ける。
目安の計算量
時間 O(epochs × m × n)、追加メモリ O(1)
参考資料
この課題はCodeUtility用に調整されています。上記の説明と制約に従ってください。