จาก ep ก่อนที่เราเรียนรู้เรื่อง Activation Function คืออะไร ใน Artificial Neural Network และพูดถึง Sigmoid Function แต่ในปัจจุบัน Activation Function ที่ได้รับความนิยมมีอีกหลายตัว หนึ่งในนั้นคือ Tanh

แล้ว Tanh ต่างกับ Sigmoid อย่างไร ทำไมถึงต้องมี Tanh ขึ้นมาอีก

Tanh Function

Tanh Function หรือชื่อเต็มคือ Hyperbolic Tangent Activation Function เป็นฟังก์ชันที่แก้ข้อเสียหลายอย่างของ Sigmoid แต่รูปร่างเป็นตัว S เหมือนกัน กราฟสีเขียวด้านล่าง

sinh, cosh, tanh function. Credit https://commons.wikimedia.org/wiki/Trigonometric_function_plots
sinh, cosh, tanh function. Credit https://commons.wikimedia.org/wiki/Trigonometric_function_plots

สมการของ Tanh Function

\(f(x)=\tanh(x)=\frac{(e^{x} – e^{-x})}{(e^{x} + e^{-x})}\)

หรือเราจะคิดง่าย ๆ ว่า Tanh = ( Sigmoid x 2 ) - 1 คือ เอา Sigmoid มาคูณ 2 ให้ยืดจาก 0-1 เป็น 0-2 แล้ว ลบ 1 เพื่อเลื่อนลง จาก 0-2 เป็น -1-1

Derivative ของ Tanh Function

Derivative ของ Tanh Function ก็สามารถคำนวนได้ง่าย ๆ จากค่าของ Tanh Function เอง ดังนี้

\(f'(x)=1-f(x)^2\)

แต่ตอนนี้เรายังไม่ต้องสนใจ สมการสูตรคณิตศาสตร์ เรามาดูกันว่า Tanh Function จริง ๆ แล้ว Input/Output ของมันมีหน้าตาเป็นอย่างไร เปรียบเทียบกับ Sigmoid Function

เรามาเริ่มกันเลยดีกว่า

Open In Colab

ข้อดีของ Tanh Function

  1. Output มีความ Balance มี Mean เท่ากับ 0 ทำให้ Optimize ง่ายขึ้น
  2. Output อยู่ในช่วง -1, 1 นิยมใช้งานเกี่ยวกับ Classification ระหว่าง 2 อย่าง และเป็นตัว Normalize ให้เป็น 1 Unit
  3. เข้าใจง่าย
  4. หา Derivative ไม่ยาก
  5. ถ้า Input ใกล้ 0 แล้ว Derivative จะมี Slope ชันกว่า Sigmoid ทำให้ Gradient มากกว่า เทรนได้เร็วกว่า

ข้อเสียของ Tanh Function

  1. ไม่สามารถใช้เป็น Probability ได้
  2. ถ้า Input น้อยกว่า -3 หรือมากกว่า 3 ความชัน Slope จะเข้าใกล้ 0 จน Gradient หายไปหมด ทำให้โมเดล Train ไม่ไปไหน เรียกว่า Vanishing Gradient จะอธิบายต่อไป
  3. ใช้แล้วโมเดลมักจะ Converge ช้า

ข้อเสียเหล่านี้ทำให้ Tanh Function ไม่ได้ถูกใช้เป็น Activation Function หลักของโมเดล แต่มักจะถูกนำมาใช้กับงานเฉพาะบางอย่าง เช่น ใน LSTM, GRU จะอธิบายต่อไป

Train Neural Network

Deep Neural Network with 2 Hidden Layers using Tanh

Train Neural Network using Tanh. Credit https://playground.tensorflow.org
Train Neural Network using Tanh. Credit https://playground.tensorflow.org

สังเกตว่าเพียง 100+ Epoch เท่านั้น ก็ Converge โดย Training Loss และ Test Loss ค่อย ๆ ลดเป็นช่วง ๆ เปรียบเทียบกับ Sigmoid ที่ต้องเทรนนานถึง 1000+ Epoch

มีผู้ออกแบบ Hard Tanh เพื่อมาแก้ไขข้อเสียของ Tanh แต่ก็ยังไม่ค่อยได้รับความนิยมเท่าที่ควร ReLU จะได้รับความนิยมมากกว่า

Credit

แชร์ให้เพื่อน:

Surapong Kanoktipsatharporn on FacebookSurapong Kanoktipsatharporn on LinkedinSurapong Kanoktipsatharporn on Rss
Surapong Kanoktipsatharporn
Solutions Architect at Bua Labs
The ultimate test of your knowledge is your capacity to convey it to another.

Published by Surapong Kanoktipsatharporn

The ultimate test of your knowledge is your capacity to convey it to another.