<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Tiwarin Suthasom on Medium]]></title>
        <description><![CDATA[Stories by Tiwarin Suthasom on Medium]]></description>
        <link>https://medium.com/@suthasom-t?source=rss-e010574c8d5e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*zTCgm-Qw0waMlIAF.jpg</url>
            <title>Stories by Tiwarin Suthasom on Medium</title>
            <link>https://medium.com/@suthasom-t?source=rss-e010574c8d5e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 19:38:21 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@suthasom-t/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[การเลือกใช้ Loss Function ในการพัฒนา Deep Learning Model]]></title>
            <link>https://suthasom-t.medium.com/%E0%B8%81%E0%B8%B2%E0%B8%A3%E0%B9%80%E0%B8%A5%E0%B8%B7%E0%B8%AD%E0%B8%81%E0%B9%83%E0%B8%8A%E0%B9%89-loss-function-%E0%B9%83%E0%B8%99%E0%B8%81%E0%B8%B2%E0%B8%A3%E0%B8%9E%E0%B8%B1%E0%B8%92%E0%B8%99%E0%B8%B2-deep-learning-model-4963f0a2e6ac?source=rss-e010574c8d5e------2</link>
            <guid isPermaLink="false">https://medium.com/p/4963f0a2e6ac</guid>
            <category><![CDATA[loss-function]]></category>
            <dc:creator><![CDATA[Tiwarin Suthasom]]></dc:creator>
            <pubDate>Wed, 04 Nov 2020 14:32:19 GMT</pubDate>
            <atom:updated>2020-11-04T14:39:33.411Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*CdfsaeQsCSxKW4Qx" /><figcaption>Photo by <a href="https://unsplash.com/@lazycreekimages?utm_source=medium&amp;utm_medium=referral">Michael Dziedzic</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4Glsq9jRIRlbDDMyQouwVw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0yRVs4-dJCIxdNGPZX5UgA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Igx-ShpGKNzCPOE-m-vnlA.png" /></figure><h3><strong>REFERENCE</strong></h3><ul><li><a href="https://blog.pjjop.org/loss-functions-for-training-deep-learning-model-part1/">การเลือกใช้ Loss Function ในการพัฒนา Deep Learning Model (ตอนที่ 1)</a></li><li><a href="https://blog.pjjop.org/loss-functions-for-training-deep-learning-model-part2/">การเลือกใช้ Loss Function ในการพัฒนา Deep Learning Model (ตอนที่ 2)</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4963f0a2e6ac" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Visualizing Kernels and Feature Maps in Deep Learning Model (CNN)]]></title>
            <link>https://suthasom-t.medium.com/visualizing-kernels-and-feature-maps-in-deep-learning-model-cnn-f0e8200680a0?source=rss-e010574c8d5e------2</link>
            <guid isPermaLink="false">https://medium.com/p/f0e8200680a0</guid>
            <category><![CDATA[cnn]]></category>
            <dc:creator><![CDATA[Tiwarin Suthasom]]></dc:creator>
            <pubDate>Tue, 20 Oct 2020 12:13:02 GMT</pubDate>
            <atom:updated>2020-11-04T15:33:55.328Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*c23BAb0h91ajU0S_" /><figcaption>Photo by <a href="https://unsplash.com/@tuelangdu?utm_source=medium&amp;utm_medium=referral">Tuệ Nguyễn</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><strong>CNN (Convolutional Neural Network)</strong> เป็นโครงสร้างภายใน Deep Learning Model ที่ใช้แนวคิดของ Convolution ในการทำงานกับข้อมูล 2 มิติ เช่น Image Data ซึ่งแต่ละ Pixel ของ Image จะมีความสัมพันธ์กันในเชิงพื้นที่ (Spatial Relationship)</p><p>ด้วยลักษณะโครงสร้างของ CNN ที่ถูกออกแบบมาเพื่อทำงานกับ Image Data ในตอนเริ่มต้น เราจึงสามารถแสดงข้อมูลที่เป็นองค์ประกอบของการตัดสินใจหรือการทำนายของ Model ด้วยภาพได้ดีกว่า Neural Network ชนิดอื่นๆ ที่จะไม่สามารถแสดงให้เห็นและอธิบายเหตุผลได้ว่าทำไมมันจึงมีการตัดสินใจหรือคาดคะเนผลลัพธ์ออกมาแบบนั้น</p><p>CNN ประกอบด้วย <strong>Kernel</strong> และผลลัพธ์จากการกระทำทางคณิตศาสตร์ของ Kernel กับ Input Image ที่เรียกว่า Activation Map หรือ <strong>Feature Map</strong> โดยทั้ง Kernel และ Feature Map นั้นสามารถแสดงผลได้ด้วยภาพ</p><p>ในบทความนี้ผู้อ่านจะได้ทำความเข้าใจแนวคิดของ CNN เพื่อดึง Kernel และ Feature Map ของออกมาแสดงผล</p><h3>2D Convolutions Concept</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/535/1*FHjn4GWkS1JNkBqX2wVEmg.gif" /><figcaption>รูปภาพจาก<a href="https://miro.medium.com/max/669/1*Zx-ZMLKab7VOCQTxdZ1OAw.gif"> https://miro.medium.com/max/669/1*Zx-ZMLKab7VOCQTxdZ1OAw.gif</a></figcaption></figure><p>2D Convolution เป็นการนำ <strong>Matrix ขนาดเล็ก </strong>ของ Weight หรือที่เรียกว่า Kernel มา Slide ไปบน 2D Input Image (สีฟ้าด้านบนซ้ายมือ) โดยขณะที่มีการทาบ Kernel บน Input Image มันจะ<strong>คูณ</strong>ค่าแต่ละ Pixel ของ Input Image กับ Kernel แล้วนำผลลัพธ์ทั้งหมดมา<strong>บวก</strong>กันเป็น 1 จุด Pixel ของ Feature Map (สีเขียวขวามือ)</p><p>2D Convolution ที่มีการสร้าง Feature Map ขึ้นมาด้วยการนำ Kernel Slide ไปบน Input Image จะใช้ Parameter น้อยกว่า Fully Connected Layer</p><p>โดยจากตัวอย่าง ในการนำภาพขนาด 5x5 Pixel เข้า Model, 2D Convolution Layer จะใช้จำนวน Parameter เท่ากับขนาดของ Kernel คือ 3x3 = 9 Parameter ขณะที่ถ้าเป็น Fully Connected Layer จะใช้จำนวน Parameter เท่ากับขนาดของ Input Image x 9 = 5x5x9 = 225 Parameter!</p><h3>Padding</h3><p>ตามภาพด้านบน ขณะที่มีการ Slide Kernel เราจะเห็นว่า Pixel ตรงขอบภาพสีฟ้าจะไม่มีทางอยู่ตรงกลาง Kernel ตอนที่มันทาบลงไป เพราะเราไม่สามารถขยาย Kernel ให้เลยออกไปนอกขอบของภาพ จึงทำให้ Feature Map ที่ได้มีขนาดเล็กกว่า Input Image</p><p>ดังนั้น เพื่อจะทำให้ Feature Map มีขนาดเท่ากับ Input Image และ Pixel ที่ขอบภาพอยู่ตรงกลาง Kernel ตอนที่มันทาบลงไป เราจะต้องมีการทำ Padding โดยการเสริมกรอบด้วยการเติม 0 (Zero Padding) รอบๆ ภาพเดิม</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/395/0*lHfANOrO9x6rEXgc.gif" /><figcaption>รูปภาพจาก <a href="https://miro.medium.com/max/494/1*1okwhewf5KCtIPaFib4XaA.gif">https://miro.medium.com/max/494/1*1okwhewf5KCtIPaFib4XaA.gif</a></figcaption></figure><h3>Striding</h3><p>การ Striding เป็นกระบวนการในการทำ Convolution โดยการเลื่อนแผ่น Kernel ไปบน Input Image ซึ่งโดย Default ของ Convolution แล้ว Stride จะมีค่าเท่ากับ 1 คือจะมีการเลื่อน Kernel ไปบน Input Image ครั้งละ 1 Pixel</p><p>เราสามารถลดขนาดของภาพที่แต่ละ Pixel มีความสัมพันธ์กันในเชิงพื้นที่ได้โดยการเพิ่มค่า Stride ซึ่งเมื่อมีการกำหนดค่า Stride มากขึ้น จะทำให้การเลื่อมกันของ Kernel ตอนที่มีการทาบกับ Input Image และขนาดของ Feature Map ลดลง</p><p>เมื่อกำหนด Stride เท่ากับ 2 แล้ว Kernel ขนาด 3x3 จะถูก Slide ข้าม Pixel ของ Input Image ขนาด 5x5 ทีละ 2 Pixel ทำให้ได้ Feature Map ขนาด 2x2 ดังภาพด้านล่าง</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/294/0*EtBzL6oY2kctPAXX.gif" /><figcaption>รูปภาพจาก <a href="https://miro.medium.com/max/368/1*BMngs93_rm2_BpJFH2mS0Q.gif">https://miro.medium.com/max/368/1*BMngs93_rm2_BpJFH2mS0Q.gif</a></figcaption></figure><h3>Pooling</h3><p>นอกจากการลดขนาดของภาพด้วยการเพิ่มค่า Stride โดยการ Slide Kernel ข้าม Pixel ของ Input Image ตามระยะทางที่กำหนดแล้ว ยังมีอีกวิธีหนึ่งในการลดขนาดของภาพ คือการทำ <strong>Max Pooling</strong> หรือ <strong>Average Pooling </strong>โดย Pooling จะเป็นกระบวนการทำงานภายนอก CNN Layer</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Bd83aygS6o1j1g-K.png" /><figcaption>รูปภาพจาก <a href="https://miro.medium.com/max/875/1*ReZNSf_Yr7Q1nqegGirsMQ@2x.png">https://miro.medium.com/max/875/1*ReZNSf_Yr7Q1nqegGirsMQ@2x.png</a></figcaption></figure><p>Max Pooling หรือ Average Pooling จะเป็นการเลือกตัวแทนของภาพด้วยการหาค่ามากที่สุด หรือค่าเฉลี่ยจาก Pixel ใน Window ตามขนาดที่กำหนด เช่น ขนาด 2x2 ซึ่งจะทำให้มีการลดขนาดของภาพลงได้ครึ่งหนึ่งดังตัวอย่างด้านบน</p><h3>Multi-channel</h3><p>อย่างไรก็ตาม ในตัวอย่างที่ผ่านมาจะเป็นการจัดการกับ Input Image แบบ 1 Channel เช่น ภาพแบบ Grayscale แต่บ่อยครั้งที่ Input Image ของเราจะเป็นภาพสี แบบ 3 Channel (โดยทั่วไปจำนวน Channel ของ Input Image จะเพิ่มขึ้นเมื่อมันถูกส่งเข้าสู่ชั้น CNN Layer ที่ลึกขึ้น)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*HAwfDBVr-5Zw4y4b.jpeg" /><figcaption>รูปภาพจาก <a href="https://miro.medium.com/max/1250/1*k8P28Ayl-5hOqIMSv-qosw.jpeg">https://miro.medium.com/max/1250/1*k8P28Ayl-5hOqIMSv-qosw.jpeg</a></figcaption></figure><p>เพื่อจะจัดการกับ Input Image แบบ 3 Channel อย่างเช่นภาพสีในระบบ RGB เราจะต้องใช้ Kernel จำนวน 3 ตัว ในการ Slide ไปบน Input Image แต่ละ Channel ซึ่งเราเรียก Kernel ทั้ง 3 ตัวว่า <strong>Filter</strong> (ในที่นี้ 1 Filter ประกอบด้วย Kernel 3 Kernel)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*BebdmjHJuRpeI6xx.gif" /><figcaption>รูปภาพจาก <a href="https://miro.medium.com/max/1250/1*8dx6nxpUh2JqvYWPadTwMQ.gif">https://miro.medium.com/max/1250/1*8dx6nxpUh2JqvYWPadTwMQ.gif</a></figcaption></figure><p>Feature Map แต่ละ Version ขนาด 3x3 ที่เกิดจากการ Slide Kernel ไปบน Input Channel ขนาด 5x5 จะถูกนำมารวมกันเป็น <strong>Output Channel</strong> 1 Channel เพื่อจะส่งต่อไปยัง Neural Network Layer ถัดไป</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*AsXzadjvhrzV1J-m.gif" /><figcaption>รูปภาพจาก <a href="https://miro.medium.com/max/1250/1*CYB2dyR3EhFs1xNLK8ewiA.gif">https://miro.medium.com/max/1250/1*CYB2dyR3EhFs1xNLK8ewiA.gif</a></figcaption></figure><p>ซึ่ง Output Channel จะถูกนำมาบวกกับ Bias ในขั้นตอนสุดท้ายของกระบวนการทำ Convolution</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/294/0*jQxbdGFUc8lyfpFX.gif" /><figcaption>รูปภาพจาก <a href="https://miro.medium.com/max/368/1*RYYucIh3U-YFxrIkyQKzRw.gif">https://miro.medium.com/max/368/1*RYYucIh3U-YFxrIkyQKzRw.gif</a></figcaption></figure><p><em>เพื่อจะสร้าง Output Channel 1 Channel ดังภาพด้านบน เราจะต้องใช้ Filter 1 Filter ซึ่งแต่ละ Filter ก็จะประกอบด้วยจำนวน Kernel 3 Kernel ดังนั้นในกรณีที่ต้องการสร้าง Output Channel หลาย Channel เราจะต้องมีจำนวน Filter หลาย Filter</em></p><h3>Visualizing CNN</h3><blockquote>Model with 2D CNN Layer</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/914/1*XrvnQ3mBzAjLiEUdbqIZXQ.png" /></figure><ul><li>Model แบบ 2D Convolution โดยรับ Input Image ขนาด 1,440x1,080 Pixel แบบ <strong>3 Channel</strong> โดยมี <strong>Filter ขนาด 3x3</strong> จำนวน <strong>3 Filter</strong> เพื่อนำไป Slide บน Input Image ของแต่ละ Channel</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/914/1*xzkgUqc5LirHz0D_EXMEwg.png" /></figure><ul><li>Model แบบ 2D Convolution โดยรับ Input Image ขนาด 1,440x1,080 Pixel แบบ 3 Channel โดยมี <strong>Filter ขนาด 10x10</strong> จำนวน 3 Filter เพื่อนำไป Slide บน Input Image แต่ละ Channel</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/914/1*hmHt6oDV-l-EhqqmXd5aog.png" /></figure><ul><li>Model แบบ 2D Convolution โดยรับ Input Image ขนาด 1,440x1,080 Pixel แบบ 3 Channel โดยมี Filter ขนาด 3x3 <strong>จำนวน 1 Filter</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/914/1*5jYjcKoBrRuiOOvFt8WU2g.png" /></figure><ul><li>Model แบบ 2D Convolution โดยรับ Input Image ขนาด 1,440x1,080 Pixel แบบ 3 Channel โดยมี <strong>Filter ขนาด 20x20</strong> จำนวน 1 Filter</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/914/1*HzLFyCJOi7eT_T3MNbCNXQ.png" /></figure><ul><li>Model แบบ 2D Convolution โดยรับ Input Image ขนาด 1,440x1,080 Pixel แบบ 3 Channel โดยมี Filter ขนาด 20x20 จำนวน 1 Filter และ<strong>เพิ่ม ReLu Activation Function</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/914/1*uXUGquWxEO2gde294opoog.png" /></figure><ul><li>Model แบบ 2D Convolution โดยรับ Input Image ขนาด 1,440x1,080 Pixel แบบ 3 Channel โดยมี <strong>Filter ขนาด 3x3</strong> จำนวน 1 Filter และ<strong>เพิ่ม Max Pooling ขนาด 5x5</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/996/1*YMv7px9L9lsZMMttLU3icQ.png" /></figure><ul><li>Model แบบ 2D Convolution โดยรับ Input Image ขนาด 1,440x1,080 Pixel แบบ 3 Channel โดยมี Filter ขนาด 3x3 จำนวน 1 Filter <strong>เพิ่ม ReLu Activation Function และ</strong> <strong>Max Pooling ขนาด 5x5</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/836/1*tjDJyUw7JBhHUjBVsTr7lw.png" /></figure><ul><li>Model แบบ <strong>2D Convolution, ReLu Activation Function และ Max Pooling อย่างละ 2 Layer</strong></li></ul><p>ก็จบกันไปแล้วสำหรับบทความนี้ หากผิดพลาดประการใดก็ขออภัยมา ณ ที่นี้ด้วยค่ะ</p><h3>Reference</h3><p><a href="https://blog.pjjop.org/visualizing-filters-and-feature-maps-in-deep-learning-cnn/">Visualizing Kernels and Feature Maps in Deep Learning Model (CNN)</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f0e8200680a0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[การทำ Regularization ด้วยเทคนิค Augmentation, Batch Normalization และ Dropout by Google colab]]></title>
            <link>https://suthasom-t.medium.com/%E0%B8%81%E0%B8%B2%E0%B8%A3%E0%B8%97%E0%B8%B3-regularization-%E0%B8%94%E0%B9%89%E0%B8%A7%E0%B8%A2%E0%B9%80%E0%B8%97%E0%B8%84%E0%B8%99%E0%B8%B4%E0%B8%84-augmentation-batch-normalization-%E0%B9%81%E0%B8%A5%E0%B8%B0-dropout-by-google-colab-f7008c80a3e?source=rss-e010574c8d5e------2</link>
            <guid isPermaLink="false">https://medium.com/p/f7008c80a3e</guid>
            <category><![CDATA[regularization]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Tiwarin Suthasom]]></dc:creator>
            <pubDate>Wed, 07 Oct 2020 14:15:33 GMT</pubDate>
            <atom:updated>2020-10-07T14:15:33.532Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*CQn7DY6ml8ojsUhV" /><figcaption>Photo by <a href="https://unsplash.com/@vincefleming?utm_source=medium&amp;utm_medium=referral">Vince Fleming</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>ถ้าพูดถึงเรื่องของการเพิ่มประสิทธิภาพของ Machine Learning Model สิ่งที่ต้องพิจารณา 2 เรื่องหลักๆคือ <br>1.ในเรื่องของการพยายามลด Generalization Error ด้วย <strong>Regularization <br></strong>2. การลด Cost Value ด้วย <strong>Optimization</strong></p><p>ซึ่งในวันนี้เราจะมาพูดถึงเรื่อง <strong>Regularization </strong>ถ้าหากพูดถึงเรื่อง<strong> </strong>Generalization Error คือ <strong>Error </strong>ที่เกิดจากการที่เราเอา model ที่ Train แล้วด้วย Training Dataset ไปใช้ในการ predict และการวัดประสิทธิภาพโดยใช้ data ที่ Model <strong>ไม่เคยเรียนรู้ไม่เคยเห็นมาก่อน</strong>แล้วสามารถที่จะทำงานได้ดี <strong>Loss</strong> น้อย <strong>Accuracy </strong>สูง</p><p>ทีนี้ถ้าพูดถึงการทำการลด Generalization Error จะต้องมาดูในสิ่งที่เรียกว่า learning curve เพราะว่า learning curve เป็นตัวที่ใช้ในการบอกว่า model มีประสิทธิภาพในการเรียนรู้ดีหรือไม่ นั่นคือมันจะบอกปัญหาของ model <br>2 อย่างหลักๆ คือ <br><strong>1. Underfitting </strong>คือการที่ model ไม่สามารถที่จะเรียนรู้ได้เลย<br><strong>2. Overfitting </strong>คือ model เก่งในการเรียนรู้ data ที่เอามา Train แต่ว่าไม่ฉลาดในการ predict กับ data ที่มันไม่เคยเห็นมาก่อน<br>ซึ่งทั้ง 2 ปัญหามันจะทำให้เกิด Generalization Error สูง</p><p>เราสามารถจัดการกับปัญหา <strong>Underfitting</strong> ได้โดยการเพิ่มจำนวน Layer และจำนวน Node ใน Layer ให้มากขึ้น แต่ก็อาจทำให้เกิดปัญหา Overfitting ตามมา</p><p>ฉะนั้นการแก้ปัญหา <strong>Overfitting</strong> มันจะมีเทคนิคหลากหลายที่ใช้ในการแก้ไขอย่างเช่น การทำ Augmentation, Batch Normalization, Dropout, L1/L2 Regularization, Weight Decay, Weight Constraints และ Early Stopping ฯลฯ</p><p>ในบทความนี้เราจะทดลองแก้ปัญหา <strong>Overfitting</strong> ของ Neural Network แบบ Classification Model ที่มีการ Train ด้วย <strong>Fashion-MNIST Dataset </strong>โดยยกตัวอย่างเทคนิคที่เป็นที่นิยมในปัจจุบัน 3 เทคนิค ได้แก่<strong> </strong>การทำ <strong>Augmentation</strong>, <strong>Batch Normalization</strong> และ <strong>Dropout </strong>ซึ่งในที่สุดแล้วจะทำให้สามารถเพิ่มประสิทธิภาพของ Model ได้มากน้อยเท่าไหร่ <strong>ตามมาดูกันเลย!</strong></p><h3><strong>Fashion-MNIST Dataset</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/888/1*vIpkolZZ3jACO529n4QaJg.png" /><figcaption>ภาพจาก <a href="https://cdn-images-1.medium.com/freeze/max/1000/1*-kpgaee9X9Gm-SrQKdk_og.png?q=20">https://cdn-images-1.medium.com/freeze/max/1000/1*-kpgaee9X9Gm-SrQKdk_og.png?q=20</a></figcaption></figure><p>Fashion-MNIST เป็น Dataset ที่เป็นภาพเสื้อผ้า กระเป๋า และรองเท้า ทั้งหมด 10 class หรือ 10 ประเภท ตั้งแต่ 0–9 ขนาด 28x28 Pixel แบบ Grayscale ซึ่งแบ่งเป็นข้อมูล Train 60,000 ภาพ และข้อมูล Test อีก 10,000 ภาพ ดังนี้</p><p>0: T-shirt/top<br>1: Trouser<br>2: Pullover<br>3: Dress<br>4: Coat<br>5: Sandal<br>6: Shirt<br>7: Sneaker<br>8: Bag<br>9: Ankle boot</p><p>ซึ่งเราจะต้องมีการ Load Dataset แล้วขยายมิติของ Dataset ทำ Scaling ข้อมูล ระหว่าง 0–1 เข้ารหัสผลเฉลยแบบ One-hot Encoding และ Split Dataset สำหรับการ Train และ Validation ดังต่อไปนี้</p><blockquote>หากเครื่องของใครมี GPUขอแนะนำให้ใช้ GPUถ้าหากไม่ใช้ GPUมันจะใช้เวลาค่อนข้างเยอะพอสมควรซึ่งเจ้าของบทความใช้ google colab ในการเขียนโค้ดจึงต้องทำการเปลี่ยน type การ run ก่อน</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/978/1*FqSD7lcJW3dwc7wyd0KoMQ.png" /><figcaption>กด Runtime เลือก Change runtime type</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/484/1*fK1iqYFpUc3Idd1SMR1aPg.png" /><figcaption>ช่อง Hardware accelerator ให้เลือก GPU จากนั้นกด Save</figcaption></figure><h3>มาเริ่มกันเลย!!</h3><blockquote>Config การใช้งาน GPU ด้วยคำสั่งต่อไปนี้</blockquote><pre>!nvidia-smi -L</pre><pre>import tensorflow as tf<br>tf.__version__</pre><pre>config = tf.compat.v1.ConfigProto()<br>config.gpu_options.allow_growth = True<br>sess = tf.compat.v1.Session(config=config)<br><br>print( &#39;Tensorflow Version:&#39;, tf.__version__)<br>print(&quot;GPU Available::&quot;, tf.config.list_physical_devices(&#39;GPU&#39;))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/893/1*DXLnEwOiXzOnjcXXV5FMkA.png" /></figure><blockquote>Import Library และกำหนดค่า Parameter ที่จำเป็น</blockquote><pre>from tensorflow.keras.models import Sequential<br>from tensorflow.keras.layers import Dense, Activation, Conv2D, MaxPool2D, Flatten, Dropout, BatchNormalization<br>from tensorflow.keras.optimizers import RMSprop,Adam<br><br>from tensorflow.keras.utils import to_categorical<br>from tensorflow.keras.preprocessing.image import ImageDataGenerator<br>from sklearn.model_selection import train_test_split<br><br>from matplotlib import pyplot<br>from tensorflow.keras.datasets import fashion_mnist<br><br>import plotly.graph_objs as go<br>from plotly import tools<br>import plotly<br><br>import cv2</pre><blockquote>กำหนดค่าต่างๆ</blockquote><pre>IMG_ROWS = 28<br>IMG_COLS = 28<br>NUM_CLASSES = 10<br>TEST_SIZE = 0.2<br>RANDOM_STATE = 99<br><br>NO_EPOCHS = 10<br>BATCH_SIZE = 128</pre><blockquote>Load Dataset</blockquote><pre>(train_data, y), (test_data, y_test) = fashion_mnist.load_data()<br><br>print(&quot;Fashion MNIST train -  rows:&quot;,train_data.shape[0],&quot; columns:&quot;, train_data.shape[1], &quot; rows:&quot;, train_data.shape[2])<br>print(&quot;Fashion MNIST test -  rows:&quot;,test_data.shape[0],&quot; columns:&quot;, test_data.shape[1], &quot; rows:&quot;, train_data.shape[2])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gBRRvqA98l4mjnQrMsdq4A.png" /></figure><pre>for i in range(9):<br>    pyplot.subplot(330 + 1 + i)    <br>    pyplot.imshow(train_data[i], cmap=pyplot.get_cmap(&#39;gray&#39;))<br><br>pyplot.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/901/1*C0F1JRdNan_eyO7IjDA0ng.png" /></figure><blockquote>ขยายมิติของ Dataset</blockquote><pre>print(train_data.shape, test_data.shape)<br><br>train_data = train_data.reshape((train_data.shape[0], 28, 28, 1))<br>test_data = test_data.reshape((test_data.shape[0], 28, 28, 1))<br><br>print(train_data.shape, test_data.shape)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/876/1*Ih9SxZawF7aeIm5ase9Ohg.png" /></figure><blockquote>ทำ Scaling</blockquote><pre>train_data = train_data / 255.0<br>test_data = test_data / 255.0</pre><blockquote>เข้ารหัสผลเฉลยแบบ One-hot Encoding</blockquote><pre>print(y.shape, y_test.shape)<br>print(y[:10])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/859/1*Ejn26Sx-cXk7ZtO9h9lPeQ.png" /></figure><pre>y = to_categorical(y)<br>y_test = to_categorical(y_test)<br><br>print(y.shape, y_test.shape)<br>y[:10]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4ghGTfT3cJ2bMaObeZB9Xg.png" /></figure><blockquote>แบ่งข้อมูลสำหรับ Train และ Validate โดยการสุ่มในสัดส่วน 80:20</blockquote><pre>X_train, X_val, y_train, y_val = train_test_split(train_data, y, test_size=TEST_SIZE, random_state=RANDOM_STATE)<br><br>X_train.shape, X_val.shape, y_train.shape, y_val.shape</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KUJPFSDSxEeS5rD9eVXxLg.png" /></figure><h4>นิยาม Model</h4><pre>model = Sequential()<br><br>#1. CNN LAYER<br>model.add(Conv2D(filters = 32, kernel_size = (3,3), padding = &#39;Same&#39;, input_shape=(28, 28, 1)))<br>model.add(Activation(&quot;relu&quot;))<br><br>#2. CNN LAYER<br>model.add(Conv2D(filters = 32, kernel_size = (3,3), padding = &#39;Same&#39;))<br>model.add(Activation(&quot;relu&quot;))<br><br>model.add(MaxPool2D(pool_size=(2, 2)))<br><br>#3. CNN LAYER<br>model.add(Conv2D(filters = 64, kernel_size = (3,3), padding = &#39;Same&#39;))<br>model.add(Activation(&quot;relu&quot;))<br><br>#4. CNN LAYER<br>model.add(Conv2D(filters = 64, kernel_size = (3,3), padding = &#39;Same&#39;))<br>model.add(Activation(&quot;relu&quot;))<br><br>model.add(MaxPool2D(pool_size=(2, 2)))<br><br>#FULLY CONNECTED LAYER<br>model.add(Flatten())<br>model.add(Dense(256))<br>model.add(Activation(&quot;relu&quot;))<br><br>#OUTPUT LAYER<br>model.add(Dense(10, activation=&#39;softmax&#39;))</pre><h4>Compile Model</h4><pre>optimizer = Adam()<br>model.compile(optimizer = optimizer, loss = &quot;categorical_crossentropy&quot;, metrics=[&quot;accuracy&quot;])<br><br>model.summary()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/957/1*MAaY4yWRlxn_8-a6JjAdnw.png" /></figure><h4>Train Model</h4><pre>train_model = model.fit(X_train, y_train,<br>                  batch_size=BATCH_SIZE,<br>                  epochs=NO_EPOCHS,<br>                  verbose=1,<br>                  validation_data=(X_val, y_val))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0f4gUlESARzjbZoWSBXTAQ.png" /></figure><h4>Evaluation</h4><pre>def create_trace(x,y,ylabel,color):<br>        trace = go.Scatter(<br>            x = x,y = y,<br>            name=ylabel,<br>            marker=dict(color=color),<br>            mode = &quot;markers+lines&quot;,<br>            text=x<br>        )<br>        return trace<br>    <br>def plot_accuracy_and_loss(train_model):<br>    hist = train_model.history<br>    acc = hist[&#39;accuracy&#39;]<br>    val_acc = hist[&#39;val_accuracy&#39;]<br>    loss = hist[&#39;loss&#39;]<br>    val_loss = hist[&#39;val_loss&#39;]<br>    epochs = list(range(1,len(acc)+1))<br>    <br>    trace_ta = create_trace(epochs,acc,&quot;Training accuracy&quot;, &quot;Green&quot;)<br>    trace_va = create_trace(epochs,val_acc,&quot;Validation accuracy&quot;, &quot;Red&quot;)<br>    trace_tl = create_trace(epochs,loss,&quot;Training loss&quot;, &quot;Blue&quot;)<br>    trace_vl = create_trace(epochs,val_loss,&quot;Validation loss&quot;, &quot;Magenta&quot;)<br>   <br>    fig = tools.make_subplots(rows=1,cols=2, subplot_titles=(&#39;Training and validation accuracy&#39;,<br>                                                             &#39;Training and validation loss&#39;))<br>    fig.append_trace(trace_ta,1,1)<br>    fig.append_trace(trace_va,1,1)<br>    fig.append_trace(trace_tl,1,2)<br>    fig.append_trace(trace_vl,1,2)<br>    fig[&#39;layout&#39;][&#39;xaxis&#39;].update(title = &#39;Epoch&#39;)<br>    fig[&#39;layout&#39;][&#39;xaxis2&#39;].update(title = &#39;Epoch&#39;)<br>    fig[&#39;layout&#39;][&#39;yaxis&#39;].update(title = &#39;Accuracy&#39;, range=[0,1])<br>    fig[&#39;layout&#39;][&#39;yaxis2&#39;].update(title = &#39;Loss&#39;, range=[0,1])<br><br>    plotly.offline.iplot(fig, filename=&#39;accuracy-loss&#39;)<br></pre><pre>plot_accuracy_and_loss(train_model)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6VvKihw9I4_ezKun6g0m7Q.png" /></figure><pre>score = model.evaluate(test_data, y_test,verbose=0)<br>print(&quot;Test Loss:&quot;,score[0])<br>print(&quot;Test Accuracy:&quot;,score[1])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/895/1*DAS8fOMigKAzEOXurvEKvg.png" /></figure><p><em>จากกราฟ Loss ด้านบน พบว่า Model มีปัญหา Overfitting ตั้งแต่รอบที่ 7 โดยเมื่อวัดประสิทธิภาพการ Predict ด้วย Test Dataset ได้ค่า Accuracy 92.37%</em></p><h3>Image Augmentation</h3><p>ปัญหา Overfitting ของ Model สามารถแก้ได้ด้วยการเพิ่มจำนวน Data ในการ Train แต่ด้วย Dataset ของเรามีจำกัด ดังนั้นในบางกรณีเราจึงต้องสังเคราะห์ Data ขึ้นมาเอง ในกรณีของ Data แบบ Image เราสามารถใช้เทคนิคอย่างเช่นการหมุนภาพ การเลื่อนภาพ และการกลับภาพ ฯลฯ ซึ่งนอกจากเป็นการขยายจำนวน Data แล้ว Image Augmentation ยังช่วย<strong>เพิ่มความหลากหลายของภาพ</strong>ที่จะนำไป Train อีกด้วย</p><p>การทำ Image Augmentation ในแบบต่างๆ ได้แก่</p><ol><li>Vertical Shift</li><li>Horizontal Shift</li><li>Shear</li><li>Zoom</li><li>Vertical Flip</li><li>Horizontal Flip</li><li>Rotate</li><li>Fill Mode<br>8.1 Constant Values<br>8.2 Nearest Neighbor<br>8.3 Reflect Values</li></ol><p>แต่ก่อนอื่นเราจะอ่านไฟล์ภาพมาทดลองทำ Image Augmentation ตามขั้นตอน ดังนี้</p><blockquote>อ่านไฟล์ภาพ</blockquote><pre>cat = cv2.imread(&#39;/content/drive/My Drive/Colab Notebooks/nonmeaw.jpg&#39;)</pre><pre>cat.shape</pre><p>ขอบคุณภาพจาก <a href="https://www.zastavki.com/eng/Animals/Cats/wallpaper-45506.htm">https://www.zastavki.com/eng/Animals/Cats/wallpaper-45506.htm</a></p><blockquote>แปลงระบบสีจาก BGR ซึ่งเป็นค่า Default ของ OpenCV Library เป็น RGB</blockquote><pre>cat = cv2.cvtColor(cat, cv2.COLOR_RGB2BGR)</pre><blockquote>Plot ภาพ</blockquote><pre>plt.figure(dpi=100)<br>plt.imshow(cat)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/994/1*NLOfadZucIcgoxtdg26r4w.png" /></figure><blockquote>ขยายมิติของภาพจาก 3 มิติเป็น 4 มิติ เพื่อเตรียมนำเข้า Function ทำ Image Augmentation</blockquote><pre>print(cat.shape)<br>cat = cat.reshape(1,cat.shape[0],cat.shape[1],cat.shape[2])<br>print(cat.shape)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/933/1*1bGEo2PIGfLl1M-I2d9YLw.png" /></figure><blockquote>ทำ <strong>Vertical Shift</strong> ด้วยการเลื่อนภาพขึ้นลงแบบสุ่มไม่เกิน 20%</blockquote><pre>datagen = ImageDataGenerator(height_shift_range=0.2)<br><br>aug_iter = datagen.flow(cat, batch_size=1)<br><br>fig, ax = pyplot.subplots(nrows=1, ncols=3, figsize=(15,15))<br><br>for i in range(3):<br>    image = next(aug_iter)[0].astype(&#39;uint8&#39;)<br>    ax[i].imshow(image)<br>    ax[i].axis(&#39;off&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0ZEK3c-_PWWYvHY8VGv90w.png" /></figure><blockquote>ทำ <strong>Horizontal Shift</strong> ด้วยการเลื่อนภาพซ้ายขวาแบบสุ่มไม่เกิน 20%</blockquote><pre>datagen = ImageDataGenerator(width_shift_range=0.2)<br><br>aug_iter = datagen.flow(cat, batch_size=1)<br><br>fig, ax = pyplot.subplots(nrows=1, ncols=3, figsize=(15,15))<br><br>for i in range(3):<br>    image = next(aug_iter)[0].astype(&#39;uint8&#39;)<br>    ax[i].imshow(image)<br>    ax[i].axis(&#39;off&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-pgCJCrs4WtIiJIdQgNVUQ.png" /></figure><blockquote>บิดภาพ (<strong>Shear</strong>) แบบสุ่มไม่เกิน 20 องศา</blockquote><pre>datagen = ImageDataGenerator(shear_range=20)<br><br>aug_iter = datagen.flow(cat, batch_size=1)<br><br>fig, ax = pyplot.subplots(nrows=1, ncols=3, figsize=(15,15))<br><br>for i in range(3):<br>    image = next(aug_iter)[0].astype(&#39;uint8&#39;)<br>    ax[i].imshow(image)<br>    ax[i].axis(&#39;off&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*euG7XE_wpecSKej7F4mBqw.png" /></figure><blockquote>ขยายภาพ (<strong>Zoom</strong>) แบบสุ่มไม่เกิน 30%</blockquote><pre>datagen = ImageDataGenerator(zoom_range=0.3)<br><br>aug_iter = datagen.flow(cat, batch_size=1)<br><br>fig, ax = pyplot.subplots(nrows=1, ncols=3, figsize=(15,15))<br><br>for i in range(3):<br>    image = next(aug_iter)[0].astype(&#39;uint8&#39;)<br>    ax[i].imshow(image)<br>    ax[i].axis(&#39;off&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Lp-6jDLq5VrbxDsw0YR0Bw.png" /></figure><blockquote>พลิกภาพแนวตั้ง (<strong>Vertical Flip</strong>) แบบสุ่ม</blockquote><pre>datagen = ImageDataGenerator(vertical_flip=True)<br><br>aug_iter = datagen.flow(cat, batch_size=1)<br><br>fig, ax = pyplot.subplots(nrows=1, ncols=3, figsize=(15,15))<br><br>for i in range(3):<br>    image = next(aug_iter)[0].astype(&#39;uint8&#39;)<br>    ax[i].imshow(image)<br>    ax[i].axis(&#39;off&#39;)<br>    <br>fig.savefig(&#39;cat.jpeg&#39;, dpi=300)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RPHuOJ1RigWj4D0E8JCz-A.png" /></figure><blockquote>พลิกภาพแนวนอน (<strong>Horizontal Flip</strong>) แบบสุ่ม</blockquote><pre>datagen = ImageDataGenerator(horizontal_flip=True)<br><br>aug_iter = datagen.flow(cat, batch_size=1)<br><br>fig, ax = pyplot.subplots(nrows=1, ncols=3, figsize=(15,15))<br><br>for i in range(3):<br>    image = next(aug_iter)[0].astype(&#39;uint8&#39;)<br>    ax[i].imshow(image)<br>    ax[i].axis(&#39;off&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*baOufgFWVzTEG_tyG26ubg.png" /></figure><blockquote>หมุนภาพ (<strong>Rotate</strong>) ไม่เกิน 30 องศา แบบสุ่ม</blockquote><pre>datagen = ImageDataGenerator(rotation_range=30)<br><br>aug_iter = datagen.flow(cat, batch_size=1)<br><br>fig, ax = pyplot.subplots(nrows=1, ncols=3, figsize=(15,15))<br><br>for i in range(3):<br>    image = next(aug_iter)[0].astype(&#39;uint8&#39;)<br>    ax[i].imshow(image)<br>    ax[i].axis(&#39;off&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZEwOOiVh_ulC-V1cEh28IA.png" /></figure><h3>Fill Mode</h3><blockquote>เติมสีดำ (<strong>Constant Values</strong>)</blockquote><pre>datagen = ImageDataGenerator(rotation_range=30, fill_mode = &#39;constant&#39;)<br><br>aug_iter = datagen.flow(cat, batch_size=1)<br><br>fig, ax = pyplot.subplots(nrows=1, ncols=3, figsize=(15,15))<br><br>for i in range(3):<br>    image = next(aug_iter)[0].astype(&#39;uint8&#39;)<br>    ax[i].imshow(image)<br>    ax[i].axis(&#39;off&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H7JQb94Hoiy0_2Tmtb-0kg.png" /></figure><blockquote>เติมสีข้างเคียง (<strong>Nearest Neighbor</strong>)</blockquote><pre>datagen = ImageDataGenerator(rotation_range=30, fill_mode = &#39;nearest&#39;)<br><br>aug_iter = datagen.flow(cat, batch_size=1)<br><br>fig, ax = pyplot.subplots(nrows=1, ncols=3, figsize=(15,15))<br><br>for i in range(3):<br>    image = next(aug_iter)[0].astype(&#39;uint8&#39;)<br>    ax[i].imshow(image)<br>    ax[i].axis(&#39;off&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8tasnxtu908P19mdek9IXg.png" /></figure><blockquote>เติมสีแบบกระจกสะท้อน (<strong>Reflect Values</strong>)</blockquote><pre>datagen = ImageDataGenerator(rotation_range=50, fill_mode = &#39;reflect&#39;)<br><br>aug_iter = datagen.flow(cat, batch_size=1)<br><br>fig, ax = pyplot.subplots(nrows=1, ncols=3, figsize=(15,15))<br><br>for i in range(3):<br>    image = next(aug_iter)[0].astype(&#39;uint8&#39;)<br>    ax[i].imshow(image)<br>    ax[i].axis(&#39;off&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GlscOMLop1ToVwRiE97kyg.png" /></figure><blockquote>เติมสีจากภาพแบบต่อกัน (<strong>Wrap Values</strong>)</blockquote><pre>datagen = ImageDataGenerator(rotation_range=30, fill_mode = &#39;wrap&#39;)<br><br>aug_iter = datagen.flow(cat, batch_size=1)<br><br>fig, ax = pyploy.subplots(nrows=1, ncols=3, figsize=(15,15))<br><br>for i in range(3):<br>    image = next(aug_iter)[0].astype(&#39;uint8&#39;)<br>    ax[i].imshow(image)<br>    ax[i].axis(&#39;off&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MOEYY0fL3VrExP9Ci75aBg.png" /></figure><h4>นิยามวิธีการทำ Image Augmentation</h4><pre>datagen = ImageDataGenerator(<br>        rotation_range=0.05,  #Randomly rotate images in the range<br>        zoom_range = 0.2, # Randomly zoom image<br>        width_shift_range=0.1,  #Randomly shift images horizontally<br>        height_shift_range=0.1,  #Randomly shift images vertically<br>        shear_range=0.05 #Randomly shear images<br>)<br><br>datagen.fit(X_train)</pre><h4>นิยาม Model</h4><pre>model = Sequential()<br><br>#1. CNN LAYER<br>model.add(Conv2D(filters = 32, kernel_size = (3,3), padding = &#39;Same&#39;, input_shape=(28, 28, 1)))<br>model.add(Activation(&quot;relu&quot;))<br><br>#2. CNN LAYER<br>model.add(Conv2D(filters = 32, kernel_size = (3,3), padding = &#39;Same&#39;))<br>model.add(Activation(&quot;relu&quot;))<br><br>model.add(MaxPool2D(pool_size=(2, 2)))<br><br>#3. CNN LAYER<br>model.add(Conv2D(filters = 64, kernel_size = (3,3), padding = &#39;Same&#39;))<br>model.add(Activation(&quot;relu&quot;))<br><br>#4. CNN LAYER<br>model.add(Conv2D(filters = 64, kernel_size = (3,3), padding = &#39;Same&#39;))<br>model.add(Activation(&quot;relu&quot;))<br><br>model.add(MaxPool2D(pool_size=(2, 2)))<br><br>#FULLY CONNECTED LAYER<br>model.add(Flatten())<br>model.add(Dense(256))<br>model.add(Activation(&quot;relu&quot;))<br><br>#OUTPUT LAYER<br>model.add(Dense(10, activation=&#39;softmax&#39;))</pre><h4>Compile Model</h4><pre>optimizer = Adam()<br>model.compile(optimizer = optimizer, loss = &quot;categorical_crossentropy&quot;, metrics=[&quot;accuracy&quot;])<br><br>model.summary()</pre><h4>Train Model</h4><pre>NO_EPOCHS = 50<br><br>history = model.fit_generator(datagen.flow(X_train, y_train, batch_size=BATCH_SIZE),<br>                              shuffle=True,<br>                              epochs=NO_EPOCHS, validation_data = (X_val, y_val),<br>                              verbose = 1, steps_per_epoch=X_train.shape[0] // BATCH_SIZE)</pre><h4>Plot กราฟ</h4><pre>plot_accuracy_and_loss(history)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d3Te-RRIMhkqhKAPI6FSPA.png" /></figure><h4>วัดค่า Accuracy จาก Test Dataset</h4><pre>score = model.evaluate(test_data, y_test,verbose=0)<br>print(&quot;Test Loss:&quot;,score[0])<br>print(&quot;Test Accuracy:&quot;,score[1])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/893/1*GqzVYgCzfHM9iyhskEMVEw.png" /></figure><p><em>จากกราฟ Loss ด้านบน เมื่อมีการ Train ทั้งหมด 50 Epoch พบว่า Validation Loss ไม่พุ่งขึ้นในรอบแรกๆ เหมือนในการ Train แบบไม่ใช้เทคนิค Image Augmentation โดยเมื่อวัดประสิทธิภาพการ Predict ด้วย Test Dataset ได้ค่า Accuracy 92.62% อย่างไรก็ตาม ใน Epoch ท้ายๆ Validation Loss ก็ยังมีแนวโน้มที่จะยกสูงขึ้นจนเกิดปัญหา Overfitting</em></p><h3>Batch Normalization</h3><p>Batch Normalization เป็นเทคนิคในการทำ Scaling Data หรือเรียกอีกอย่างหนึ่งว่าการทำ Normalization เพื่อปรับค่าข้อมูลให้อยู่ในขอบเขตที่กำหนด ก่อนส่งออกจาก Node ใน Neural Network Layer เป็น Input ของ Layer ถัดไป ซึ่งเดิมเราจะทำ Normalization ในขั้นตอน Feature Engineering เช่น Normalize ด้วยการแปลงค่าสีของภาพแบบ Grayscale จาก 0–255 เป็น 0–1 โดยนำค่าสีเดิมหารด้วย 255 ฯลฯ</p><p>นอกจากนี้การทำ Data Normalization กับ Feature อย่างเช่น อายุ และเงินเดือน จะทำให้ทั้ง 2 Feature มีน้ำหนักเท่ากัน มีการกระจายตัวเหมือนกัน ไม่มีตัวหนึ่งตัวใดมีอิทธิพลมากกว่ากัน ทั้งยังเป็นการเพิ่มความเร็วในการ Train Model และทำให้ค่า Loss ลดลงเมื่อเทียบกันตอนที่ยังไม่ได้ทำ Normalization เพราะมีค่าข้อมูลที่เล็กกว่า</p><p>ในการทำ Data Normalization เราสามารถเลือกวิธีการได้หลายวิธี เช่น การทำ Min-Max Normalization หรือการทำ Standardization เป็นต้น</p><p><strong>Min-Max Normalization</strong> = 𝑥′ = [𝑥–min(𝑥)]/[max(𝑥) — min(𝑥)]</p><p><strong>Standardization</strong> = 𝑥′ = (𝑥–𝑥¯)/𝜎2</p><p>โดยที่ 𝑥¯ คือ Mean และ 𝜎2 คือ Variance</p><p>Batch Normalization จะใช้วิธีการแบบ <strong>Standardization</strong> ซึ่งจะมีการกำหนดค่า <strong>Mean</strong> และ <strong>Variance</strong> โดยการเรียนรู้จาก Batch ขนาดเล็ก ที่หยิบมาสอน Model ด้วย Layer พิเศษใน Neural Network เอง</p><p>เราจะทดลองใช้ Batch Normalization ร่วมกับเทคนิค Image Augmentation เพื่อแก้ปัญหา Overfitting ตามขั้นตอนดังต่อไปนี้</p><h4>นิยามวิธีการทำ Image Augmentation</h4><pre>datagen = ImageDataGenerator(<br>        rotation_range=0.05,  # Randomly rotate images in the range<br>        zoom_range = 0.2, # Randomly zoom image<br>        width_shift_range=0.1,  # Randomly shift images horizontally<br>        height_shift_range=0.1,  # Randomly shift images vertically<br>        shear_range=0.05<br>)<br><br>datagen.fit(X_train)</pre><h4>นิยาม Model</h4><pre>model = Sequential()</pre><pre>#1. CNN LAYER<br>model.add(Conv2D(filters = 32, kernel_size = (3,3), padding = &#39;Same&#39;, input_shape=(28, 28, 1)))<br>model.add(BatchNormalization())<br>model.add(Activation(&quot;relu&quot;))</pre><pre>#2. CNN LAYER<br>model.add(Conv2D(filters = 32, kernel_size = (3,3), padding = &#39;Same&#39;))<br>model.add(BatchNormalization())<br>model.add(Activation(&quot;relu&quot;))</pre><pre>model.add(MaxPool2D(pool_size=(2, 2)))</pre><pre>#3. CNN LAYER<br>model.add(Conv2D(filters = 64, kernel_size = (3,3), padding = &#39;Same&#39;))<br>model.add(BatchNormalization())<br>model.add(Activation(&quot;relu&quot;))</pre><pre>#4. CNN LAYER<br>model.add(Conv2D(filters = 64, kernel_size = (3,3), padding = &#39;Same&#39;))<br>model.add(BatchNormalization())<br>model.add(Activation(&quot;relu&quot;))</pre><pre>model.add(MaxPool2D(pool_size=(2, 2)))</pre><pre>#FULLY CONNECTED LAYER<br>model.add(Flatten())<br>model.add(Dense(256))<br>model.add(BatchNormalization())<br>model.add(Activation(&quot;relu&quot;))</pre><pre>#OUTPUT LAYER<br>model.add(Dense(10, activation=&#39;softmax&#39;))</pre><h4>Compile Model</h4><pre>optimizer = Adam()<br>model.compile(optimizer = optimizer, loss = &quot;categorical_crossentropy&quot;, metrics=[&quot;accuracy&quot;])<br><br>model.summary()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NcGboWjXq286aYMAsyDDXA.png" /></figure><p>จากภาพจะเห็นว่าใน Batch Normalization Layer จะมี Parameter สำหรับกำหนดค่า Mean และ Variance โดยการเรียนรู้จาก Batch ขนาดเล็กที่หยิบมาสอน Model</p><h4>Train Model</h4><pre>NO_EPOCHS = 50<br>history = model.fit_generator(datagen.flow(X_train, y_train, batch_size=BATCH_SIZE),<br>                              shuffle=True,<br>                              epochs=NO_EPOCHS, validation_data = (X_val, y_val),<br>                              verbose = 1, steps_per_epoch=X_train.shape[0] // BATCH_SIZE)</pre><h4>Plot กราฟ</h4><pre>plot_accuracy_and_loss(history)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JRopVZ7xks977RaWUjTimA.png" /></figure><h4>วัดค่า Accuracy จาก Test Dataset</h4><pre>score = model.evaluate(test_data, y_test,verbose=0)<br>print(&quot;Test Loss:&quot;,score[0])<br>print(&quot;Test Accuracy:&quot;,score[1])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/853/1*YdgsbjT5Ao4CAldFAYZiTg.png" /></figure><p><em>จากกราฟ Loss พบว่า Training Loss มีแนวโน้มที่จะลดลง แต่ Validation Loss ค่อนข้างแกว่ง จึงอาจต้องใช้เทคนิคอื่นร่วมแก้ปัญหา Overfitting ซึ่งเทคนิคหนึ่งที่มักนำมาใช้งานร่วมกับ Batch Normalization คือ Dropout</em></p><h3>Dropout</h3><p>Dropout เป็นเทคนิคในการทำ Regularization ที่เรียบง่าย แต่มีประสิทธิภาพอย่างมาก โดยเมื่อมีการใช้งาน Dropout ภายใน Layer ที่กำหนดแล้ว Node ใน Layer นั้นจะถูกสุ่มเพื่อปิดการทำงานชั่วคราวในแต่ละรอบของการทำ Forward Propagation และ Back-propagation ตามอัตราที่กำหนด ในขณะที่มีการ Train Model ทำให้ไม่มีการ Update Weight ใดๆ ที่ถูกเชื่อมต่อกับ Neuron Node ที่กำลังถูกปิด</p><p>เราจะทดลองใช้เทคนิค Dropout ร่วมกับ Batch Normalization และ Image Augmentation เพื่อแก้ปัญหา Overfitting ตามขั้นตอนดังต่อไปนี้</p><h4>นิยามวิธีการทำ Image Augmentation</h4><pre>datagen = ImageDataGenerator(<br>        rotation_range=0.05,  #Randomly rotate images in the range<br>        zoom_range = 0.2, # Randomly zoom image<br>        width_shift_range=0.1,  #Randomly shift images horizontally<br>        height_shift_range=0.1,  #Randomly shift images vertically<br>        shear_range=0.05 #Randomly shear images<br>)</pre><pre>datagen.fit(X_train)</pre><h4>นิยาม Model</h4><pre>model = Sequential()</pre><pre>#1. CNN LAYER<br>model.add(Conv2D(filters = 32, kernel_size = (3,3), padding = &#39;Same&#39;, input_shape=(28, 28, 1)))<br>model.add(BatchNormalization())<br>model.add(Activation(&quot;relu&quot;))<br>model.add(Dropout(0.3))</pre><pre>#2. CNN LAYER<br>model.add(Conv2D(filters = 32, kernel_size = (3,3), padding = &#39;Same&#39;))<br>model.add(BatchNormalization())<br>model.add(Activation(&quot;relu&quot;))</pre><pre>model.add(MaxPool2D(pool_size=(2, 2)))<br>model.add(Dropout(0.3))</pre><pre>#3. CNN LAYER<br>model.add(Conv2D(filters = 64, kernel_size = (3,3), padding = &#39;Same&#39;))<br>model.add(BatchNormalization())<br>model.add(Activation(&quot;relu&quot;))<br>model.add(Dropout(0.3))</pre><pre>#4. CNN LAYER<br>model.add(Conv2D(filters = 64, kernel_size = (3,3), padding = &#39;Same&#39;))<br>model.add(BatchNormalization())<br>model.add(Activation(&quot;relu&quot;))</pre><pre>model.add(MaxPool2D(pool_size=(2, 2)))<br>model.add(Dropout(0.3))<br></pre><pre>#FULLY CONNECTED LAYER<br>model.add(Flatten())<br>model.add(Dense(256))<br>model.add(BatchNormalization())<br>model.add(Activation(&quot;relu&quot;))<br>model.add(Dropout(0.30))</pre><pre>#OUTPUT LAYER<br>model.add(Dense(10, activation=&#39;softmax&#39;))</pre><h4>Compile Model</h4><pre>optimizer = Adam()<br>model.compile(optimizer = optimizer, loss = &quot;categorical_crossentropy&quot;, metrics=[&quot;accuracy&quot;])</pre><pre>model.summary()</pre><h4>Train Model</h4><pre>NO_EPOCHS = 200<br>history = model.fit_generator(datagen.flow(X_train, y_train, batch_size=BATCH_SIZE),<br>                              shuffle=True,<br>                              epochs=NO_EPOCHS, validation_data = (X_val, y_val),<br>                              verbose = 1, steps_per_epoch=X_train.shape[0] // BATCH_SIZE)</pre><p>เพิ่ม Epoch ในการ Train เป็น 200 จากเดิม 50 Epoch เพราะเราคาดว่า Validation Loss จะลดลงได้มากกว่าก่อนการใช้งาน Dropout</p><h4>Plot กราฟ</h4><pre>plot_accuracy_and_loss(history)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vVgoblTNDXP72KtOoVCUwA.png" /></figure><h4>วัดค่า Accuracy จาก Test Dataset</h4><pre>score = model.evaluate(test_data, y_test,verbose=0)<br>print(&quot;Test Loss:&quot;,score[0])<br>print(&quot;Test Accuracy:&quot;,score[1])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/876/1*b_c0t4zqCnYiyM3lfd4lgg.png" /></figure><p><em>จากกราฟ Loss ด้านบน เมื่อมีการ Train ทั้งหมด 200 Epoch โดยใช้เทคนิค Augmentation, Batch Normalization และ Dropout พบว่า Validation Loss ไม่พุ่งขึ้นจนเกิดปัญหา Overfitting เหมือนกับในการ Train แบบไม่ใช้ Dropout เมื่อวัดประสิทธิภาพการ Predict ด้วย Test Dataset ได้ค่า Accuracy 93.80%</em></p><p>ก็จบกันไปแล้วสำหรับการทำ <strong>Regularization</strong> หากผิดพลาดประการใด ก็ขออภัยมา ณ ที่นี้ด้วยค่ะ ขอบคุณค่ะ ^^</p><h3>Reference</h3><p><a href="https://blog.pjjop.org/modern-regularization-with-data-augmentation-batch-normalization-and-dropout/">การทำ Regularization แบบสมัยใหม่ ด้วยเทคนิค Augmentation, Batch Normalization และ Dropout</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f7008c80a3e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[การวิเคราะห์ประสิทธิภาพของ Machine Learning Model ด้วย Learning Curve]]></title>
            <link>https://suthasom-t.medium.com/%E0%B8%81%E0%B8%B2%E0%B8%A3%E0%B8%A7%E0%B8%B4%E0%B9%80%E0%B8%84%E0%B8%A3%E0%B8%B2%E0%B8%B0%E0%B8%AB%E0%B9%8C%E0%B8%9B%E0%B8%A3%E0%B8%B0%E0%B8%AA%E0%B8%B4%E0%B8%97%E0%B8%98%E0%B8%B4%E0%B8%A0%E0%B8%B2%E0%B8%9E%E0%B8%82%E0%B8%AD%E0%B8%87-machine-learning-model-%E0%B8%94%E0%B9%89%E0%B8%A7%E0%B8%A2-learning-curve-c42185f47a6c?source=rss-e010574c8d5e------2</link>
            <guid isPermaLink="false">https://medium.com/p/c42185f47a6c</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[learning-curve]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Tiwarin Suthasom]]></dc:creator>
            <pubDate>Wed, 30 Sep 2020 12:42:15 GMT</pubDate>
            <atom:updated>2020-09-30T15:25:21.050Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/741/1*WXi_7HIL3FKETFdfegcEmA.png" /><figcaption>ภาพจาก : <a href="http://3.bp.blogspot.com/-I7RePzkTwV8/Uv3juzHvmhI/AAAAAAAABls/AiyXsLCpE8o/s320/Screen+Shot+2014-02-14+at+11.35.49+AM.png">http://3.bp.blogspot.com/-I7RePzkTwV8/Uv3juzHvmhI/AAAAAAAABls/AiyXsLCpE8o/s320/Screen+Shot+2014-02-14+at+11.35.49+AM.png</a></figcaption></figure><p>ในแต่ละครั้งที่เรา Train เราจะดูประสิทธิภาพของ Model ซึ่งประสิทธิภาพเราจะดูจาก 2 ค่าด้วยกันคือค่า Loss กับค่า Accuracy โดยยิ่งค่า<strong> </strong>Loss หรือ Error ของ Model น้อย แสดงว่า Model มีการเรียนรู้ที่ดี หรือ Accuracy มากแสดงว่า Model มีการเรียนรู้ที่ดี</p><p>การวินิจฉัยและแก้ไขปัญหาการเรียนรู้ของ Model อย่างเช่น ปัญหา Underfitting และ Overfitting ได้ เราจะต้องมีความเข้าใจรูปแบบ Learning Curve ที่เกิดขึ้น นอกจากนี้เรายังสามารถพิจารณาจาก Learning Curve ได้ว่า Training Dataset และ Validation Dataset เป็นตัวแทนของ Data ที่เหมาะสมในกระบวนการพัฒนา Model หรือไม่</p><h3>มาเริ่มกันเลย</h3><p>โดยในบทความนี้เราจะทำการวิเคราะห์ประสิทธิภาพของ model จาก 2 Dataset ด้วยกัน มาดูกันเลย!</p><h3>1. Dataset Advertising</h3><p>สามารถไป Download ไฟล์ Dataset กันได้ตาม link ด้านล่างเลย</p><p><a href="https://www.kaggle.com/bumba5341/advertisingcsv">Advertising.csv</a></p><blockquote>ก่อนอื่นเราต้องทำการ import Library ที่เราจำเป็นต้องใช้ก่อน</blockquote><pre>from tensorflow.keras.models import Sequential<br>from tensorflow.keras.layers import Dense<br>from tensorflow.keras.optimizers import SGD</pre><pre>from tensorflow.keras.utils import to_categorical<br>from tensorflow.keras.preprocessing import sequence</pre><pre>import plotly<br>import plotly.graph_objs as go<br>import plotly.express as px</pre><pre>import matplotlib.pyplot as plt<br>import numpy</pre><pre>from pandas import DataFrame<br>from sklearn.model_selection import train_test_split</pre><pre>import pandas as pd<br>%matplotlib inline</pre><blockquote>ถัดมาทำการอ่านไฟล์เข้ามาโดยใช้ Library pandas</blockquote><pre>df = pd.read_csv(&quot;Advertising.csv&quot;)</pre><blockquote>และแสดงข้อมูลในไฟล์ออกมา</blockquote><pre>df.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/743/1*5lW-A9huLoO0Y5QcBGoQAQ.png" /></figure><blockquote>ถัดมาเราจะทำการแบ่งข้อมูลเป็น input(x) กับ output(y)</blockquote><pre>X = df[&#39;TV&#39;].values.reshape(-1,1)<br>y = df[&#39;sales&#39;].values.reshape(-1,1)</pre><blockquote>แบ่งข้อมูลสำหรับ Train และ Test โดยการสุ่มในสัดส่วน 50:50</blockquote><pre>X_train, X_test, y_train, y_test = train_test_split(X, y,       test_size=0.5, shuffle= True)</pre><pre>X_train.shape, X_test.shape, y_train.shape, y_test.shape</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/946/1*iwuHgpHMrbT2Pk2Di0QRXA.png" /></figure><blockquote>เข้ารหัสผลเฉลย แบบ One-Hot Encoding</blockquote><pre>y_train = to_categorical(y_train)<br>y_test = to_categorical(y_test)</pre><blockquote>ทำการนิยาม Model</blockquote><pre>model = Sequential()<br>model.add(Dense(1, input_dim=1, activation=&#39;linear&#39;, kernel_initializer=&#39;he_uniform&#39;))<br>model.compile(loss=&#39;mse&#39;, optimizer=&#39;adam&#39;, metrics=[&#39;accuracy&#39;])<br>model.summary()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*ZWWWPfLRyFfvpXX3fsAUvw.png" /></figure><blockquote>Train Model</blockquote><p>เราได้กำหนด epochs = 200 หรือรอบการ Train 200 รอบ</p><pre>his = model.fit(X_train, y_train, validation_data=(X_test, y_test), epochs=500, verbose=1)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qqX3EAqDnO-DtU5QTG0jZA.png" /></figure><blockquote>ถัดมาเรามาดูกราฟ Loss กัน</blockquote><pre>plotly.offline.init_notebook_mode(connected=True)</pre><pre>h1 = go.Scatter(y=his.history[&#39;loss&#39;], <br>                    mode=&quot;lines&quot;, line=dict(<br>                    width=2,<br>                    color=&#39;blue&#39;),<br>                    name=&quot;loss&quot;<br>                   )<br>h2 = go.Scatter(y=his.history[&#39;val_loss&#39;], <br>                    mode=&quot;lines&quot;, line=dict(<br>                    width=2,<br>                    color=&#39;red&#39;),<br>                    name=&quot;val_loss&quot;<br>                   )</pre><pre>data = [h1,h2]<br>layout1 = go.Layout(title=&#39;Loss&#39;,<br>                   xaxis=dict(title=&#39;epochs&#39;),<br>                   yaxis=dict(title=&#39;&#39;))<br>fig1 = go.Figure(data = data, layout=layout1)<br>plotly.offline.iplot(fig1, filename=&quot;Intent Classification&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*JYP7G1bYcXY3-kJz2jN8AA.png" /></figure><blockquote>Plot Accuracy</blockquote><pre>h1 = go.Scatter(y=his.history[&#39;accuracy&#39;], <br>                    mode=&quot;lines&quot;, line=dict(<br>                    width=2,<br>                    color=&#39;blue&#39;),<br>                    name=&quot;acc&quot;<br>                   )<br>h2 = go.Scatter(y=his.history[&#39;val_accuracy&#39;], <br>                    mode=&quot;lines&quot;, line=dict(<br>                    width=2,<br>                    color=&#39;red&#39;),<br>                    name=&quot;val_acc&quot;<br>                   )</pre><pre>data = [h1,h2]<br>layout1 = go.Layout(title=&#39;Accuracy&#39;,<br>                   xaxis=dict(title=&#39;epochs&#39;),<br>                   yaxis=dict(title=&#39;&#39;))<br>fig1 = go.Figure(data = data, layout=layout1)<br>plotly.offline.iplot(fig1, filename=&quot;Intent Classification&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*fux45OHDaBgfjFsWwpimkw.png" /></figure><p>จากกราฟด้านบนพบว่าเกิดการ<em> “ </em><strong>Unrepresentative Train Dataset</strong> <strong>”</strong> คือเมื่อมีการ Train Model มากขึ้น Gap ระหว่าง Training Loss กับ Validation Loss รวมทั้ง Gap ระหว่าง Training Accuracy กับ Validation Accuracy สูง ซึ่งแสดงว่าเรามี Training Dataset น้อยไป ไม่เพียงพอในการ Train Model</p><h3>2. Dataset housing</h3><p>สามารถไป Download ไฟล์ Dataset กันได้ตาม link ด้านล่างเลย</p><p><a href="https://www.kaggle.com/harrywang/housing?select=housing.csv">California Housing Data (1990)</a></p><blockquote>ทำการอ่านไฟล์ datasetที่ 2 เข้ามาโดยใช้ Library pandas</blockquote><pre>df = pd.read_csv(&quot;housing.csv&quot;)</pre><blockquote>และแสดงข้อมูลในไฟล์ออกมา</blockquote><pre>df.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0KCAH3ndeWRlJZyHJNLKrg.png" /></figure><blockquote>ทำการแบ่งข้อมูลเป็น input(x) กับ output(y)</blockquote><pre>X = df[&#39;population&#39;].values.reshape(-1,1)<br>y = df[&#39;households&#39;].values.reshape(-1,1)</pre><blockquote>แบ่งข้อมูลสำหรับ Train และ Test โดยการสุ่มในสัดส่วน 70:30</blockquote><pre>X_train, X_test, y_train, y_test = train_test_split(X, y,<br>                                                    test_size = 0.3,<br>                                                    shuffle= True)<br>X_train.shape,y_train.shape,X_test.shape,y_test.shape</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/872/1*HGOS2pvfX5rr19p_npfPgQ.png" /></figure><blockquote>เข้ารหัสผลเฉลย แบบ One-Hot Encoding</blockquote><pre>y_train = to_categorical(y_train)<br>y_test = to_categorical(y_test)</pre><blockquote>ทำการนิยาม Model</blockquote><pre>model = Sequential()<br>model.add(Dense(1, input_dim=1, activation=&#39;relu&#39;, kernel_initializer=&#39;he_uniform&#39;))<br>model.compile(loss=&#39;mse&#39;, optimizer=&#39;adam&#39;, metrics=[&#39;accuracy&#39;])<br>model.summary()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/967/1*QvKZTZsk1QjJLSXBc2BJTg.png" /></figure><blockquote>Train Model</blockquote><p>เราได้กำหนด epochs = 200 หรือรอบการ Train 200 รอบ</p><pre>his = model.fit(X_train, y_train, validation_data=(X_test, y_test), epochs=200, batch_size=128, verbose=2)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YtkxCGNSyYiDfNWnMFTRBQ.png" /></figure><blockquote>Plot Loss</blockquote><pre>plotly.offline.init_notebook_mode(connected=True)</pre><pre>h1 = go.Scatter(y=his.history[&#39;loss&#39;], <br>                    mode=&quot;lines&quot;, line=dict(<br>                    width=2,<br>                    color=&#39;blue&#39;),<br>                    name=&quot;loss&quot;<br>                   )<br>h2 = go.Scatter(y=his.history[&#39;val_loss&#39;], <br>                    mode=&quot;lines&quot;, line=dict(<br>                    width=2,<br>                    color=&#39;red&#39;),<br>                    name=&quot;val_loss&quot;<br>                   )</pre><pre>data = [h1,h2]<br>layout1 = go.Layout(title=&#39;Loss&#39;,<br>                   xaxis=dict(title=&#39;epochs&#39;),<br>                   yaxis=dict(title=&#39;&#39;))<br>fig1 = go.Figure(data = data, layout=layout1)<br>plotly.offline.iplot(fig1, filename=&quot;Intent Classification&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*gWBfmHjPVzZjQPPVrdr3rQ.png" /></figure><blockquote>Plot Accuracy</blockquote><pre>h1 = go.Scatter(y=his.history[&#39;accuracy&#39;], <br>                    mode=&quot;lines&quot;, line=dict(<br>                    width=2,<br>                    color=&#39;blue&#39;),<br>                    name=&quot;acc&quot;<br>                   )<br>h2 = go.Scatter(y=his.history[&#39;val_accuracy&#39;], <br>                    mode=&quot;lines&quot;, line=dict(<br>                    width=2,<br>                    color=&#39;red&#39;),<br>                    name=&quot;val_acc&quot;<br>                   )</pre><pre>data = [h1,h2]<br>layout1 = go.Layout(title=&#39;Accuracy&#39;,<br>                   xaxis=dict(title=&#39;epochs&#39;),<br>                   yaxis=dict(title=&#39;&#39;))<br>fig1 = go.Figure(data = data, layout=layout1)<br>plotly.offline.iplot(fig1, filename=&quot;Intent Classification&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*lVDA4t16nxYVQ4FREgLUKw.png" /></figure><p>จากกราฟ Loss ด้านบนจะพบว่าเป็น Learning Curve แบบ “ <strong>Good Fit Learning Curve ”</strong> ซึ่งจะเห็นว่าทั้ง Training Loss และ Validation Loss มีค่าลดลงอย่างต่อเนื่องจนถึงจุดหนึ่งมันจะคงที่ ซึ่งกราฟทั้ง 2 เส้น จะมี Gap ระหว่างกันน้อยมาก โดยรูปแบบ Learning Curve ดังกล่าว แสดงว่าเป็น Model แบบ Good Fitting หรือเป็น Model ที่มีการเรียนรู้ที่ดี สามารถนำไป Predict ข้อมูลที่ไม่เคยพบเห็นมาก่อนได้อย่างแม่นยำ</p><p>ก็จบกันไปแล้วสำหรับบทความนี้แล้วพบกันใหม่บทความหน้า ขอบคุณค่าาา ^^</p><h3>Reference</h3><p><a href="https://blog.pjjop.org/diagnose-machine-learning-model-performance-with-learning-curves/">การวิเคราะห์ประสิทธิภาพ Machine Learning Model ด้วย Learning Curve</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c42185f47a6c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploy Machine Learning Model ด้วย FastAPI, Uvicorn, Docker การ Clone Git การสร้าง VM ผ่าน…]]></title>
            <link>https://suthasom-t.medium.com/deploy-machine-learning-model-%E0%B8%94%E0%B9%89%E0%B8%A7%E0%B8%A2-fastapi-uvicorn-docker-%E0%B8%81%E0%B8%B2%E0%B8%A3-clone-git-%E0%B8%81%E0%B8%B2%E0%B8%A3%E0%B8%AA%E0%B8%A3%E0%B9%89%E0%B8%B2%E0%B8%87-vm-%E0%B8%9C%E0%B9%88%E0%B8%B2%E0%B8%99-28296ee16d14?source=rss-e010574c8d5e------2</link>
            <guid isPermaLink="false">https://medium.com/p/28296ee16d14</guid>
            <dc:creator><![CDATA[Tiwarin Suthasom]]></dc:creator>
            <pubDate>Wed, 23 Sep 2020 16:57:22 GMT</pubDate>
            <atom:updated>2020-09-23T17:05:10.650Z</atom:updated>
            <content:encoded><![CDATA[<h3>Deploy Machine Learning Model ด้วย FastAPI, Docker การ Clone Git การสร้าง VM ผ่าน microsoft azure และ การทำ Load Testing ใน Locast</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*EYDYTx05kQMfV8fH" /><figcaption>Photo by <a href="https://unsplash.com/@nasa?utm_source=medium&amp;utm_medium=referral">NASA</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>1. นำ Model ที่เราสร้างและ Train เสร็จแล้วขึ้น GitLab</h3><p>ก่อนอื่นหากใครยังไม่ได้สมัคร GitLab ต้องทำการสมัคร Gitlab ก่อน ไปสมัครตามลิ้งค์ <a href="https://gitlab.cpsudevops.com/users/sign_in">https://gitlab.cpsudevops.com/users/sign_in</a> ได้เลย</p><p>ถัดมาเมื่อทำการสมัครแล้วเราก็มาทำการสร้าง Project ใน GitLab โดยกดที่<strong>เครื่องหมาย + </strong>และเลือก <strong>New project </strong>และทำการตั้งชื่อ<strong> project </strong>จากนั้นกด<strong> Create Project</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a6dOMd_5CfwEtywPjyGL7g.png" /></figure><p>จากนั้นจะได้หน้าตาดังภาพด้านล่าง</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Alf4R0PZc-99vGmD2G9hXw.png" /></figure><p>แล้วเราก็จะมาทำการ Git เพื่อนำไฟล์ขึ้นไปไว้ใน GitLab โดยเราจะทำการ Git ผ่าน <strong>visual studio </strong>และอย่าลืมเปลี่ยนให้ Terminal เปลื่ยนใช้เป็นแบบ cmd</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IKQgf3sAAd51Ijp9WDTLaQ.png" /></figure><p>ถัดมาทำการ git global setup</p><pre>git config --global user.name &quot;username&quot; <br>git config --global user.email &quot;email&quot;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uwelXBJfVKucr_SN3tvxhA.png" /></figure><p>และทำการนำไฟล์ขึ้นไปไว้ใน GitLab ด้วยคำสั่ง</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/775/1*NlHMHiyrGFIn5QAzTiIgVA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HwRuzRw4gOjuPoa9dnAXdw.png" /></figure><p>ถ้าหากขึ้นแบบนี้แสดงว่าสำเร็จแล้วให้ทำการ Refresh หน้าเว็บ GitLab</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CzrEKeI8F2WNDeGHClDREw.png" /></figure><p>หากตอนทำ Git เกิดปัญหาอาจเป็นไปได้ว่าในเครื่องคอมพิวเตอร์ยังไม่ได้ติดตั้ง git .ให้ทำการติดตั้งได้ที่ <a href="https://git-scm.com/downloads">https://git-scm.com/downloads?fbclid=IwAR0LX30SFVmu22-R01jJM18pJyvKljgLHw-pAleTGX1_Ikwpfgyka5_BQuE</a></p><h3>2. สร้าง virtual machines ใน Microsoft Azure</h3><p>หากใครที่ยังไม่มีหรือยังไม่ได้สมัครก็สามารถทำการสมัครก่อนได้ที่ <a href="https://azureforeducation.microsoft.com/en-us/Institutions">https://azureforeducation.microsoft.com/en-us/Institutions</a></p><p>หากทำการสมัครและเปิดหน้าเว็ปเข้าไปจะได้หน้าตาประมาณนี้</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_XP0u42u7c7uRoX8QyTEuQ.png" /><figcaption>สำหรับนักศึกสามารถใช้อีเมลมหาลัยสมัครได้เพื่อรับสิทธิประโยชน์จาก Microsoft</figcaption></figure><p>กด <strong>Virtual machines</strong> และกด<strong> + add </strong>เลือก<strong> +Virtual machines</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wxhXpubqHz7FnPKPe3_Glg.png" /></figure><p>จะได้เว็บดังภาพด้านล่าง</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UIzeC6WOTYxAhBft5e7_Sg.png" /></figure><p>กรอกตามภาพได้เลยโดย</p><ol><li><strong>Virtual machines name </strong>จะตั้งชื่ออะไรก็ได้</li><li>และ <strong>Username </strong>กับ<strong> Password </strong>กำหนดเองได้เลยแต่!!<strong> ต้องจำ *ย้ำว่าต้องจำ</strong></li></ol><p>และกด <strong>Review + Create</strong></p><p>รอจนขึ้นหน้านี้</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/996/1*jT7tltjJ4zP2J_oad55tXg.png" /></figure><p>กด Create และรอจนกว่า <strong>Go to Resource </strong>จะขึ้น</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RmZn17IDzGzhN2394IkaFQ.png" /></figure><p>หลังจากนั้นกด <strong>Go to Resource</strong></p><p>และเราจะได้หน้าตาแบบนี้</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sZ4v8tLLXw8Rbh9StFZD8A.png" /></figure><h3>3. นำโฟลเดอร์ลง VM Server</h3><p>ถัดมาเราจะเอาโฟลเดอร์มาลงใน VM กัน โดยใช้ผ่าน SSH โดยใช้คำสั่ง</p><pre>ssh username@ipaddress</pre><p>**username ของ vm ที่เราได้กำนดไปเมื่อตอนที่เรา create Virtual Machine <br>**ipaddress คือ Public IP address ที่อยู่ใน Overview ใน Microsoft Azure</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bxAXwIOzzCmgOnTyNeGygw.png" /><figcaption>password ของ vm ที่เราได้กำหนดไป ซึ่งตอนกรอกเราจะไม่เห็นฉะนั้นต้องกรอกให้ถูก</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0q996Z2RQJDh2abQPCAJ7w.png" /><figcaption>หากสำเร็จจะได้หน้าตาแบบนี้</figcaption></figure><p>ต่อมาเราจะทำการ Clone ตัว Model ที่เราอัพขึ้น Gitlab เข้ามาใน VM</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KQEY-CZMfu_Ze2iBqvOuhQ.png" /></figure><p>ทำการ copy link จาก Clone with HTTP แล้วพิมคำสั่ง</p><pre>git clone ตามด้วยlinkที่เรา copy มา</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/872/1*By81GApu9EhJHzid7V7CLA.png" /><figcaption>username กับ password ของ Gitlab</figcaption></figure><h3>4. Import Docker In VM Server</h3><p>ลง Docker ใน VM server</p><pre>sudo -i<br>snap install docker</pre><p>หลังจากเสร็จแล้วกด Ctrl+D</p><p>สร้าง Bridge Network</p><pre>sudo docker network create basic_model_network</pre><p>อัพให้ทำงานผ่านตัว Docker</p><pre>sudo docker-compose up -d</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3zmrX2hFZnvkPnevcbCOEg.png" /></figure><p>และทำการเช็ค</p><pre>sudo docker-compose ps</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*InosyNbPJS1tziLS7eYdsw.png" /></figure><h3>5. Testing In FastAPI</h3><pre>เข้าไปที่ http://Ip_Address:7001/docs</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ljLrI0Fo2RXhwPEPLbk5Ww.png" /></figure><p>กด getclass และกด Try it out เปลี่ยน Request body จะได้ผลลัพธ์ดังนี้</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ovAnvg8TJz0T1PWcQu3_-g.png" /></figure><h3>6. ลง Locust In VM Server</h3><p>ติดตั้ง python3</p><pre>sudo -i<br>apt install python3-pip</pre><p>ถัดมาติดตั้ง locust</p><pre>pip3 install locust</pre><p>ไปที่ Path ที่เราทำการเก็บ Model ที่เรา Train แล้วไว้และพิมคำสั่ง</p><pre>locust -f loadtest.py --host=http://localhost:7001</pre><p>**localhost คือ Public IP address ที่อยู่ใน Overview ใน Microsoft Azure</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nKieO66LcuaNDS1QM9Gw7w.png" /></figure><p>หลังจากนั้นให้ไปที่ <a href="http://13.76.42.61:8089/">http://localhost:8089</a> เพื่อทำการดู Load Testing ของเรา</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1Z3LfM2abPZMDTZreQksQg.png" /></figure><p>ใส่ค่า Number of total users to simulate และ Spawn rate ลงไปเท่าไรก็ได้แต่ควรเริ่มจากค่าน้อยๆก่อน</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D4L808zFT554zui7pDGADQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2LeNFpl7aU9F3pbcGV5gKQ.png" /></figure><p>เท่านี้เราก็สามารถ เอา Model มา Deploy ด้วย FastAPI, Docker การ Clone Git การสร้าง VM ผ่าน microsoft azure และ การทำ Load Testing ใน Locast ได้แล้ว</p><p>หากผิดพลาดประการใดก็ขออภัยมา ณ ที่นี้ด้วยค่ะ</p><p>REFERENCE</p><p><a href="https://blog.pjjop.org/deploy-ml-model-on-production-with-fastapi-uvicorn-and-docker/">การ Deploy Machine Learning Model บน Production ด้วย FastAPI, Uvicorn และ Docker</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=28296ee16d14" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Effects of the Learning Rate on Model Performance]]></title>
            <link>https://suthasom-t.medium.com/the-effects-of-the-learning-rate-on-model-performance-95450eeabca9?source=rss-e010574c8d5e------2</link>
            <guid isPermaLink="false">https://medium.com/p/95450eeabca9</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[learning-rate]]></category>
            <dc:creator><![CDATA[Tiwarin Suthasom]]></dc:creator>
            <pubDate>Sun, 20 Sep 2020 15:04:27 GMT</pubDate>
            <atom:updated>2020-09-20T15:04:27.002Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qxqEamHtoRVxLYUM" /><figcaption><strong>Parameter</strong>Photo by <a href="https://unsplash.com/@chrisliverani?utm_source=medium&amp;utm_medium=referral">Chris Liverani</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4><strong>Learning Rate คืออะไร ?</strong></h4><p><strong>Learning Rate</strong> เป็นหนึ่งในตัวแปรของ <strong>Hyperparameter</strong> ที่เป็นตัวแปรภายนอก Model ซึ่งไม่ได้เกิดจากการประมาณค่าโดยตรงจาก Dataset เหมือนกับ <strong>Parameter</strong> นอกจากนี้ตัว <strong>Hyperparameter</strong> ยังมีตัวแปรอื่นๆอีกเช่น Droupout Rate, Batch Size เป็นต้น</p><blockquote><strong>Learning Rate</strong> มีหน้าที่ในการปรับขนาดของ Error ในแต่ละครั้งของการปรับปรุง Weight และ Bias ด้วย Back-propagation Algorithm</blockquote><blockquote>ซึ่งการปรับเปลี่ยน Learning Rate จะมีผลกระทบกับประสิทธิภาพของ Model เป็นอย่างมาก</blockquote><p>ในบทความนี้เราจะมาลองปรับเปลี่ยนค่า Learning Rate ด้วยวิธีการต่างๆ ได้แก่ Momentum, Learning Rate Decay, การลด Learning Rate เมื่อเจอกับที่ราบสูง (Plateau) และการใช้ Adaptive Learning Rate Algorithm เพื่อปรับค่า Learning Rate แบบอัตโนมัติ</p><h3>Impact of Learning Rate</h3><p>โดยในบทความนี้เราจะใช้ Mnist Dataset ที่เป็นรูปภาพตัวเลข 0–9</p><p>เรามาเริ่มจาก import Library กันเลย</p><pre>from tensorflow.keras.datasets import mnist<br>from tensorflow.keras.layers import Dense, Dropout, Flatten<br>from tensorflow.keras.models import Sequential<br>from tensorflow.keras.optimizers import SGD<br>from tensorflow.keras.utils import to_categorical</pre><pre>from sklearn.datasets import make_blobs<br>from matplotlib import pyplot<br>from numpy import where</pre><pre>from sklearn.model_selection import train_test_split</pre><pre>import pandas as pd<br>import plotly.express as px<br>import matplotlib.pyplot as plt<br>import numpy as np</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/968/1*fVijOwRhEJQoNmIwpnTmJg.png" /></figure><p>ต่อมาเราจะทำการลดขนาด pixel ของภาพและดูขนาด shape ของมัน</p><pre>(X_train, y_train), (X_test, y_test) = mnist.load_data()</pre><pre>X_train, X_test = X_train / 255.0, X_test / 255.0</pre><pre>X_train = np.array([X.flatten() for X in X_train])<br>X_test = np.array([X.flatten() for X in X_test])<br>X_train.shape, y_train.shape, X_test.shape, y_test.shape</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/789/1*FVFaR7JkmqanHOcFWGGwJQ.png" /></figure><p>นำ Dataset ส่วนที่ Train มาแปลงเป็น DataFrame</p><pre>X_train_pd = pd.DataFrame(X_train)<br>y_train_pd = pd.DataFrame(y_train, columns=[&#39;class&#39;])<br>df = pd.concat([X_train_pd, y_train_pd], axis=1)<br>df[&#39;class&#39;] = df[&#39;class&#39;].astype(str)</pre><pre>y_train = to_categorical(y_train)<br>y_test = to_categorical(y_test)</pre><p>นิยาม Model, Complie Model และ Plot Accuracy</p><pre>def fit_model(trainX, trainy, testX, testy, lrate):<br>    model = Sequential()<br>    model.add(Flatten(input_shape=(28,28)))<br>    model.add(Dense(units = 50, activation = &#39;relu&#39;, kernel_initializer=&#39;he_uniform&#39;))<br>    model.add(Dense(units = 10, activation=&#39;softmax&#39;))<br> <br>    opt = SGD(lr=lrate)<br>    model.compile(loss=&#39;categorical_crossentropy&#39;, optimizer=opt, metrics=[&#39;accuracy&#39;])<br> <br>    history = model.fit(trainX, trainy, validation_data=(testX, testy), epochs=50, verbose=0)<br>    pyplot.plot(history.history[&#39;accuracy&#39;], label=&#39;train&#39;)<br>    pyplot.plot(history.history[&#39;val_accuracy&#39;], label=&#39;test&#39;)<br>    pyplot.title(&#39;lr=&#39;+str(lrate), pad=-35)<br>learning_rates = [1E-0, 1E-1, 1E-2, 1E-3, 1E-4, 1E-5, 1E-6, 1E-7]<br>for i in range(len(learning_rates)):<br>    plot_no = 420 + (i+1)<br>    pyplot.subplot(plot_no)<br>    fit_model(X_train, y_train, X_test, y_test, learning_rates[i])<br>pyplot.tight_layout()<br>pyplot.savefig(&#39;lr1.jpeg&#39;, dpi=300)<br>pyplot.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xgrm_4c4GJunA8aYL8nWCA.png" /></figure><p>เมื่อ Train เสร็จแล้ว จะเห็นกราฟ Accuracy หรือ <strong>Learning Curve</strong> ของ Model ดังภาพ</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FIIMXk_fUrXdapHbSumTJw.jpeg" /></figure><p>จากภาพจะเห็นได้ว่า Ir = 0.01,0.001,0.0001, Model ประสบความสำเร็จในการเรียนรู้มากกว่าที่ lr ค่าอื่นๆ โดยที่ lr = 0.01, Model มีอัตราการเรียนรู้สูงที่สุด</p><h3>Momentum</h3><p>Momentum (<em>β</em>) เป็นเทคนิคในการลดการแกว่งของ Learning Curves พร้อมกับเร่งอัตราการเรียนรู้ของ Model ให้เร็วขึ้น โดยใช้ <strong>Velocity</strong> (ความเร็ว) ของรอบก่อนหน้า และ Error ในรอบปัจจุบันเพื่อปรับปรุง Weight และ Bias ด้วยค่าน้ำหนักตามที่กำหนด</p><p>นิยาม Model, กำหนด lr = 0.01, Complie Model และ Plot Accuracy</p><pre>def fit_model(trainX, trainy, testX, testy, momentum):<br>    model = Sequential()<br>    model.add(Flatten(input_shape=(28,28)))<br>    model.add(Dense(units = 50, activation = &#39;relu&#39;, kernel_initializer=&#39;he_uniform&#39;))<br>    model.add(Dense(units = 10, activation=&#39;softmax&#39;))<br>    opt = SGD(lr=0.01, momentum=momentum)<br>    <br>    model.compile(loss=&#39;categorical_crossentropy&#39;, optimizer=opt, metrics=[&#39;accuracy&#39;])</pre><pre>history = model.fit(trainX, trainy, validation_data=(testX, testy), epochs=200, verbose=0)</pre><pre>pyplot.plot(history.history[&#39;accuracy&#39;], label=&#39;train&#39;)<br>    pyplot.plot(history.history[&#39;val_accuracy&#39;], label=&#39;test&#39;)<br>    pyplot.title(&#39;momentum=&#39;+str(momentum), pad=-80)<br> <br>momentums = [0.0, 0.5, 0.9, 0.99]<br>for i in range(len(momentums)):<br>    plot_no = 220 + (i+1)<br>    pyplot.subplot(plot_no)</pre><pre>fit_model(X_train, y_train, X_test, y_test, momentums[i])</pre><pre>pyplot.tight_layout()<br>pyplot.savefig(&#39;momentum.jpeg&#39;, dpi=300)<br>pyplot.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BnA1JVV9BUSlK8R3HyODjA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fo5fB3tnLI8ZkgtLN1Wc4g.jpeg" /></figure><p>จากภาพด้านบน momentum (<em>β</em>) = 0.0, Learning Curves ของ Model มีการแกว่งน้อยกว่า momentum (<em>β</em>) ตัวอื่นๆ รวมทั้งมีอัตราการเรียนรู้ที่เร็วขึ้นกว่าตอนที่ไม่ได้ใช้ momentum อย่างเห็นได้ชัด</p><h3>Learning Rate Decay</h3><p>นอกจากนี้เรายังสามารถเพิ่มประสิทธิภาพของ Model ได้โดยการค่อย ๆ ลด Learning Rate (Learning Rate Decay) ในแต่ละ Epoch ในอัตราที่เหมาะสม เช่น</p><pre>def decay_lrate(initial_lrate, decay, iteration):<br>    return initial_lrate * (1.0 / (1.0 + decay * iteration))<br> <br>decays = [1E-1, 1E-2, 1E-3, 1E-4]<br>lrate = 0.01<br>n_updates = 200<br>for decay in decays:<br>    <br>    lrates = [decay_lrate(lrate, decay, i) for i in range(n_updates)]<br>    <br>    pyplot.plot(lrates, label=str(decay))<br>pyplot.legend()<br>pyplot.savefig(&#39;decay.jpeg&#39;, dpi=300)<br>pyplot.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/971/1*22YItyLx1zwxeAPqMeMkbw.png" /></figure><p>นิยาม Model, กำหนด lr = 0.01, Complie Model และ Plot Accuracy</p><pre>def fit_model(trainX, trainy, testX, testy, decay):<br>    model = Sequential()<br>    model.add(Flatten(input_shape=(28,28)))<br>    model.add(Dense(units = 50, activation = &#39;relu&#39;, kernel_initializer=&#39;he_uniform&#39;))<br>    model.add(Dense(units = 10, activation=&#39;softmax&#39;))</pre><pre>opt = SGD(lr=0.01, decay=decay)<br>    model.compile(loss=&#39;categorical_crossentropy&#39;, optimizer=opt, metrics=[&#39;accuracy&#39;])<br>    <br>    history = model.fit(trainX, trainy, validation_data=(testX, testy), epochs=200, verbose=0)</pre><pre>pyplot.plot(history.history[&#39;accuracy&#39;], label=&#39;train&#39;)<br>    pyplot.plot(history.history[&#39;val_accuracy&#39;], label=&#39;test&#39;)<br>    pyplot.title(&#39;decay=&#39;+str(decay), pad=-80)</pre><pre>decay_rates = [1E-1, 1E-2, 1E-3, 1E-4]<br>for i in range(len(decay_rates)):<br>    plot_no = 220 + (i+1)<br>    pyplot.subplot(plot_no)<br>    fit_model(X_train, y_train, X_test, y_test, decay_rates[i])</pre><pre>pyplot.legend()<br>pyplot.savefig(&#39;decay2.jpeg&#39;, dpi=300)<br>pyplot.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ilB8bpEBWLmtt-NJ9leWVg.jpeg" /></figure><p>จากภาพด้านบนจะเห็นว่าที่ decay = 0.001 และ 0.0001, มีค่า Accuracy ที่สูงกว่าตอนที่ยังไม่ได้ใช้ decay</p><h3>Drop Learning Rate on Plateau</h3><p>หาก Loss Value ไม่ลดลงมาระยะเวลาหนึ่ง เราจะเรียกสถานการณ์นี้ว่าการเจอที่ราบสูง (Plateau) เราจะแก้ปัญหาด้วยการนำ Learning Rate ด้วยการคูณกับค่า <strong>factor </strong>ตามตัวอย่างต่อไปนี้</p><p>ก่อนอื่นต้อง import Library ที่จะใช้เพิ่มก่อน</p><pre>from tensorflow.keras.callbacks import Callback<br>from tensorflow.keras.callbacks import ReduceLROnPlateau<br>from tensorflow.keras import backend</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/745/1*ZDJDapWSsIe3tLgTbKTd1g.png" /></figure><pre>class LearningRateMonitor(Callback):<br>    def on_train_begin(self, logs={}):<br>        self.lrates = list()<br> <br>    def on_epoch_end(self, epoch, logs={}):<br>        optimizer = self.model.optimizer<br>        lrate = float(backend.get_value(self.model.optimizer.lr))<br>        self.lrates.append(lrate)<br> <br>def fit_model(trainX, trainy, testX, testy, patience):<br>    model = Sequential()<br>    model.add(Flatten(input_shape=(28,28)))<br>    model.add(Dense(units = 50, activation = &#39;relu&#39;, kernel_initializer=&#39;he_uniform&#39;))<br>    model.add(Dense(units = 10, activation=&#39;softmax&#39;))</pre><pre>opt = SGD(lr=0.01)<br>    model.compile(loss=&#39;categorical_crossentropy&#39;, optimizer=opt, metrics=[&#39;accuracy&#39;])</pre><pre>rlrp = ReduceLROnPlateau(monitor=&#39;val_loss&#39;, factor=0.1, patience=patience, min_delta=1E-7)<br>    lrm = LearningRateMonitor()<br>    history = model.fit(trainX, trainy, validation_data=(testX, testy), epochs=200, verbose=0, callbacks=[rlrp, lrm])<br>    return lrm.lrates, history.history[&#39;loss&#39;], history.history[&#39;accuracy&#39;]</pre><pre>def line_plots(patiences, series, st):<br>    for i in range(len(patiences)):<br>        pyplot.subplot(220 + (i+1))<br>        pyplot.plot(series[i])<br>        pyplot.title(&#39;patience=&#39;+str(patiences[i]), pad=-80)<br>    pyplot.legend()<br>    pyplot.savefig(&#39;patience.jpeg&#39;, dpi=300)<br>    pyplot.show()<br> <br>patiences = [2, 5, 10, 15]<br>lr_list, loss_list, acc_list, = list(), list(), list()<br>for i in range(len(patiences)):<br>    lr, loss, acc = fit_model(X_train, y_train, X_test, y_test, patiences[i])<br>    lr_list.append(lr)<br>    loss_list.append(loss)<br>    acc_list.append(acc)</pre><pre>line_plots(patiences, lr_list, &#39;lr&#39;)</pre><pre>line_plots(patiences, loss_list, &#39;loss&#39;)</pre><pre>line_plots(patiences, acc_list, &#39;acc&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/762/1*nbtvrjo2iATKto-xAY1T_Q.png" /></figure><p>Learning Rate (แกน y) ที่ลดลง ตามเงื่อนไขที่กำหนด (patience = 2, 5, 10, 15)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/749/1*bjhJVWMnXi9_Zb2KTFOWQg.png" /></figure><p>Loss Value (แกน y) ที่เกิดจากการปรับลด Learning Rate ตามเงื่อนไขที่กำหนด (patience = 2, 5, 10, 15)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/761/1*ws7wimmFMqze_Q8u-lQnNQ.png" /></figure><p>Accuracy (แกน y) ที่เกิดจากการปรับลด Learning Rate ตามเงื่อนไขที่กำหนด (patience = 2, 5, 10, 15)</p><p>และจากภาพด้านบน จะเห็นว่าที่ patience = 10 และ 15, Loss Value ลดน้อยลงจนเกือบๆถึง 0.0 ขณะที่ Accuracy เพิ่มขึ้นมากกว่า 95%</p><h3>Adaptive Learning Rates Gradient Descent</h3><p>วิธีสุดท้าย เราจะเปรียบเทียบ Adaptive Learning Rate Algorithm ได้แก่ <strong>AdaGrad</strong> (Adaptive Gradient Algorithm), <strong>RMSprop</strong> (Root Mean Square Propagation) และ <strong>Adam</strong> (Adaptive Moment Estimation) กับ Optimizer พื้นฐาน (SGD Optimizer)</p><pre>def fit_model(trainX, trainy, testX, testy, optimizer):<br>    model = Sequential()<br>    model.add(Flatten(input_shape=(28,28)))<br>    model.add(Dense(units = 50, activation = &#39;relu&#39;, kernel_initializer=&#39;he_uniform&#39;))<br>    model.add(Dense(units = 10, activation=&#39;softmax&#39;))</pre><pre>model.compile(loss=&#39;categorical_crossentropy&#39;, optimizer=optimizer, metrics=[&#39;accuracy&#39;])<br>    <br>    history = model.fit(trainX, trainy, validation_data=(testX, testy), epochs=200, verbose=0)</pre><pre>pyplot.plot(history.history[&#39;accuracy&#39;], label=&#39;train&#39;)<br>    pyplot.plot(history.history[&#39;val_accuracy&#39;], label=&#39;test&#39;)<br>    pyplot.title(&#39;opt=&#39;+optimizer, pad=-80)</pre><pre>momentums = [&#39;sgd&#39;, &#39;rmsprop&#39;, &#39;adagrad&#39;, &#39;adam&#39;]<br>for i in range(len(momentums)):<br>    plot_no = 220 + (i+1)<br>    pyplot.subplot(plot_no)</pre><pre>fit_model(X_train, y_train, X_test, y_test, momentums[i])</pre><pre>pyplot.legend()<br>pyplot.savefig(&#39;adaptive.jpeg&#39;, dpi=300)    <br>pyplot.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PX8T4Mvr5hIba-jO7l2tOA.jpeg" /></figure><p>ก็จบไปแล้วสำหรับการปรับเปลี่ยนค่า Learning Rate ด้วยวิธีการต่างๆ ในบทความนี้ก็ขอจบเพียงเท่านี้ หากผิดพลากประการใดก็ของอภัยมา ณ ที่นี้ด้วยค่ะ ขอบคุณค่ะ</p><h3>REFERENCE</h3><p><a href="https://blog.pjjop.org/learning-rate/">The Effects of the Learning Rate on Model Performance</a></p><p>และขอบคุณความรู้เรื่องวิธีการแปลงหรือปรับขนาดของ dataset จาก</p><p><a href="https://medium.com/@promtao_c/the-effects-of-the-learning-rate-on-model-performance-mnist-dataset-94b462ee2245">The Effects of the Learning Rate on Model Performance (MNIST Dataset)</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=95450eeabca9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stochastic Gradient Descent (SGD) with Tensorflow and Keras Framework by google colab]]></title>
            <link>https://suthasom-t.medium.com/stochastic-gradient-descent-sgd-with-tensorflow-and-keras-framework-by-google-colab-69408f4b5091?source=rss-e010574c8d5e------2</link>
            <guid isPermaLink="false">https://medium.com/p/69408f4b5091</guid>
            <category><![CDATA[sgd]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Tiwarin Suthasom]]></dc:creator>
            <pubDate>Wed, 02 Sep 2020 10:07:27 GMT</pubDate>
            <atom:updated>2020-09-02T10:07:27.523Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*S3oLN40uWnGmP63lOFEDUg.gif" /><figcaption><a href="https://images.app.goo.gl/FjBAqmZdLbarSzaf8">https://images.app.goo.gl/FjBAqmZdLbarSzaf8</a></figcaption></figure><h4>Stochastic Gradient Descent (SGD) คืออะไร ?</h4><p>เป็นวิธีการหลักในการ Train Neural Network Model ซึ่งเป็นวิธีที่ทำให้ <strong>Loss </strong>สามารถค้นพบค่าที่น้อยที่สุดหรือ <strong>Loss Value</strong> เคลื่อนที่ไปยัง <strong>จุดต่ำที่สุด</strong> โดยใช้ <strong>Gradient</strong> หรือ <strong>ความชัน </strong>เป็นตัวบอกขนาดและทิศทางในการปรับ Parameters ซึ่งเป็นอัลกอริทึมที่เร็วมากๆอัลกอริทึมหนึ่งเลยก็ว่าได้</p><p>ในบทความนี้เราจะมาดูการเคลื่อนที่ของ Loss Value ในแต่ละรอบของการ Train Model แบบ <strong>Linear Regression</strong> โดยใช้ Tensorflow และ Keras Framework</p><h3>Linear Regression with Tensorflow</h3><p>โดยเราจะใช้ <strong>Gradient Descent Method และ dataset </strong>weatherHistory.csv</p><h4>มาเริ่มกันเลย!!</h4><p>Import Library ที่จำเป็นต้องใช้</p><pre>import tensorflow.compat.v1 as tf<br>tf.disable_v2_behavior()</pre><pre>import pandas as pd<br>import numpy as np<br>import matplotlib.pyplot as plt<br>import seaborn as seabornInstance<br>from sklearn.model_selection import train_test_split<br>from sklearn import metrics</pre><pre>%matplotlib inline</pre><p>ซึ่งใน google colab เมื่อทำการ plot กราฟ plotly.offline.iplot(…) จะไม่แสดงภาพกราฟขึ้นมาเราจึงต้องทำการเพิ่ม configure_plotly_browser_state() เข้าไปเพื่อให้ภาพกราฟแสดงขึ้นมา</p><pre>def configure_plotly_browser_state():<br>  import IPython<br>  display(IPython.core.display.HTML(&#39;&#39;&#39;<br>        &lt;script src=&quot;/static/components/requirejs/require.js&quot;&gt;  <br>        &lt;/script&gt;<br>        &lt;script&gt;<br>          requirejs.config({<br>            paths: {<br>              base: &#39;/static/base&#39;,<br>              plotly: &#39;<a href="https://cdn.plot.ly/plotly-1.5.1.min.js?noext&#39;">https://cdn.plot.ly/plotly-1.5.1.min.js? <br>noext&#39;</a>,<br>            },<br>          });<br>        &lt;/script&gt;<br>        &#39;&#39;&#39;))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/941/1*UueN0wHRFpCK43BTvlsA-g.jpeg" /></figure><p>และให้พิมโค้ดด้านล่างนี้ในทุกๆ cell ที่เราต้องการ plot กราฟที่ใช้ library plotly</p><pre>configure_plotly_browser_state()</pre><p>ถัดมาเรามากำหนด seed และ Epoch ที่ใช้ในการ Train</p><pre>np.random.seed(seed=13)<br>Epoch = 500</pre><p>อ่านข้อมูล Dataset เข้ามา</p><pre>dataset = pd.read_csv(&quot;/content/drive/My Drive/Colab Notebooks/weatherHistory.csv&quot;)<br>dataset.shape</pre><p>วิธีการนำ dataset เข้ามาไว้ใน google colab และการหาที่อยู่ของไฟล์ได้กล่าวไปแล้วในบทความด้านล่างนี้</p><p><a href="https://medium.com/@suthasom_t/feature-engineering-for-ai-machine-learning-with-google-colab-e243b7ef804d">Feature Engineering for AI (Machine Learning) with Google Colab</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/885/1*xO1ST9mdFNtl_EqfOpjmoA.jpeg" /></figure><p>จะพบว่า dataset ที่เรานำมามีทั้งหมด 96453 แถวและ 12 คอลัม ดูข้อมูลในตารางกัน</p><pre>dataset.describe()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BiU3CxJh1LFWWu2UmkRVFg.png" /></figure><p>ถัดมาเราจะทำการนำ Column Apparent Temperature (C) มาทำเป็น Input Data หรือตัวแปรอิสระ (Predictor) และ Temperature (C) มาทำเป็นผลเฉลย หรือตัวแปรตาม (Response) และทำการ Plot เพื่อดูลักษณะของข้อมูล</p><pre>dataset.plot(x=&#39;Apparent Temperature (C)&#39;, y=&#39;Temperature (C)&#39;, style=&#39;o&#39;)<br>plt.title(&#39;Apparent Temperature vs Temperature&#39;)<br>plt.xlabel(&#39;Apparent Temperature&#39;)<br>plt.ylabel(&#39;Temperature&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/827/1*yq4kUbgGt2AJNRt-N34H7A.png" /></figure><p>และมาดูการกระจายตัวของ Column Apparent Temperature (C) กัน</p><pre>plt.figure(figsize=(15,10))<br>plt.tight_layout()<br>seabornInstance.distplot(dataset[&#39;Temperature (C)&#39;])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ecJw0OSW2V7BSHf65-J1DA.png" /></figure><p>ทำการแยก Dataset เป็นตัวแปรอิสระ (x) และผลเฉลย (y)</p><pre>X = dataset[&#39;Apparent Temperature (C)&#39;].values.reshape(-1,1)<br>y = dataset[&#39;Temperature (C)&#39;].values.reshape(-1,1)<br>X.shape</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/846/1*Gfa3NGWfy5v1sTQjqr0gXw.png" /></figure><p>แบ่งข้อมูลออกเป็น 2 ชุด สำหรับ Train 80% และ Test 20%</p><pre>X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, shuffle= True)<br><br>X_train.shape, X_test.shape, y_train.shape, y_test.shape</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/911/1*X4SNsMlOgiv_76gnMx9c1g.png" /></figure><p>นำ X_train เข้า Model ทั้งหมด 77162 Row ด้วย Tensorflow</p><pre>W = tf.Variable(tf.random.uniform([1], -1.0, 1.0))<br>b = tf.Variable(tf.random.uniform([1], -1.0, 1.0))<br><br>y = W * X_train + b</pre><p>ทำการนิยาม Loss Function เป็นแบบ Mean Squared Error (MSE)</p><pre>loss = tf.reduce_mean(tf.square(y - y_train))</pre><p>กำหนด Optimizer และ Learning Rate</p><pre>optimizer = tf.train.GradientDescentOptimizer(0.0001)</pre><pre>train = optimizer.minimize(loss)</pre><p>ซึ่งใน tensorflow เวอร์ชั่นปัจจุบันไม่มี attribute ‘GradientDescentOptimizer’ เราจึงทำการ import library import tensorflow.compat.v1 as tf และ tf.disable_v2_behavior() ดังข้างต้นที่เราได้ทำการ import library เข้ามา</p><p>โดย Optimizer จะทำ <strong>Back-propagation Algorithm </strong>เพื่อปรับค่า Weight (W) และ Bias (b) ให้เราอัตโนมัติ โดยไม่ต้องมีการหาอนุพันธ์ด้วยตัวเอง</p><p>ต่อมาเคลียร์ Tensorflow Variable</p><pre>init = tf.global_variables_initializer()</pre><p>สร้าง session และรัน init เพื่อเคลียร์ค่า Variable จริงๆ</p><pre>sess = tf.Session()<br>sess.run(init)</pre><p>ถัดมาทำการ Train Model</p><pre>his=[]<br>wb = []<br><br>for step in range(EPOCH):<br>    sess.run(train)<br>    his.append(sess.run(loss))<br>    print(step, sess.run(W), sess.run(b), sess.run(loss))<br>    wb.append([sess.run(W)[0], sess.run(b)[0], sess.run(loss)])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/991/1*AQaPxRLeMCR0-QAojz8uSA.png" /></figure><p>จะทำการ Train ไป 500 ครั้งตามที่เราได้กำหนด Epoch และจะเห็นได้ว่า Tensorflow ใช้เวลา Train ไม่นานนัก</p><p>ขั้นต่อมาดึง Weight (W) และ Bias (b) มาสร้าง Linear Regression Model</p><pre>M = sess.run(W)<br>C = sess.run(b)</pre><p>Function Predict</p><pre>def predict(X, M, C):<br>    y = M*X+C<br>    return y[0]</pre><p>แปลง Loss Value List เป็น DataFrame</p><pre>df = pd.DataFrame(his, columns=[&#39;loss&#39;])</pre><p>Plot เพื่อดู Loss</p><pre>import plotly<br>from plotly.offline import iplot<br>import plotly.graph_objs as go</pre><pre>configure_plotly_browser_state()</pre><pre>plotly.offline.init_notebook_mode(connected=True)</pre><pre>h1 = go.Scatter(y=df[&#39;loss&#39;],<br>                    mode=&quot;lines&quot;, line=dict(<br>                    width=2,<br>                    color=&#39;blue&#39;),<br>                    name=&quot;loss&quot;)<br>data = [h1]</pre><pre>layout1 = go.Layout(title=&#39;Loss&#39;,<br>                    xaxis=dict(title=&#39;epochs&#39;),<br>                    yaxis=dict(title=&#39;&#39;))<br>fig1 = go.Figure(data, layout=layout1)<br>plotly.offline.iplot(fig1)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/871/1*NWxUSA1xkXVbBVuZ8UhN1Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*8w-jG8jQ6ZDAk6b5osI87Q.png" /></figure><p>Predict</p><pre>y_pred = [predict(i, M, C) for i in X_test]<br>y_test.shape</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/746/1*3yzL-8G7yresg9GXbXEWkQ.png" /></figure><pre>y_test = y_test.reshape(-1)<br>y_test.shape</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/710/1*5Uf30daJIydfp1oT7LGdGg.png" /></figure><pre>df = pd.DataFrame({&#39;Actual&#39;: y_test, &#39;Predicted&#39;: y_pred})<br>df.head(10)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/966/1*jwNWRSGi9Pu-Er4MW3RfgA.png" /></figure><p>Plot กราฟเปรียบเทียบผลการทำนายกับค่าจริง</p><pre>df1 = df.head(25)<br>df1.plot(kind=&#39;bar&#39;,figsize=(16,10))<br>plt.grid(which=&#39;major&#39;, linestyle=&#39;-&#39;, linewidth=&#39;0.5&#39;, color=&#39;green&#39;)<br>plt.grid(which=&#39;minor&#39;, linestyle=&#39;:&#39;, linewidth=&#39;0.5&#39;, color=&#39;black&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SzKYdP0pR5aZmyLtuD5L-g.png" /></figure><pre>M = [i[0] for i in wb]<br>L = [i[2] for i in wb]<br>C = [i[1] for i in wb]</pre><p>ทำการแสดง Model ที่สร้างจากการ Train ใน Epoch ที่ 1</p><pre>y_pred = [predict(i, M[0], C[0]) for i in X_test]<br><br>plt.scatter(X_test, y_test,  color=&#39;gray&#39;)<br>plt.plot(X_test, y_pred, color=&#39;red&#39;, linewidth=2)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/836/1*C26GV0OK-cg0pAJSajt1Kg.png" /></figure><p>มาดู Epoch ที่ 5</p><pre>y_pred = [predict(i, M[4], C[4]) for i in X_test]<br><br>plt.scatter(X_test, y_test,  color=&#39;gray&#39;)<br>plt.plot(X_test, y_pred, color=&#39;red&#39;, linewidth=2)<br>plt.savefig(&#39;5_model.jpeg&#39;, dpi=300)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/884/1*f7rJBTzPeee3E3q3rFIhRg.png" /></figure><p>อีกสักนิดมาดู Epoch ที่ 10 กัน</p><pre>y_pred = [predict(i, M[9], C[9]) for i in X_test]<br><br>plt.scatter(X_test, y_test,  color=&#39;gray&#39;)<br>plt.plot(X_test, y_pred, color=&#39;red&#39;, linewidth=2)<br>plt.savefig(&#39;10_model.jpeg&#39;, dpi=300)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/767/1*QYY0NUYRFfY2BH8DN0oyug.png" /></figure><p>สุดท้ายมาดู Model ที่สร้างจากการ Train 500 Epoch</p><pre>y_pred = [predict(i, M[499], C[499]) for i in X_test]<br><br>plt.scatter(X_test, y_test,  color=&#39;gray&#39;)<br>plt.plot(X_test, y_pred, color=&#39;red&#39;, linewidth=2)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/756/1*hdC8eW9Xjla9-JHTVSGjGA.png" /></figure><p>ดู Loss Value เทียบกับค่า Weight</p><pre>plt.scatter(M, L,  color=&#39;red&#39;)<br>plt.savefig(&#39;weight.jpeg&#39;, dpi=300)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/740/1*aIDUbTLlqWNpE6ws2yFM6Q.png" /></figure><p>Loss Value เทียบกับค่า Bias</p><pre>plt.scatter(C, L, color=&#39;gray&#39;)<br>plt.savefig(&#39;bias.jpeg&#39;, dpi=300)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/708/1*EWpo15EQDGeNv2JqwmDkwA.png" /></figure><p>สุดท้ายแล้วเรามาดู Loss Value เทียบกับค่า Weight และ Bias</p><pre>import plotly.express as px</pre><pre>configure_plotly_browser_state()</pre><pre>df = pd.DataFrame({&#39;W&#39;: M, &#39;Bias&#39;: C, &#39;Loss&#39;: L})<br>fig = px.scatter_3d(df, x=&#39;W&#39;, y=&#39;Bias&#39;, z=&#39;Loss&#39;)<br>fig.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pHKeLFIz09r3BNob7jOPzg.png" /></figure><p>มาดูประสิทธิภาพของ Model ด้วย Mean Absolute Error, Mean Squared Error และ Root Mean Squared Error</p><pre>print(&#39;Mean Absolute Error:&#39;, metrics.mean_absolute_error(y_test, y_pred))  <br>print(&#39;Mean Squared Error:&#39;, metrics.mean_squared_error(y_test, y_pred))  <br>print(&#39;Root Mean Squared Error:&#39;, np.sqrt(metrics.mean_squared_error(y_test, y_pred)))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/1*dmHgo_T7O4USCCvVghrg7Q.png" /></figure><p>จะเห็นได้ว่าค่า Error น้อยมากๆๆๆ</p><h3>Linear Regression with Keras</h3><p>เราจะสุ่มแบ่ง Dataset เป็นก้อนเล็กๆที่มีขนาด 64 Row (Batch Size เท่ากับ 64) เพื่อนำไป Train Model ซึ่งเราจะเรียกว่า <strong>Stochastic Gradient Descent </strong>เนื่องจากการ Train Model โดยใช้<strong> </strong>Keras Framework นั้นจะใช้เวลาค่อนข้างนาน การจะนำ Dataset เข้า Train Model เป็นก้อนใหญ่ๆ จึงไม่เหมาะสม</p><h4>มาเริ่มกันเลย!!</h4><p>import Library ที่จำเป็นต้องใช้</p><pre>from tensorflow.python.keras.models import Sequential<br>from tensorflow.python.keras.layers import Dense<br>from keras import backend as K</pre><pre>import plotly<br>from plotly.offline import iplot<br>import plotly.graph_objs as go</pre><p>นิยาม Root Mean Squared Error</p><pre>def rmse(y_true, y_pred):<br>return K.sqrt(K.mean(K.square(y_pred - y_true), axis=-1))</pre><p>นิยาม Model</p><pre>model = Sequential()<br>model.add(Dense(1, input_dim=1, kernel_initializer=&#39;random_uniform&#39;, activation=&#39;linear&#39;))<br>model.summary()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/929/1*DxpmMw8WemqDs656TPzsig.png" /></figure><p>ทำการ Compile Model</p><pre>model.compile(loss=&#39;mse&#39;, optimizer=&#39;adam&#39;, metrics=[&#39;mae&#39;, &#39;mse&#39;, rmse])</pre><p>Train Model โดยสุ่มแบ่งข้อมูล Train 80% และ Validate อีก 20% โดยกำหนด Batch Size เท่ากับ 64</p><pre>history = model.fit(X_train, y_train, epochs=EPOCH, batch_size=64,  verbose=1, validation_split=0.2, shuffle=True)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WKN8OrUR-bmSMSmLyK7mAQ.png" /></figure><p>Plot Loss และ Validate Loss</p><pre>configure_plotly_browser_state()</pre><pre>h2 = go.Scatter(y=history.history[&#39;loss&#39;], <br>                    mode=&quot;lines&quot;, line=dict(<br>                    width=2,<br>                    color=&#39;blue&#39;),<br>                    name=&quot;loss&quot;)<br><br>h3 = go.Scatter(y=history.history[&#39;val_loss&#39;], <br>                    mode=&quot;lines&quot;, line=dict(<br>                    width=2,<br>                    color=&#39;green&#39;),<br>                    name=&quot;val_loss&quot;)<br>                    <br>data = [h2, h3]<br><br>layout1 = go.Layout(title=&#39;Loss&#39;,<br>                   xaxis=dict(title=&#39;epochs&#39;),<br>                   yaxis=dict(title=&#39;&#39;))<br>fig1 = go.Figure(data, layout=layout1)<br>plotly.offline.iplot(fig1)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q30cvaXhuMssIxrlw-RLUQ.png" /></figure><p>Predict</p><pre>y_pred = model.predict(X_test)</pre><p>แปลงเป็น DataFrame</p><pre>y_pred = y_pred.flatten()<br>df = pd.DataFrame({&#39;Actual&#39;: y_test, &#39;Predicted&#39;: y_pred})<br>df.head(10)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/829/1*45X_7x8zqUiWOeEMngoQVA.png" /></figure><p>Plot กราฟเปรียบเทียบผลการทำนายกับค่าจริง</p><pre>df1 = df.head(25)<br>df1.plot(kind=&#39;bar&#39;,figsize=(16,10))<br>plt.grid(which=&#39;major&#39;, linestyle=&#39;-&#39;, linewidth=&#39;0.5&#39;, color=&#39;green&#39;)<br>plt.grid(which=&#39;minor&#39;, linestyle=&#39;:&#39;, linewidth=&#39;0.5&#39;, color=&#39;black&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Shg0lpJKfx7BO2dWg11Vnw.png" /></figure><p>มาดู Model ที่สร้างจากการ Train 500 Epoch กัน</p><pre>plt.scatter(X_test, y_test,  color=&#39;gray&#39;)<br>plt.plot(X_test, y_pred, color=&#39;red&#39;, linewidth=2)<br>plt.savefig(&#39;keras_500_model.jpeg&#39;, dpi=300)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/752/1*8yse2rmfdVHRVSvaNOlGUg.png" /></figure><p>มาดูประสิทธิภาพของ Model ด้วย Mean Absolute Error, Mean Squared Error และ Root Mean Squared Error</p><pre>print(&#39;Mean Absolute Error:&#39;, metrics.mean_absolute_error(y_test, y_pred))  <br>print(&#39;Mean Squared Error:&#39;, metrics.mean_squared_error(y_test, y_pred))  <br>print(&#39;Root Mean Squared Error:&#39;, np.sqrt(metrics.mean_squared_error(y_test, y_pred)))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/909/1*Sw7nD9bNRzFJjE17dDToWw.png" /></figure><blockquote><strong>จะเห็นได้ว่าเมื่อใช้ Keras เทียบกับการที่ใช้ tensorflow นั้น Keras มีค่า Error น้อยกว่า Tensorflow แต่ข้อเสียของ Keras คือใช้เวลาที่ค่อนข้างนานในการ Train แต่กระบวนการทำสั้น ซึ่งต่างการ Tensorflow ที่ใช้เวลาไม่นานในการ Train แต่กระบวนการทำนั้นยาวกว่า</strong></blockquote><p>สำหรับบทความนี้ก็ขอจบเพียงเท่านี้ขอบคุณที่แวะเข้ามาอ่านนะคะ หากผิดพลาดประการใดก็ขออภัยด้วยค่ะ บ๊ายบายยย~</p><h3>Reference</h3><p><a href="https://blog.pjjop.org/introduction-to-stochastic-gradient-descent-with-tensorflow-and-keras/">Introduction to Stochastic Gradient Descent with Tensorflow and Keras Framework</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=69408f4b5091" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Back-propagation Algorithm Neural Network with numpy]]></title>
            <link>https://suthasom-t.medium.com/back-propagation-algorithm-neural-network-with-numpy-816b34ef0670?source=rss-e010574c8d5e------2</link>
            <guid isPermaLink="false">https://medium.com/p/816b34ef0670</guid>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[numpy]]></category>
            <category><![CDATA[backpropagation]]></category>
            <dc:creator><![CDATA[Tiwarin Suthasom]]></dc:creator>
            <pubDate>Wed, 26 Aug 2020 06:32:06 GMT</pubDate>
            <atom:updated>2020-08-26T06:35:56.922Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5roIkAgaCJtfbXOi" /><figcaption>Photo by <a href="https://unsplash.com/@alinnnaaaa?utm_source=medium&amp;utm_medium=referral">Alina Grubnyak</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><figure><img alt="https://blog.pjjop.org/content/images/2020/08/image-3-1.png" src="https://cdn-images-1.medium.com/max/1024/1*MmXci_eUZZX-mO-1_k4tLA.png" /><figcaption>รูปภาพจาก <a href="https://blog.pjjop.org/content/images/2020/08/image-3-1.png">https://blog.pjjop.org/content/images/2020/08/image-3-1.png</a></figcaption></figure><p><strong>Perceptron</strong> คือโหนดกลมๆที่เราเห็นดังภาพข้างบนการทำงานจะรับข้อมูลเข้ามาและทำการคำนวณด้วยฟังก์ชันของตัวมันเองจากนั้นจะแสดงผลลัพธ์ออกมา และนำผลลัพธ์ไปเทียบกับค่าที่เรารับมาและหาค่า error เพื่อที่จะได้นำไปปรับปรุงค่าในฟังก์ชันให้เกิดค่า error น้อยที่สุด</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JcDjsbmigllJW0lsG7VujA.png" /></figure><h4>เรามาเริ่มจาก Forward Propagation</h4><blockquote>จากภาพด้านบนโหนดสีฟ้าจะเป็นโหนด <strong>Input Layer</strong></blockquote><blockquote><strong>Output Layer</strong> จะเป็นโหนดสีเหลืองและโหนดสีน้ำตาล</blockquote><p>นำ <strong>Weight</strong> ที่เกิดจากการสุ่มในช่วงเริ่มต้นของการ Train คูณกับ <strong>Input Data </strong>แล้วนำผลลัพธ์จากการคูณมาบวกกับ <strong>Bias (B)</strong> ซึ่งเกิดจากการสุ่มในช่วงเริ่มต้นเช่นกัน</p><pre>Z = W * X + B</pre><p>เราจะแทน Weight (W) ด้วย Matrix ขนาด mxn โดย m คือจำนวน Output Node (ในที่นี้มี 1 Node) และ n คือ จำนวน Input Node (ในที่นี้มี 2 Node)</p><pre>W = [w1 w2]</pre><p>X จะเป็น Matrix ขนาด nx1 ที่แทนกลุ่มของ <strong>Input Node</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/734/1*r3PT032zi6Sgt0ggLiJqxg.png" /></figure><p>และ B เป็น Matrix ขนาด mx1</p><pre>B = [b]</pre><p>คำนวณ Z ได้ดังนี้</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/708/1*0I2Qmm7f4WSfJyh2XdzVbA.jpeg" /></figure><p>สมมติว่าเราให้ X, W, B เป็นดังภาพข้างล่าง</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nMt95syn6D749m2AI_hobA.png" /></figure><p>Z ก็จะเท่ากับ</p><pre>Z = [w1x1 + w2x2] + [b]<br>  = [(0.2)(0.05) + (0.5)(0.1)] + [0.3]<br>  = [0.36]</pre><p>ถัดมาเราจะใช้ <strong>Sigmoid Function </strong>ในการปรับค่า<strong> Activate Function </strong>เพื่อทำให้มันอยู่ในช่วง <strong>0–1</strong></p><p>ดังนั้นผลลัพธ์สุดท้ายที่เป็นค่าที่ Model ทำนายออกมาได้ หรือ ŷ จะเท่ากับ Sigmoid(z)</p><pre>ŷ = Sigmoid(z) = Sigmoid(0.36) = 0.5890</pre><h3>Loss Function</h3><p>เป็นขั้นตอนที่ประเมินว่าผลการ Predict คลาดเคลื่อนกับ Output y มากน้อยแค่ไหนด้วย ด้วย Loss Function (<strong>L</strong>) = Loss(y, ŷ)</p><p>สมมติให้ y เท่ากับ 0.7</p><pre>L = Loss(y,ŷ) <br>  = (y - ŷ)^2 <br>  = (0.7 - 0.589)^2 = 0.0123</pre><h3>Back-propagation</h3><p>เป็นการปรับค่า w2 จากการหาอนุพันธ์ของ L เทียบกับ w2 หรือความชัน</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w0_43hYZMCfutyLIo8vGfw.jpeg" /></figure><p>ใช้กฎลูกโซ่ (Chain Rule) เพราะใน w2 ไม่มี L</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r3jEhvMkPYa3Lg0_R6GGkA.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tPTZmZHjT76IaoBSxAqtJQ.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7LpCFBQ3svnIiyk7k9HxHA.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/635/1*meg9ZT0v4EkawDUkaZUWLw.jpeg" /></figure><p>ดังนั้น Error_at_w2 = (-0.222)(0.242)(0.1) = -0.005</p><p>ถัดมาเราให้ <strong>Learning Rate</strong> เท่ากับ 0.5 เพื่อนำมาปรับค่า w2</p><pre>Update w2 = w2 - Learning_Rate*Error_at_w1<br>          = 0.5-(0.5)(-0.005)<br>          = 0.5025</pre><p>ดังนั้น w2 ใหม่ของเราจะมีค่า 0.5025 ซึ่งมากกว่าเดิมมานิดนึง</p><h3>Implement with NumPy</h3><p>การดำเนินการกับ <strong>Numpy</strong> หรือการนำ <strong>Perceptron </strong>มาประยุกต์ใช้กับ <strong>Numpy</strong></p><p>เริ่มจากเขียนคลาส NeuralNetwork</p><pre>class NeuralNetwork:<br>    def __init__(self, x, y):<br>        self.input      = x<br>        self.weights1   = np.random.rand(self.input.shape[1],4) <br>        self.weights2   = np.random.rand(4,1)                 <br>        self.y          = y<br>        self.output     = np.zeros(y.shape)</pre><p>กำหนดค่า x, y</p><pre>import numpy as np</pre><pre>X = np.array([[0,0,1],<br>              [0,1,1],<br>              [1,0,1],<br>              [1,1,1]])</pre><pre>y = np.array([[0],[1],[1],[0]])</pre><p>สร้าง nn1 แล้ว print ดูค่าต่างและรูปร่างต่างๆของ nn1</p><pre>nn1 = NeuralNetwork(X,y)<br>nn1.input.shape<br>print(nn1.input)</pre><pre>nn1.weights1.shape<br>print(nn1.weights1)</pre><pre>nn1.weights2.shape<br>print(nn1.weights2)</pre><pre>nn1.y.shape<br>print(nn1.y)</pre><pre>nn1.output.shape<br>print(nn1.output)</pre><h3>Neural Network Class</h3><pre>def sigmoid(x):<br>    return 1.0/(1+ np.exp(-x))</pre><pre>def sigmoid_derivative(x):<br>    return x * (1.0 - x)</pre><pre>class NeuralNetwork:<br>    def __init__(self, x, y, l):<br>        self.input      = x<br>        self.weights1   = np.random.rand(self.input.shape[1],4) <br>        self.weights2   = np.random.rand(4,1)                 <br>        self.y          = y<br>        self.output     = np.zeros(self.y.shape)<br>        self.learning_rate = l<br>        <br>    def loss(self):<br>        return sum((self.y - self.output)**2)</pre><pre>def feedforward(self):<br>        self.layer1 = sigmoid(np.dot(self.input, self.weights1))<br>        self.output = sigmoid(np.dot(self.layer1, self.weights2))</pre><pre>def backprop(self):<br>        #learning_rate = 1.0<br>        <br>        d_weights2 = np.dot(self.layer1.T, (2*(self.y - self.output) * sigmoid_derivative(self.output)))<br>        d_weights1 = np.dot(self.input.T,  (np.dot(2*(self.y - self.output) * sigmoid_derivative(self.output), self.weights2.T) * sigmoid_derivative(self.layer1)))</pre><pre>#self.weights1 += d_weights1<br>        #self.weights2 += d_weights2<br>        <br>        self.weights1 += self.learning_rate*d_weights1<br>        self.weights2 += self.learning_rate*d_weights2</pre><h3>Train Model</h3><pre>learning_rate = 0.1<br>nn1 = NeuralNetwork(X,y,learning_rate)</pre><pre>loss=[]</pre><pre>for i in range(1000):<br>    nn1.feedforward()<br>    nn1.backprop()<br>    loss.append(nn1.loss())</pre><h3>Plot Loss</h3><pre>import pandas as pd<br>from matplotlib import pyplot as plt  <br>%matplotlib inline</pre><pre>import plotly<br>import plotly.graph_objs as go</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/877/1*Jk7PN_T3o6Tj9JJVnsrPqQ.jpeg" /></figure><pre>df = pd.DataFrame(loss, columns=[&#39;loss&#39;])<br>df.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/885/1*oYJIJMVyazWgemFN72HYDw.jpeg" /></figure><pre>plotly.offline.init_notebook_mode(connected=True)</pre><pre>h1 = go.Scatter(y=df[&#39;loss&#39;], <br>                    mode=&quot;lines&quot;, line=dict(<br>                    width=2,<br>                    color=&#39;blue&#39;),<br>                    name=&quot;loss&quot;)<br>data = [h1]</pre><pre>layout1 = go.Layout(title=&#39;Loss&#39;,<br>                   xaxis=dict(title=&#39;epochs&#39;),<br>                   yaxis=dict(title=&#39;&#39;))<br>fig1 = go.Figure(data, layout=layout1)<br>plotly.offline.iplot(fig1)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nJl0QHZYAYsX9EXTQI9wug.jpeg" /></figure><p>ให้ทำการเปลี่ยนค่า learning_rate ไปเรื่อยๆตั้งแต่ 0.1–1.0 และให้ทำการเปลี่ยน h1 ไปเรื่อยๆจนถึง h10 เช่นตัวอย่างด้านล่าง</p><pre>learning_rate = 0.2<br>nn2 = NeuralNetwork(X,y,learning_rate)</pre><pre>loss=[]</pre><pre>for i in range(1000):<br>    nn2.feedforward()<br>    nn2.backprop()<br>    loss.append(nn2.loss())</pre><pre>df = pd.DataFrame(loss, columns=[&#39;loss&#39;])<br>df.head()</pre><pre><br>h2 = go.Scatter(y=df[‘loss’], <br> mode=”lines”, line=dict(<br> width=2,<br> color=’red’),<br> name=”loss”)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/871/1*f2pxZ9Rw1etfAv40Ac0tkg.jpeg" /></figure><p>เมื่อถึง learning_rate = 1.0 และ h10 ให้ทำการ plot กราฟออกมาเพื่อดูผลลัพธ์</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4IeMm8X31EGPx6JX8Zs8TQ.jpeg" /></figure><p>จากภาพจะเห็นได้ว่าค่า Loss ลดลงเรื่อยๆนั่นแสดงว่ามี Error เกิดขึ้นน้อยที่สุด</p><p>เพียงเท่านี้ก็สามารถนำ <strong>Perceptron </strong>มาประยุกต์ใช้กับ <strong>Numpy </strong>ด้วยวิธี<strong> Back-propagation Algorithm </strong>ได้แล้ว</p><p>สำหรับบทความนี้ก็ขอจบเพียงเท่านี้ขอบคุณค่าาา ^^</p><h3>reference</h3><p><a href="https://blog.pjjop.org/basic-machine-learning/">Implement the Back-propagation Algorithm from Scratch with NumPy</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=816b34ef0670" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Feature Engineering for AI (Machine Learning) with Google Colab]]></title>
            <link>https://suthasom-t.medium.com/feature-engineering-for-ai-machine-learning-with-google-colab-e243b7ef804d?source=rss-e010574c8d5e------2</link>
            <guid isPermaLink="false">https://medium.com/p/e243b7ef804d</guid>
            <dc:creator><![CDATA[Tiwarin Suthasom]]></dc:creator>
            <pubDate>Wed, 19 Aug 2020 04:05:21 GMT</pubDate>
            <atom:updated>2020-08-19T05:07:23.626Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IR29xCHjzWRQPjUm" /><figcaption>Photo by <a href="https://unsplash.com/@campaign_creators?utm_source=medium&amp;utm_medium=referral">Campaign Creators</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>What is Feature Engineering ?</h3><p>คือ วิธีการที่นำ data หรือข้อมูลดิบที่ยังไม่ผ่านการกลั่นกรองมาทำกระบวนการให้ data มีความพร้อมมากที่สุดเพราะ Machine Learning จะเรียนรู้จากการ Input แสดงเป็น Output ออกมาและในตัว Input จะมี Feature ต่าง ๆ อยู่ในแต่ละ Column ซึ่งในแต่ละ row หรือ column อาจจะมี missing values หรือข้อมูลที่สูญหายอยู่ดังนั้นจึงมีการนำกระบวนการ Feature Engineering มาใช้เพื่อเพิ่มประสิทธิภาพของ Machine Learning Model นั่นเอง.</p><p>ซึ่งในบทความนี้ผู้เขียนจะพาไปฝึกเทคนิคการแก้ปัญหาด้วย Feature Engineering ทั้งหมด 7 เทคนิคด้วยกัน มีอะไรบ้างมาดูกัน</p><ol><li>Imputation</li><li>Handling Outliers</li><li>Drop Outlier with Standard Deviation</li><li>Drop with Percentiles</li><li>Binning</li><li>Log Transform</li><li>One-hot encoding</li></ol><p>แต่ช้าก่อน ก่อนที่เราจะเริ่มทำกันเราต้องทำการสำรวจตรวจสอบข้อมูลกันซะก่อนเพื่อพิจารณาคุณภาพของข้อมูลและนำมาวิเคราะห์ว่าเราควรจะเลือกทำ Feature Engineering ในเทคนิคไหน? ให้เหมาะสมที่สุด</p><p>ซึ่งเราก็มี <strong>ProfileReport</strong> Function เป็น Function ใน Library ของ Pandas ที่จะช่วยให้เราสามารถดูการวิเคราะห์ค่าต่างๆของข้อมูลได้อย่างรวดเร็วและง่ายดายด้วยโค้ดบรรทัดเดียวโดยที่เราไม่ต้องมาวิเคราะห์เองเลย</p><p>ก่อนอื่นเราต้องทำการติดตั้ง Pandas Profiling Library ก่อนโดยใน google colab เราจะใช้ <strong>pip install </strong>จากใน GitHub เนื่องจาก pip install pandas-profiling[notebook]ใน google colab ไม่รองรับแล้วซึ่งเราจะใช้คำสั่งข้างล่างแทนพิมคำสั่งตามได้เลย</p><pre>pip install <a href="https://github.com/pandas-profiling/pandas-profiling/archive/master.zip">https://github.com/pandas-profiling/pandas-profiling/archive/master.zip</a></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xn7qkzvSRpOVZ3UZHiV8zg.jpeg" /></figure><p>ต่อมาทำการ import library ต่างๆที่ต้องใช้</p><pre>import numpy as np<br>import pandas as pd<br>from pandas_profiling import ProfileReport</pre><p>ถัดมาเป็นการนำ Data ชื่อ <a href="https://gitlab.cpsudevops.com/nuttachot/dataset_w5/blob/master/titanic.csv">titanic</a> ที่เราทำการโหลดเตรียมไว้เข้ามาใน google colab</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/445/1*5U2VTEjN-bAi3_mOnphC-Q.png" /><figcaption>กด upload file titanic ลง google colab</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1010/1*QeanKD7VZ0kjYwpaM9WLgA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/441/1*T20ZJGTSvyjvhoIwdh8vlg.jpeg" /><figcaption>จะได้ไฟล์ titanic.csv เข้ามาอยู่ใน google colab</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J2JN8mqWFfGRqeiYeTqN2w.jpeg" /><figcaption>คลิกขาวที่ไฟล์ titanic.csv และเลือก Copy path จะได้ที่อยู่ไฟล์มา</figcaption></figure><p>และทำการอ่านไฟล์เข้ามาเพื่อนำ Data มาเรียกใช้ ProfileReport Function</p><pre>df = pd.read_csv(&#39;/titanic.csv&#39;, sep = &#39;,&#39;)</pre><p>และเรียกดู data ใน titanic</p><pre>df.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GDroGR40MzTbt3SadaO5TQ.jpeg" /></figure><p>เรียกใช้ ProfileReport Function</p><pre>profile = ProfileReport(df, title=&quot;Pandas Profiling Report&quot;)<br>profile</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6P-OEOJdEboTf2RR0r3uvA.jpeg" /></figure><p>จากภาพข้างบนจะเห็นได้ว่ามีค่า missing values หรือข้อมูลที่หายไปถึง 866 cell เลยทีเดียว</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FMR4tPinuOsfpExM_lixlA.jpeg" /></figure><p>เรามาดูค่า missing values ของแต่ละ Column กันพิมคำสั่งตามด้านล่างเลย</p><pre>print(df.isnull().sum())</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BakGrmO5YnYIAlUkz90pPQ.jpeg" /></figure><p>ว้าวววจากภาพด้านบน column Age และ Cabin มีค่า missing values มากที่สุดซึ่งใน Column Age จะมีค่าtypeเป็นตัวเลขแต่ Column Cabin จะมีค่าเป็น String อ้างอิงได้จากข้อมูลที่เราเรียกดูด้วยคำสั่ง df.head()</p><p>หลังจากเราทำการวิเคราะห์ข้อมูลกันเสร็จเรียบร้อยแล้ว เรามาเริ่มทำกันที่เทคนิคที่ 1 กันเลย!!</p><h3>Imputation</h3><p>เป็นเทคนิคที่ใช้การแทนค่าที่หายไปหรือค่า missing values ด้วยค่าใดค่าหนึ่ง เช่น ค่าเฉลี่ย, ค่ามัธยฐาน หรือ การแทนค่า 0 ก็ได้เช่นกัน</p><h4>การแทนค่า missing values ด้วยค่าเฉลี่ยของอายุ (Age) เนื่องจาก Column Age มีค่า missing values มากที่สุดและมีค่าtypeเป็นตัวเลข</h4><pre>new_df = df.copy() #เราจะไม่ใช้ชุดข้อมูลเดิมตรงๆแต่เราจะทำการ copy ชุดข้อมูลเดิมมาใช้เป็นชุดข้อมูลใหม่ <br>new_df[&#39;Age&#39;].fillna(df[&#39;Age&#39;].mean(), inplace = True)</pre><p>มาดูผลลัพธ์กัน!!</p><pre>print(new_df.isnull().sum())</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vTPJWkZX9vo7q8NjRFHuUA.jpeg" /></figure><p>จะเห็นได้เลยว่าค่า missing values ของ Column Age มีค่าเป็น 0 แล้วว!! เนื่องจากเราแทนค่า missing values ด้วยค่าเฉลี่ยของตัวมันเองแล้วนั่งเอง</p><p>แต่!การแทนค่าด้วยค่าเฉลี่ยก็ใช่ว่าเราจะได้ข้อมูลตรงตามที่เราต้องการเสมอไปในบางทีเราอาจะทำการลบ column หรือ row แทนโดยกำหนดค่า Threshold หาก column หรือ row ไหนมีค่าร้อยละของค่า missing values มากกว่า 50% column และ row นั้นก็จะถูกลบไป</p><h4>การลบ column ที่มีค่าร้อยละของค่า missing values มากกว่า 50%</h4><pre>df.isnull().mean()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l0lwDjh_hL-f8BaoWX8W6g.jpeg" /></figure><p>จากภาพด้านบนค่า missing values ของ column Cabin มีมากถึง 0.771044*100 = 77.1044 % <br>ต่อมาเราจะทำการลบ column Cabin ที่มีค่าร้อยละของค่า missing values เกิน 50%</p><pre>threshold = 0.5<br>new_df = df[df.columns[df.isnull().mean() &lt; threshold]]<br>new_df.isnull().mean()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K_aqXQRcoojMkAFIdge_mw.jpeg" /></figure><p>จากภาพด้านบนจะเห็นได้ว่า column Cabin ถูกลบไปแล้ว!</p><h4>การลบ row ที่มีค่าร้อยละของค่า missing values มากกว่า 50%</h4><pre>print(df.shape)</pre><pre>new_df = df.loc[df.isnull().mean(axis=1) &lt; threshold]</pre><pre>print(new_df.shape)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/985/1*CNEg6mZxDA-G8qk4oeHgAg.jpeg" /></figure><p><strong>(891, 12)<br></strong>891 : <strong>row<br></strong>12 : <strong>column</strong></p><p>Row ไม่ได้ถูกลบไปเลยแม้แต่สัก row เพราะบางทีอาจจะไม่มีค่า missing values เลยทั้ง row เพียงแต่ใน row นั้นมีอยู่แค่บาง cell เท่านั้น</p><h4>การแทนค่า missing values ด้วยค่ามัธยฐาน</h4><pre>print(df.median())</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1014/1*iHe3hLIsnP1-gMou6T7sSQ.jpeg" /><figcaption>จะโชว์ขึ้นมาเฉพาะ Column ที่มี tpye เป็นตัวเลขเท่านั้น</figcaption></figure><pre>new_df = df.fillna(df.median())<br>print(new_df.isnull().sum())</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UrKsNkfE_uCxnpw8ZP5f4g.jpeg" /></figure><h4>การแทนค่า missing values ด้วยการแทนค่า 0</h4><pre>new_df = df.fillna(0)<br>print(new_df.isnull().sum())</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j0eXflfKxNuuEMGSNcsduA.jpeg" /></figure><p>column ทุก column มีค่าเป็น 0 ซึ่งนั่นไม่ใช่สิ่งที่เราต้องการเพราะบาง column มีค่าเป็น String ไม่ใช่ตัวเลขวิธีนี้จึงเหมาะสำหรับชุดข้อมูลที่มี column ทั้งหมดเป็น tpye ตัวเลข</p><pre>new_df.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KJQLwhsAHqWNEcaDdDAYjw.jpeg" /></figure><p>มาถึงที่วิธีสุดท้ายของเทคนิคแรกคือการลบทิ้งทั้ง row หากพบว่า cell ใด cell หนึ่งมีค่า Missing value ก็จะทำการลบหมดเลยทั้ง row</p><pre>print(df.shape)<br>new_df = df.dropna(how=&#39;any&#39;)<br>print(new_df.shape)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iS97nUPEb0xN_dP6z_NAEA.jpeg" /></figure><p>โอ๊ะโอ่.. ข้อมูลถูกลบไปถึง 708 row เลยทีเดียว นี่อาจจะไม่ใช่วิธีที่ดีหากมีข้อมูลถูกลบไปเป็นจำนวนมากเช่นนี้</p><h3>Handling Outliers</h3><p>มาต่อกันที่เทคนิคที่ 2 คือการ Handling Outliers เป็นวิธีที่จัดการกับค่าที่มีค่าออกมาโดดๆหรือข้อมูลที่มีค่าสูงหรือค่าต่ำกว่าข้อมูลส่วนใหญ่โดยค่านั้นเรียกว่า Outlier</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/1*oTVbNRJJUoEbv6A4NGvcnA.png" /></figure><p>เรามา import library ที่เราต้องใช้กันก่อน</p><pre>import seaborn as sns<br>from matplotlib import pyplot as plt</pre><p>ก่อนอื่นเราจะทำการแสดงข้อมูลแบบ Data Visualization เพื่อดูการกระจายข้อมูล</p><pre>fig = plt.figure(figsize=(12,8))<br>sns.boxplot(x=df[&#39;Age&#39;], color=&#39;palegreen&#39;)<br>plt.xlabel(&#39;Age Featured&#39;, fontsize=14)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*by9yoYRAs-NOWX1X33KhzQ.jpeg" /></figure><pre>df[&#39;Age&#39;].describe()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Fc4XP_tyYpOOknrO7SOmxA.jpeg" /></figure><p>ข้อมูลมี Outlier ไปฝั่งทางขวาค่อนข้างมากนั่นหมายถึงผู้คนส่วนใหญ่ที่อยู่บนเรือลำนี้อายุอยู่ช่วงประมาณวัยรุ่นจนถึงวัยกลางคนเนื่องจากมีค่าเฉลี่ยอายุ 29.69 % แต่ก็มีผู้สูงอายุจำนวนไม่มากไม่น้อยขึ้นมาบนเรือลำนี้ด้วยเนื่องจากบุคคลที่อายุมากที่สุดคือ 80 ปีและจากภาพ boxplot ที่มี Outlier ไปฝั่งทางขวาค่อนข้างมาก</p><h3>Drop Outlier with Standard Deviation</h3><p>การลบแถวที่มี Outlier ด้วย Standard Deviation (ส่วนเบี่ยงเบนมาตรฐาน)</p><pre>print(df.shape)<br>factor = 3</pre><pre>upper_lim = df[&#39;Age&#39;].mean () + df[&#39;Age&#39;].std () * factor<br>lower_lim = df[&#39;Age&#39;].mean () - df[&#39;Age&#39;].std () * factor</pre><pre>drop_outlier1 = df[(df[&#39;Age&#39;] &lt; upper_lim) &amp; (df[&#39;Age&#39;] &gt; lower_lim)]<br>print(drop_outlier1.shape)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1018/1*GcyihAijVVTEVjoAQVy_Jw.jpeg" /></figure><p>หลังจากทำการลบแถวที่มี Outlier ด้วย Standard Deviation แล้วมาดู Data Visualization เพื่อดูการกระจายข้อมูลกันอีกที</p><pre>fig = plt.figure(figsize=(12,8))<br>sns.boxplot(x=drop_outlier1[&#39;Age&#39;], color=&#39;skyblue&#39;)<br>plt.xlabel(&#39;Age Featured&#39;, fontsize=14)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z6ItGv_FN6qjjvgfmaDF6w.jpeg" /></figure><pre>drop_outlier1[&#39;Age&#39;].describe()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1020/1*tnz6lkETwUG9twIs6scUsQ.jpeg" /></figure><p>จากภาพด้านบนจะเห็นได้ว่าค่าเฉลี่ยของอายุลดลงเพียงเล็กน้อยจาก 29.69% ลดลงมา 29.56% แต่บุคคลที่อายุมากที่สุดลดลงจาก 80 ปีเหลือเพียง 71 ปี</p><h3>Drop with Percentiles</h3><p>นอกจากนี้เราสามารถลบแถวที่พบ Outlier ใน Column Age ที่น้อยกว่าหรือเท่ากับ Quantile 0.5 และมากกว่าหรือเท่ากับ Quantile 0.95 ตามตัวอย่างด้านล่าง</p><pre>print(df.shape)</pre><pre>upper_lim = df[&#39;Age&#39;].quantile(.95)<br>lower_lim = df[&#39;Age&#39;].quantile(.05)</pre><pre>drop_outlier2 = df[(df[&#39;Age&#39;] &lt; upper_lim) &amp; (df[&#39;Age&#39;] &gt; lower_lim)]</pre><pre>print(drop_outlier2.shape)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1Dwc30sdF_9-_wYq2u32Nw.jpeg" /></figure><p>มาดู Data Visualization เพื่อดูการกระจายข้อมูลกันอีกสักรอบ</p><pre>fig = plt.figure(figsize=(12,8))<br>sns.boxplot(x=drop_outlier2[&#39;Age&#39;], color=&#39;salmon&#39;)<br>plt.xlabel(&#39;Age Featured&#39;, fontsize=14)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Pbsi3mPJtkk-Fo-gIa_e0A.jpeg" /></figure><pre>drop_outlier2[&#39;Age&#39;].describe()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/941/1*u8alErgZJ__6DB8wy6xXuw.jpeg" /></figure><p>จากภาพจะเห็นได้ว่าวิธีนี้แทบจะไม่พบ Outlier กันเลยทีเดียวและค่าเฉลี่ยก็ไม่ได้แตกต่างจากวิธีก่อนหน้าเท่าไรนัก บุคคลที่อายุมากที่สุดกลับลดลงเหลือเพียง 55 ปีจาก 71 ปี</p><h3>Binning</h3><p>คือการจัดและแบ่งหมวดหมู่ของข้อมูลให้อยู่ในช่วงที่เรากำหนด เช่น การจัดและแบ่งอายุคนตามช่วงวัย เป็นยังไงมาดูกัน</p><p>การแบ่งอายุคนตามช่วงวัย <strong>Childhood, teens, Mature, Elderly <br></strong>bin = [0, 12, 22, 60, 100]</p><pre>labels = [&#39;Childhood&#39;, &#39;teens&#39;, &#39;Mature&#39;, &#39;Elderly&#39;]<br>bins = [0., 12., 22., 60., 100.]</pre><pre>drop_outlier2[&#39;Age_cat&#39;] = pd.cut(drop_outlier2[&#39;Age&#39;], labels=labels, bins=bins, include_lowest=False)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KJDqfh_5XJTLC-A4a8i_eg.jpeg" /></figure><pre>drop_outlier2[[&#39;PassengerId&#39;,&#39;Name&#39;,&#39;Age&#39;,&#39;Sex&#39;,&#39;Age_cat&#39;]].sample(n=5).head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/964/1*j96hd3ES12xiw4tiGzrw-g.png" /></figure><p>ใน column สุดท้าย Age_cat เป็นการแบ่งหมวดหมู่ช่วงอายุของคนที่ขึ้นเรือลำนี้ตัวตัวอย่างดังภาพด้านบน</p><h3>Log Transform</h3><p>คือเทคนิคที่ใช้ log ทางคณิตเข้ามาช่วยเพื่อการกระจายของข้อมูลให้เป็น Normal Distribution และไม่ให้ข้อมูลมีค่าโดดมากเกินไป</p><pre>drop_outlier2[&#39;log&#39;] = (drop_outlier2[&#39;Age&#39;]).transform(np.log)<br>drop_outlier2.sample(n=5).head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5KuOUb9UXcNXmlbMpjAnxA.png" /></figure><h3>One-hot Encoding</h3><p>เทคนิคสุดท้ายโดยส่วนตัวแล้วเจ้าของบทความคิดว่าวิธีการจะคล้ายๆกับ Binning เนื่องจากมีการจัดและแบ่งหมวดหมู่เหมือนกันเพียงแต่ One-hot Encoding จะมีการแปลงข้อมูลเป็นรหัสหรือตัวเลขแทน เช่น คนอายุ 30 จะอยู่ใน column Mature และใน Column Mature จะเป็นเลข 1 ส่วน column อื่นๆจะเป็นเลข 0 โดยวิธีการนี้เราจะใช้ function <strong>get_dummies() </strong>เป็น Library ของ Pandas เข้ามาช่วย</p><pre>encoded_columns = pd.get_dummies(drop_outlier2[&#39;Age_cat&#39;])<br>drop_outlier2 = drop_outlier2.join(encoded_columns)</pre><pre>drop_outlier2.sample(n=5).head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sSP5iqsTLqKZ8OYG-6TAYg.png" /></figure><h3>สรุป</h3><p>สำหรับตัวเจ้าของบทความคิดว่าเทคนิคที่เหมาะสมที่สุดในการทำ Feature Engineering ของข้อมูลชุดนี้คือ Binning และ One-hot Encoding เนื่องจากค่า Missing value ของข้อมูลชุดนี้คือ Age (อายุ) ฉะนั้นการจัดหมวดหมู่ของอายุน่าจะเหมาะสมที่สุด</p><p>หากบทความนี้มีข้อผิดพลาดประการใด เจ้าของบทความขออภัยไว้ ณ ที่นี้ด้วยแล้วพบกัยใหม่นะคะ สวัสดีค้าาาา</p><h3>reference</h3><ul><li><a href="https://blog.pjjop.org/feature-engineering-for-ai-and-machine-learning/">Feature Engineering for AI and Machine Learning (การทำ Feature Engineering ด้วย Pandas)</a></li><li><a href="https://github.com/pandas-profiling/pandas-profiling">GitHub - pandas-profiling/pandas-profiling: Create HTML profiling reports from pandas DataFrame objects</a></li></ul><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FpLxgt20kKWU%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DpLxgt20kKWU&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FpLxgt20kKWU%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/582287ffabcf6449cab025ce4acfb9ae/href">https://medium.com/media/582287ffabcf6449cab025ce4acfb9ae/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e243b7ef804d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Image Classification (4 kinds of fruits) with CNN by Google Colab (Python language)]]></title>
            <link>https://suthasom-t.medium.com/image-classification-4-kinds-of-fruits-with-cnn-by-google-colab-python-language-240534aebeda?source=rss-e010574c8d5e------2</link>
            <guid isPermaLink="false">https://medium.com/p/240534aebeda</guid>
            <category><![CDATA[cnn]]></category>
            <category><![CDATA[image-classification]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Tiwarin Suthasom]]></dc:creator>
            <pubDate>Mon, 10 Aug 2020 18:57:25 GMT</pubDate>
            <atom:updated>2020-08-10T18:57:25.980Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*PMCnXVEDj8Ojo-RE" /><figcaption>Photo by <a href="https://unsplash.com/@joannakosinska?utm_source=medium&amp;utm_medium=referral">Joanna Kosinska</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Convolutional Neural Network (CNN) คืออะไร ?</h3><p>คือ Neural Network แบบหนึ่งที่มักถูกนำมาใช้ในงาน Computer Vision หรือ วิเคราะห์รูปภาพ เช่น Image Classification (การจำแนกรูปภาพ)ซึ่งรับ Dataset ผ่าน Input Node หรือข้อมูลที่มีลักษณะเป็นลำดับ (Sequence) ซึ่งจะต้องถูกประมวลผลตามลำดับเพื่อจะทำนายได้ถูกต้อง</p><h3>มาเริ่มกันเลย!!</h3><p>ต้องขอบอกไว้ก่อนว่าในบทความนี้เราจะเขียนโค้ดกันบน Google Colab ซึ่งเป็นของ Google และเป็น Jupyter Notebook บน Cloud เช่นกัน ยังสามารถทำงานร่วมกับ Google Drive ได้อีกด้วย</p><h3>1. Data Preparation</h3><p>เราจะทำการรวบรวมรูปภาพผลไม้ 4 ชนิด ชนิดละ 30 รูปมาเก็บไว้ในไฟล์เพื่อเอามาTrainและทดสอบข้อมูล</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/628/1*qbecNOJb0wZ_rmtH5p7xiw.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pCqNt7frBJSj3B5SecbUvg.jpeg" /></figure><p>จากนั้นอัพโหลดไฟล์รูปทั้งหมดลง Google Drive</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aiEs2JtP_EoftrrVn-tOQQ.jpeg" /></figure><p>ต่อไปเปิด Google colab ขึ้นมาเพื่อทำการเชื่อมต่อ Google Drive</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/422/1*XtKkOFHu1iNQSapEbJ4POg.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RqNHnDYIZSFWPHRBdD0Igw.jpeg" /></figure><p>หลังจากกด CONNECT TO GOOGLE DRIVE ก็จะสามารถเชื่อมต่อ Google Drive ได้เลย</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/389/1*DnmbYYrszJt0q_reLaSNEg.jpeg" /></figure><p>เท่านี้เราก็สามารถดึงข้อมูลจาก Google Drive มาใช้ได้แล้ว</p><h4>เรามาเริ่มเขียนโค้ดกัน!!</h4><p>พิมคำสั่ง !pip install tf-nightly ใน cell แรก</p><pre>!pip install tf-nightly</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*plkxPx3julDY4hi-FdFjkg.jpeg" /></figure><p>ต่อมา import TensorFlow และ libraries ต่างๆที่เกี่ยวข้อง</p><pre>import matplotlib.pyplot as plt<br>import numpy as np<br>import os<br>import PIL<br>import tensorflow as tf<br>from tensorflow import keras<br>from tensorflow.keras import layers<br>from tensorflow.keras.models import Sequential<br>from IPython.display import Image</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/517/1*8ZbBOKRZiXAGUsbZNRzGTg.jpeg" /></figure><p>และก็มาถึงขั้นตอนการเตรียมข้อมูลจริงๆสักทีพิมคำสั่งตามได้เลย!</p><pre>import pathlib<br>path = &quot;drive/My Drive/Colab Notebooks/CNN_fruit&quot; #ที่อยู่ของข้อมูลที่เราเชื่อม ไว้กับ google Drive<br>data_dir = pathlib.Path(path)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/913/1*4QZVkXQtgS1W_KrzeLq__A.jpeg" /></figure><p>เรามาเช็คจำนวนรูปภาพทั้งหมดในไฟล์ที่เราจะทำการ Train กัน</p><pre>image_count = len(list(data_dir.glob(&#39;*/*.jpg&#39;)))<br>print(image_count)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/536/1*j2rShjsH69htlLLDYI3BMg.jpeg" /></figure><p>เมื่อพิมคำสั่งแล้วจะเห็นว่ามีรูปภาพที่จะทำการ Train อยู่ทั้งหมด 120 รูป</p><p>และเราจะมาเรียกดูตัวอย่างของรูปภาพของส้มที่เราจะ Train</p><pre>Orange = list(data_dir.glob(&#39;Orange/*&#39;)) <br>PIL.Image.open(str(Orange[1]))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/756/1*AvMgp4msJL4yYqibOm71Fw.jpeg" /></figure><p>ต่อไปเรามากำหนดขนาดของข้อมูลหรือ Dataset ของเรากัน</p><pre>batch_size = 32<br>img_height = 180<br>img_width = 180</pre><p><strong>Batch_size : </strong>กำหนดขนาดการอ่านข้อมูลแต่ละรอบ</p><p><strong>img_height : </strong>กำหนดความสูงของรูปภาพ</p><p><strong>img_width : </strong>กำหนดความกว้างของรูปภาพ</p><p>ถัดมาเรามาทำการแบ่งรูปภาพทั้งหมดโดยจะทำการแบ่งเป็นการ Train 80% และ validation 20%</p><pre>train_ds = tf.keras.preprocessing.image_dataset_from_directory(<br>data_dir,<br>validation_split=0.2,<br>subset=&quot;training&quot;,<br>seed=123,<br>image_size=(img_height, img_width),<br>batch_size=batch_size)</pre><pre>val_ds = tf.keras.preprocessing.image_dataset_from_directory(<br>data_dir,<br>validation_split=0.2,<br>subset=&quot;validation&quot;,<br>seed=123,<br>image_size=(img_height, img_width),<br>batch_size=batch_size)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aVKbmQvSsksC-wEvDkBFoQ.jpeg" /></figure><p>มาดูชื่อแต่ละ Class ที่เราจะทำการ Train</p><pre>class_names = train_ds.class_names<br>print(class_names)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/910/1*EPKZKtmO7VudPIhK0Wsuqw.jpeg" /></figure><p>จะเห็นว่าเรามีClassอยู่ทั้งหมด 4 Class ตามจำนวน dataset ของเราเลย คือ Apple, Banana, Blueberry, Orange</p><p>เรามาแสดงผลภาพ 9 ภาพแรกจากชุดข้อมูลการ Train</p><pre>plt.figure(figsize=(7, 7)) #คือขนาดของรูปภาพที่เราจะให้แสดง<br>for images, labels in train_ds.take(1):<br>for i in range(9):<br>ax = plt.subplot(3, 3, i + 1)<br>plt.imshow(images[i].numpy().astype(&quot;uint8&quot;))<br>plt.title(class_names[labels[i]])<br>plt.axis(&quot;off&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QiHCoog8X8P2O5v4FKz_qQ.jpeg" /></figure><p>เราจะมาทำการ normalization เพื่อแปลงค่าสีให้สอดคล้องกับการทำ CNN</p><pre>normalization_layer =<br>layers.experimental.preprocessing.Rescaling(1./255)</pre><pre>normalized_ds = train_ds.map(lambda x, y: (normalization_layer(x), y))<br>image_batch, labels_batch = next(iter(normalized_ds))<br>first_image = image_batch[0]<br>print(np.min(first_image), np.max(first_image))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/976/1*arQAz_asz2pqDlJWJHfFJg.jpeg" /></figure><h3>2. Define Model</h3><pre>num_classes = 4</pre><pre>model = Sequential([<br>layers.experimental.preprocessing.Rescaling(1./255, input_shape=(img_height, img_width, 3)),<br>layers.Conv2D(16, 3, padding=&#39;same&#39;, activation=&#39;relu&#39;),<br>layers.MaxPooling2D(),<br>layers.Conv2D(32, 3, padding=&#39;same&#39;, activation=&#39;relu&#39;),<br>layers.MaxPooling2D(),<br>layers.Conv2D(64, 3, padding=&#39;same&#39;, activation=&#39;relu&#39;),<br>layers.MaxPooling2D(),<br>layers.Flatten(),<br>layers.Dense(128, activation=&#39;relu&#39;),<br>layers.Dense(num_classes)])</pre><p>เรากำนด num_classes เป็น 4 เพราะมีคลาสทั้งหมด 4 คลาสคือ Apple, Banana, Blueberry, Orange นั่นเอง</p><h3>3. Compile the model</h3><p>ถัดมาเรามาแสดงค่าความแม่นยำหรือ accuracy ในระหว่างการ Train</p><pre>model.compile(optimizer=&#39;adam&#39;,<br>loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),metrics=[&#39;accuracy&#39;])</pre><pre>model.summary()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*usQwMJAm2Wh7-knlG65cew.jpeg" /></figure><h3>4. Train the model</h3><pre>epochs=10</pre><pre>history = model.fit(train_ds,<br>validation_data=val_ds,<br>epochs=epochs)</pre><p><strong>epochs :</strong> คือจำนวนในการ Train</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aXTyGjBeXV-fSHP_pjwY5Q.jpeg" /></figure><p>มาดูผลลัพธ์ของการ Train Dataset เป็นรูปแบบกราฟหรือ Visualize training results กันเลยยยยยยย</p><pre>acc = history.history[&#39;accuracy&#39;]<br>val_acc = history.history[&#39;val_accuracy&#39;]</pre><pre>loss = history.history[&#39;loss&#39;]<br>val_loss = history.history[&#39;val_loss&#39;]</pre><pre>epochs_range = range(epochs)</pre><pre>plt.figure(figsize=(8, 8))<br>plt.subplot(1, 2, 1)<br>plt.plot(epochs_range, acc, label=&#39;Training Accuracy&#39;)<br>plt.plot(epochs_range, val_acc, label=&#39;Validation Accuracy&#39;)<br>plt.legend(loc=&#39;lower right&#39;)<br>plt.title(&#39;Training and Validation Accuracy&#39;)<br>plt.subplot(1, 2, 2)<br>plt.plot(epochs_range, loss, label=&#39;Training Loss&#39;)<br>plt.plot(epochs_range, val_loss, label=&#39;Validation Loss&#39;)<br>plt.legend(loc=&#39;upper right&#39;)<br>plt.title(&#39;Training and Validation Loss&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cQl2YVjJ_2CWsC-30fcX5A.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vrIVYtzuWqYa13MF7wCOfA.jpeg" /></figure><h3>Prediction</h3><p>สุดท้ายเรามาทำการทดสอบหรือทำนายตัว Model ที่เรา Train มาด้วยข้อมูลที่เราเตรียมไว้</p><pre>path = &quot;/content/drive/My Drive/Colab Notebooks/CNN_fruit/Blueberry/55f8de30434e0b0a325c68e1f47c08a428a01cdb.jpg&quot;</pre><pre>img = keras.preprocessing.image.load_img(<br>path, target_size=(img_height, img_width))</pre><pre>img_array = keras.preprocessing.image.img_to_array(img)<br>img_array = tf.expand_dims(img_array, 0)</pre><pre>predictions = model.predict(img_array)</pre><pre>score = tf.nn.softmax(predictions[0])<br>display(Image(filename=path))</pre><pre>print(<br>&quot;This image most likely belongs to {} with a {:.2f} percent confidence.&quot;<br>.format(class_names[np.argmax(score)], 100 * np.max(score)))</pre><p><strong>path :</strong> คือรูปภาพหรือข้อมูลที่เราเตรียมไว้ทดสอบ</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5IR-vMK-ZmJ0hVW7hwlFog.jpeg" /></figure><p>ซึ่งตัว Model ของเราก็ทำนายออกมาว่าเจ้ารูปนี้มันคือ Blueberry 100% !!!!</p><p>และเราก็ขอจบบทความไว้เพียงเท่านี้ หากมีตรงไหนผิดพลาดประการใดก็ขออภัยด้วยนะคะ บ๊ายบ่ายยยค่าาทู๊กคนนน</p><h3>Reference</h3><ul><li><a href="https://colab.research.google.com/github/tensorflow/docs/blob/master/site/en/tutorials/images/classification.ipynb#scrollTo=4Dr0at41KcAU">Google Colaboratory</a></li><li><a href="https://blog.pjjop.org/deep-learning/">Introduction to Deep Learning (Machine Learning Pipeline)</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=240534aebeda" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>