โจทย์
ในการฝึกนิวรอน เราต้องรู้ว่าน้ำหนักแต่ละค่าส่งผลต่อความผิดพลาดอย่างไร สำหรับตัวอย่างฝึกหนึ่งตัว:
- z = inputs · weights + bias
- y = sigmoid(z) = 1 / (1 + e^(-z))
- ค่าสูญเสีย L = (y - target)²
ตามกฎลูกโซ่ เมื่อ delta = dL/dz = 2 × (y - target) × y × (1 - y):
- dL/dw_i = delta × x_i
- dL/dbias = delta
จงเขียน neuron_gradients(inputs, weights, bias, target)
อินพุต
inputs, weights: ลิสต์ที่มีความยาว n เท่ากัน
bias: ไบแอสของนิวรอน
target: เอาต์พุตที่ถูกต้องของตัวอย่างนี้ (ระหว่าง 0 ถึง 1)
เอาต์พุต
คืนค่าลิสต์ตัวเลข n + 1 ค่า: เกรเดียนต์ของน้ำหนักแต่ละค่าตามลำดับ แล้วตามด้วยเกรเดียนต์ของไบแอส
เงื่อนไข
1 ≤ n ≤ 100
-10 ≤ อินพุต น้ำหนัก และไบแอสแต่ละค่า ≤ 10
0 ≤ target ≤ 1
ตัวอย่าง
อินพุต:
bias = 0.0
inputs = [1.0, 2.0]
target = 1.0
weights = [0.5, -0.25]
ผลลัพธ์ที่คาดหวัง:
expected = [-0.25, -0.5, -0.25]
อินพุต:
double bias = 0.0;
std::vector<double> inputs = {1.0, 2.0};
double target = 1.0;
std::vector<double> weights = {0.5, -0.25};
ผลลัพธ์ที่คาดหวัง:
std::vector<double> expected = {-0.25, -0.5, -0.25};
อินพุต:
double bias = 0.0;
double[] inputs = new double[] {1.0, 2.0};
double target = 1.0;
double[] weights = new double[] {0.5, -0.25};
ผลลัพธ์ที่คาดหวัง:
double[] expected = new double[] {-0.25, -0.5, -0.25};
คำอธิบาย
z = 1×0.5 + 2×(-0.25) = 0 ดังนั้น y = 0.5 delta = 2 × (0.5 - 1) × 0.5 × 0.5 = -0.25 เกรเดียนต์: [-0.25×1, -0.25×2, -0.25] = [-0.25, -0.5, -0.25]
อินพุต:
bias = 0.0
inputs = [3.0]
target = 0.0
weights = [0.0]
ผลลัพธ์ที่คาดหวัง:
expected = [0.75, 0.25]
อินพุต:
double bias = 0.0;
std::vector<double> inputs = {3.0};
double target = 0.0;
std::vector<double> weights = {0.0};
ผลลัพธ์ที่คาดหวัง:
std::vector<double> expected = {0.75, 0.25};
อินพุต:
double bias = 0.0;
double[] inputs = new double[] {3.0};
double target = 0.0;
double[] weights = new double[] {0.0};
ผลลัพธ์ที่คาดหวัง:
double[] expected = new double[] {0.75, 0.25};
คำอธิบาย
z = 0 และ y = 0.5 delta = 2 × (0.5 - 0) × 0.5 × 0.5 = 0.25 ดังนั้นเกรเดียนต์คือ [0.25×3, 0.25] = [0.75, 0.25] เกรเดียนต์เป็นบวกหมายความว่าควรลดน้ำหนักลง
แหล่งอ้างอิง
โจทย์นี้ปรับให้เหมาะกับ CodeUtility กรุณาทำตามคำชี้แจงและข้อจำกัดด้านบน