โครงข่ายประสาทเทียม (Neural Networks) เป็นหัวใจสำคัญของ Deep Learning มีการประยุกต์ใช้จริงในหลายด้าน เช่น การจำแนกภาพ การรู้จำเสียง การตรวจจับวัตถุ ฯลฯ
องค์ประกอบหลักของ Neural Network
- Input Layer (x): ชั้นรับข้อมูลเข้า
- Hidden Layers: ชั้นกลาง จำนวนไม่จำกัด
- Output Layer (ŷ): ชั้นให้ผลลัพธ์
- Weights (W) และ Biases (b): น้ำหนักและไบแอสระหว่างชั้นต่างๆ
- Activation Function (σ): ฟังก์ชันกระตุ้นสำหรับแต่ละ Hidden Layer
ในรูปภาพแสดงโครงข่าย 2 ชั้น (ไม่นับ Input Layer) วงกลมแทนโหนดประสาท (Neurons) เส้นเชื่อมแทน Synapses ซึ่งคูณ Input กับ Weight น้ำหนัก (Weight) แสดง "ความแข็งแกร่ง" ของการเชื่อมต่อระหว่างโหนด และเป็นตัวกำหนดผลลัพธ์ของโครงข่าย
ขั้นตอนการทำงานของ Feed Forward Neural Network
- รับ Input เป็น Matrix (อาร์เรย์ 2 มิติ)
- คูณ Input ด้วยชุด Weights
- นำไปผ่าน Activation Function
- ได้ Output
- คำนวณ Error (ความแตกต่างระหว่างค่าจริงและค่าทำนาย)
- ปรับ Weights ตาม Error
- ทำซ้ำ 1,000+ รอบ (Training) ยิ่งมากข้อมูล ยิ่งแม่นยำ
ข้อมูลตัวอย่าง: ชั่วโมงเรียน vs ชั่วโมงนอน -> คะแนนสอบ
2, 9 -> 92 1, 5 -> 86 3, 6 -> 89 4, 8 -> ?
โค้ดตัวอย่าง
from numpy import exp, array, random, dot, tanh
class my_network():
def __init__(self):
random.seed(1)
# 3x1 Weight matrix
self.weight_matrix = 2 * random.random((3, 1)) - 1
def my_tanh(self, x):
return tanh(x)
def my_tanh_derivative(self, x):
return 1.0 - tanh(x) ** 2
# Forward Propagation
def my_forward_propagation(self, inputs):
return self.my_tanh(dot(inputs, self.weight_matrix))
# Training
def train(self, train_inputs, train_outputs, num_train_iterations):
for iteration in range(num_train_iterations):
output = self.my_forward_propagation(train_inputs)
error = train_outputs - output
adjustment = dot(train_inputs.T, error * self.my_tanh_derivative(output))
self.weight_matrix += adjustment
# Driver Code
if __name__ == "__main__":
my_neural = my_network()
print('Random weights when training has started')
print(my_neural.weight_matrix)
train_inputs = array([[0, 0, 1], [1, 1, 1], [1, 0, 1], [0, 1, 1]])
train_outputs = array([[0, 1, 1, 0]]).T
my_neural.train(train_inputs, train_outputs, 10000)
print('Displaying new weights after training')
print(my_neural.weight_matrix)
# ทดสอบกับข้อมูลใหม่
print("Testing network on new examples ->")
print(my_neural.my_forward_propagation(array([1, 0, 0])))
ผลลัพธ์
Random weights when training has started [[-0.16595599] [ 0.44064899] [-0.99977125]] Displaying new weights after training [[5.39428067] [0.19482422] [0.34317086]] Testing network on new examples -> [0.99995873]