<?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 Isada Sukprapa on Medium]]></title>
        <description><![CDATA[Stories by Isada Sukprapa on Medium]]></description>
        <link>https://medium.com/@sadanalog?source=rss-3f26000581b8------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Go9OFHOnCrFOXCykRWsirg.png</url>
            <title>Stories by Isada Sukprapa on Medium</title>
            <link>https://medium.com/@sadanalog?source=rss-3f26000581b8------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 07:21:43 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sadanalog/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[ทำ NER ภาษาไทย โดยใช้ Transformers Model จาก HuggingFace]]></title>
            <link>https://medium.com/super-ai-engineer/%E0%B8%97%E0%B8%B3-ner-%E0%B8%A0%E0%B8%B2%E0%B8%A9%E0%B8%B2%E0%B9%84%E0%B8%97%E0%B8%A2-%E0%B9%82%E0%B8%94%E0%B8%A2%E0%B9%83%E0%B8%8A%E0%B9%89-transformers-model-%E0%B8%88%E0%B8%B2%E0%B8%81-huggingface-130c7a201d5e?source=rss-3f26000581b8------2</link>
            <guid isPermaLink="false">https://medium.com/p/130c7a201d5e</guid>
            <category><![CDATA[machchimasuperai]]></category>
            <category><![CDATA[ner]]></category>
            <category><![CDATA[hugging-face]]></category>
            <category><![CDATA[transformers]]></category>
            <category><![CDATA[super-ai-engineer]]></category>
            <dc:creator><![CDATA[Isada Sukprapa]]></dc:creator>
            <pubDate>Sat, 27 Mar 2021 02:42:22 GMT</pubDate>
            <atom:updated>2022-02-08T07:38:33.777Z</atom:updated>
            <content:encoded><![CDATA[<h3>ทำ NER ภาษาไทย โดยใช้ Transformers Model จาก Hugging Face</h3><p><strong>Hi,</strong> วันนี้ผมจะมาสอนทำ supervised learning คือ NER tagging โดยใช้ Transformers model จาก Library ใน HuggingFace ว่าด้วยเหตุผลที่ผมต้องการเขียนเรื่องนี้ขึ้นมา เพราะว่าเห็นตอนนี้บทความใน medium ที่สอนการทำ NER tagging ที่เป็น ภาษาไทยล่าสุดยังคงใช้ตัว <a href="https://medium.com/@NagisaZ/thai-named-entity-recognition-with-bilstm-crf-using-word-character-embedding-keras-6834717d4fdb">CRF-BiLSTM</a> อยู่ อย่างที่ทุกคนทราบดีว่าตอนนี้เทรนด์ในการนำโมเดล Transformers มาประยุกต์ในงาน NLP ถือว่าเป็นเรื่องปกติมาก จึงคิดบทความนี้น่าจะเป็นประโยชน์ต่อผู้สนใจครับ</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*byYbqjgoZ0AQPciO.png" /><figcaption>NER tagging. <a href="https://meenavyas.wordpress.com/2018/06/10/spacy-named-entity-and-dependency-parsing-visualizers/">Source</a></figcaption></figure><h3>NER คืออะไร</h3><p>ผมเชื่อว่าหลายท่านที่อยู่ในแวดวง NLP คงรู้จัก NER กันดีครับ NER มากจาก Named Entity Recognition หรือการรู้จำคำเฉพาะ ตัวอย่าง NE ก็คืออย่างจำพวกชื่อ หน่วยงาน ชื่อคน วันที่ สถานที่ หรือชื่อกระทรวง เชื่อว่าหลายท่านคงมีคำถามตามมาว่า</p><blockquote>แล้วเราสกัด NEไปเพื่ออะไร ?</blockquote><p>จริงๆการกำกับ NE มีประโยชน์มากในแง่ของการวิเคราห์ข้อมูล ที่เป็นจำพวกบทความหรือ text ยกตัวอย่างในงานด้าน biomedical ก็มีรายงานใช้ NER เพื่อตรวจจับชื่อของ Gene หรือ DNA หรืออย่างในการทำ Information Retrieval การกำกับ NE สามารถช่วย search engine ให้มีประสิทธิภาพมากขึ้น ทั้งนี้ในงานที่ผมกำลังทำในส่วนของ Machine Translation การtag NE ก็เพื่อแก้ปัญหา rare-word เนื่องจาก machine ไม่สามารถแปลคำที่ไม่เคยถูกเทรนมาก่อนได้</p><p>ในเมื่อเกริ่นมาสักพักแล้วก็ได้เวลาลงมือครับ โดยบทความนี้จะใช้ <strong>Google Colab</strong> ในการ implement เพื่อให้สามารถทำตามได้ง่าย ทั้งนี้ Google Colab ยังมี GPU ด้วย สำคัญมากๆในการเทรน Transformers ครับ</p><p>โดยโค้ดส่วนใหญ่จะเอามากจาก <a href="https://colab.research.google.com/github/huggingface/notebooks/blob/master/examples/token_classification.ipynb">Token Classificaion Example</a> สามารถไปอ่านเพิ่มเติมได้ครับ</p><h3>0. Preparing Colab</h3><ol><li>เข้าไปที่ <a href="https://colab.research.google.com/">https://colab.research.google.com/</a> &gt; create a new notebook</li><li>ทำการเปลี่ยนไปใช้ GPU โดย Runtime &gt; Change Runtime Type &gt; เลือก GPU</li><li>(อันนี้เป็นทางเลือกนะครับ) ทำการ mount drive ด้วยเพื่อเราอยาก save model หรือ dataset ไว้</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/844/1*K_CnJKUnUWvborhkrZ3Wmg.png" /><figcaption>ภาพตัวอย่าง Change Runtime Type</figcaption></figure><h3>1. Loading Dataset</h3><p>ในส่วนของ dataset ที่เราจะใช้กันคือ <strong>LST20</strong> จากแลป LST ใน NECTEC โดยdatsetตัวนี้มี format เป็น CONLL-2003</p><ol><li>เข้าไปที่ website <a href="https://aiforthai.in.th/">AI for Thai</a></li><li>ทำการ login / sign-in</li><li>สามารถไปโหลด ได้ที่ Corpus</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xtxF3hDFIwuae4MuFpnTng.png" /><figcaption>lst20 บน AIforThai</figcaption></figure><p>4. เมื่อโหลดเสร็จแล้วให้โยนทั้งก้อนไปที่ colab ครับ</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/375/1*BVfMnchsETstv8rS8qDwxQ.png" /><figcaption>ให้คลิ๊กที่ปุ่มอัปโหลด</figcaption></figure><h3>2. Preprocessing</h3><ol><li>ทำการ unzip lst20 และ pip install สิ่งที่ต้องใช้</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bec6c196ce0cee80ff1ae5e90c56274a/href">https://medium.com/media/bec6c196ce0cee80ff1ae5e90c56274a/href</a></iframe><p>2. import library ทั้งหมด</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/368e2881fd7414fd3ff384e3d1b8c449/href">https://medium.com/media/368e2881fd7414fd3ff384e3d1b8c449/href</a></iframe><p>จากที่เรา import มา คือ เราจะใช้ AutoModel กับ AutoTokenizer โดยทั้งสองตัวนี้จะช่วย auto deploy model บน huggingface โดยเราไม่จำเป็นต้องไปหา class ของ โมเดลเอง สมมุติว่า ถ้าเราใช้ โมเดล pretrained เป็น RoBERTa ตัว AutoModel ก็จะไปหา class RoBERTa มา return ให้เอง โดยหลักการหลังจากนี้คือเราก็จะ fine-tune model ต่อ</p><p>3. ทำการ declare โมเดล และ โหลด lst20</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/37aa31a7e531522d3cf71cb16d222661/href">https://medium.com/media/37aa31a7e531522d3cf71cb16d222661/href</a></iframe><p>ก่อนจะไปข้อต่อไป อยากให้ลองเล่นกับ DatasetDict ก่อน</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/907/1*CifhYaLoCzGqljFI8m-F1g.png" /></figure><p>จะเห็นว่าเรามี train set = 63310, validate set = 5620, test set = 5250 ค่อนข้างเยอะทีเดียว ไหนลองมาดูข้างในแต่ล่ะอันหน่อยสิ</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/670/1*OHtfCPyTkUqlAhMh-aT63Q.png" /></figure><p>โอเค พวก ner_tags ก็จะเป็นตัวเลข ถ้าอยากรู้ว่ามันคืออะไร ให้เราปริ้น feature name ดู</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/754/1*IKbB7zgHAEgfPTGwI6HJgQ.png" /></figure><p>สรุปเรามี 31 NE tags ถ้าใครอยากรู้ว่าแต่ล่ะ tag มีความหมายอย่างไง ให้ไปตำต่อที่ <a href="https://arxiv.org/ftp/arxiv/papers/2008/2008.05055.pdf">LST20_guideline</a> ครับ</p><p>ก่อนไปต่อ กำหนด variable feature names สักนิด สำหรับเอาไปใช้ในการเทรน</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/73de5a2ea786d51836bdafe65a2c985b/href">https://medium.com/media/73de5a2ea786d51836bdafe65a2c985b/href</a></iframe><h3>3. Tokenizer</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/da74cd73b94990a0b8453ab29b6b87ff/href">https://medium.com/media/da74cd73b94990a0b8453ab29b6b87ff/href</a></iframe><p>ในการ fine-tuning เราจำเป็นต้องมี tokenizer ตัว tokenizer จะช่วยในการตัด sequence ตั้งแต่ระดับวลี ไปถึงระดับตัวอักษร ขึ้นกับว่า pretrained ตัวนี้เทรนมาแบบไหน จากเท่าที่ดู เหมือนว่า “Geotrend/bert-base-th-cased” จะถูกเทรนมาแบบ multi-language ทำให้ tokenizer อาจมีระดับย่อยถึง 1 character งั้นมาลองดูกัน</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7RM17OTXs27ChgmWuFw3Nw.png" /></figure><p>อันนี้ลองเปรียบเทียบ input ids ของสองประโยค ประโยคล่างมีการตัดคำ ส่วนประโยคบนไม่ได้ตัด (id 11, 12 หมายถึงเริ่มต้นและจบของประโยค) ถึงแม้ว่าจัดตัดคำต่างกัน แต่สองประโยชน์เป็นประโยคเดียวกัน ทว่ามี input ids ไม่เหมือนกัน ไหนเราลองดูสิความหมายมันต่างกันอย่างไร</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3X8iXjqbFkqdCnNEJAZ0KA.png" /></figure><p>เครื่องหมาย ## หมายถึง <a href="https://huggingface.co/transformers/tokenizer_summary.html">subword</a> การที่ [‘ผ’ , ‘##ม’] หมายความว่า ‘ผ’ กับ ‘ม’ ควรจะติดกันเป็นคำเดียวกัน</p><h3>4. Aligning Labels</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1002/1*PjpGLogwUFgT1lOw1vpFXQ.png" /></figure><p>ตอนนี้ text ที่ถูก tokenized ด้วย Tokenizer มี lengthไม่เท่ากับ length ของ NE tags หมายความว่า ตัวอย่าง ประโยค ก. ว่าด้วย “นายกคือประยุทธ์” ซึ่งมีเฉลยแท็กคือ [11, 0, 0, 8, 12] (11,12 = Begin, End ของ text) เมื่อ Tokenizer ตัดประโยค ก. แล้ว จะได้ [‘นา’, ‘##ยก’, ‘คือ’, ‘ประ’, ‘##ยุทธ์’] ดังนั้นเราต้อง align เฉลยแท๊กใหม่ ก็คือ [11, 0, 0, 0, 8, 8, 12] เป็นต้น</p><p>เราเลยจำเป็นต้อง align label ใหม่</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-GFXHMD9CJvzU16elFyI8A.png" /></figure><p>อันนี้คือ simple version ของการ align labels แต่จะเห็นได้ว่า ตอนนี้ length ของ label และ tokenized_input มีขนาดเท่ากันแล้ว เราสามารถใช้ประโยชน์จาก word_ids() ได้โดยเอาไป map กับ label ที่ควรจะเป็น</p><p>โอเคมาเขียน function สำหรับ pre-process กัน</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/026be4ad73043c15ee09ca5967c2804b/href">https://medium.com/media/026be4ad73043c15ee09ca5967c2804b/href</a></iframe><p>หลักการทำงานของ function นี้คือ align label โดยทำให้ input ที่ถูก tokenize มี ner tags เหมือนก่อนที่จะถูก tokenize และมี label เริ่มต้นกับสุดท้ายให้เป็น -100 (ไม่ถูกนำมาคิด loss)</p><p>ต่อไปนำมา map กับ dataset</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1ea1d6e36afa4114bf3dc029a7dde78e/href">https://medium.com/media/1ea1d6e36afa4114bf3dc029a7dde78e/href</a></iframe><h3>5. Fine-tuning Model</h3><p>ก่อนอื่นเราต้อง load model มาก่อน โดยโมเดลที่เราใช้คือ “Geotrend/bert-base-th-cased” หรือ BERT model นั้นเอง ความง่ายของ AutoModel ของ huggingface คือเราสามารถ deploy ได้เลยไม่ยุ่งยาก</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/98a72dec4770da50fe2fd0e9cf48f30a/href">https://medium.com/media/98a72dec4770da50fe2fd0e9cf48f30a/href</a></iframe><p>ของที่เราต้องใช้ ในการ fine-tuning model หลักๆเราต้องมี 3 functions ได้แก่ <strong>TrainingArguments, DataCollator, ComputationMetrics</strong></p><p>เริ่มจาก <strong>TrainingArguments</strong> ก่อน TrainingArguments คือ การกำหนด parameters สำหรับ fine-tuning model เราสามารถกำหนด TrainingArguments ได้ดังต่อไปนี้</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/31f240eecc4940e5bf5c2b9b61a32bc2/href">https://medium.com/media/31f240eecc4940e5bf5c2b9b61a32bc2/href</a></iframe><p>TrainingArguments สำคัญมากครับ โมเดลเราจะ converge เร็ว converge ช้าขึ้นอยู่ parameters และ มันสามารถปรับเพิ่มอะไรได้อีกเยอะ แน่ะนำให้ไปตำ<a href="https://huggingface.co/transformers/_modules/transformers/training_args.html">ต่อที่นี้ครับ</a></p><p><strong>Data Collator</strong></p><p>Data Collator เป็น function ที่ทำให้ covert dataset จาก list ให้เป็น batch tensors ครับ สามารถเรียกใช้ได้ง่ายๆต่อไปนี้</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/66e8ce39888e7ab1e0091ed10b621455/href">https://medium.com/media/66e8ce39888e7ab1e0091ed10b621455/href</a></iframe><p><strong>Computation Metrics</strong></p><p>อันนี้เอามาวัดผลของการ fine-tuning เราใช้ seqeval ซึ่งเป็น libary หนึ่งที่นิยมนำมาใช้กับการวัดผล งานพวก sequence tagging ครับ</p><p>ก่อนอื่นทำการโหลด seqeval ก่อน</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7e6f8c8a42b2e5c2ba3022dbe4c5aa5a/href">https://medium.com/media/7e6f8c8a42b2e5c2ba3022dbe4c5aa5a/href</a></iframe><p>เราลองมาทดลอง function compute จาก seqeval กันก่อน (เนื่องจาก format ทำให้ seqeval จะแจ้งเตือน ถ้าเราใช้ ‘_’ แทน ‘-’ เพราะงั้นเลยต้อง replace ขจัดความรกหูรกตา)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1010/1*narn68Xsv-qhovnvKxI9cw.png" /></figure><p>ทีนี้เราต้องมาเขียน function compute_metics เอง โดยรับ predictions มาจาก model เพื่อทำการ evaluate</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b2f30661c6a4142056edb7207f6a90c9/href">https://medium.com/media/b2f30661c6a4142056edb7207f6a90c9/href</a></iframe><p>หลังจากเรามี functions ทั้งหมดแล้วก็พร้อมที่จะ fine-tuning model แล้วครับ โดย function ที่เราจะใช้คือ Trainerครับ</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b1b696232bd87a8200fae06a803c85e4/href">https://medium.com/media/b1b696232bd87a8200fae06a803c85e4/href</a></iframe><p>เราสามารถเริ่มเทรนได้ด้วยการ call trainer.train() ในการ train ค่อนข้างใช้เวลานานมากๆ 1 epoch ประมาณ 30–40 นาทีครับ</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e7e64a5afe663483016e92b30651004d/href">https://medium.com/media/e7e64a5afe663483016e92b30651004d/href</a></iframe><p>โดยทุกๆ epoch เราจะได้ผลประมาณนี้</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-nY_ghUtCAshMq--2ys_-Q.png" /></figure><p>เราสามารถ evaluate model ได้ด้วยคำสั่ง</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/63b3c94e51e9571c6a475e10232dcd31/href">https://medium.com/media/63b3c94e51e9571c6a475e10232dcd31/href</a></iframe><p>ตัวอย่างผลลัพธ์</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/395/1*WUnDWcfRwhBLtmkOKMZcSw.png" /></figure><p>นอกนั้น เราสามารถทดลอง ให้ model ทำการ predict testset จากการ modify ฟังชั่น compute_mertics ได้เหมือนกัน</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3bcbad6969fd212e737db779e81c0c4f/href">https://medium.com/media/3bcbad6969fd212e737db779e81c0c4f/href</a></iframe><p>โดยผลลัพธ์ก็จะออกมามี format เหมือนกับผล evaluate ครับ ทีนี้ในการเทรน Transformers ให้ออกมาเก่งจำเป็นต้อง train เยอะๆ epoch อย่างน้อยก็ต้องมี 20–30 epochs ถึงจะให้ผลดี ซึ้งใช้เวลาค่อนข้างนาน อยากให้ไปลองดูกัน</p><p>สุดท้ายนี้ถ้ารู้สึกว่าเทรนพอแล้ว หรืออยากเก็บไว้มาเทรนต่อวันอื่น ผมแน่ะนำให้ทำการ save pretrained สามารถอ่านต่อได้ <a href="https://huggingface.co/transformers/model_sharing.html">ตรงนี้ครับ</a></p><p>และนี้ก็คือทั้งหมดของบทความนี้ครับ สุดท้ายนี้ผมหวังว่าจะเป็นประโยชน์ไม่มากก็น้อย ถ้าบทความมีข้อผิดพลาดประการใด รบกวนช่วยคอมเม้นหรือไฮไลน์ด้วยนะครับ</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=130c7a201d5e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/super-ai-engineer/%E0%B8%97%E0%B8%B3-ner-%E0%B8%A0%E0%B8%B2%E0%B8%A9%E0%B8%B2%E0%B9%84%E0%B8%97%E0%B8%A2-%E0%B9%82%E0%B8%94%E0%B8%A2%E0%B9%83%E0%B8%8A%E0%B9%89-transformers-model-%E0%B8%88%E0%B8%B2%E0%B8%81-huggingface-130c7a201d5e">ทำ NER ภาษาไทย โดยใช้ Transformers Model จาก HuggingFace</a> was originally published in <a href="https://medium.com/super-ai-engineer">Super AI Engineer</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[เผยวิธี install CuDNN สำหรับใช้งาน CUDA บน Ubuntu 16.04]]></title>
            <link>https://medium.com/super-ai-engineer/%E0%B9%80%E0%B8%9C%E0%B8%A2%E0%B8%A7%E0%B8%B4%E0%B8%98%E0%B8%B5-install-cudnn-%E0%B8%AA%E0%B8%B3%E0%B8%AB%E0%B8%A3%E0%B8%B1%E0%B8%9A%E0%B9%83%E0%B8%8A%E0%B9%89%E0%B8%87%E0%B8%B2%E0%B8%99-cuda-%E0%B8%9A%E0%B8%99-ubuntu-16-04-42d4aa0194b?source=rss-3f26000581b8------2</link>
            <guid isPermaLink="false">https://medium.com/p/42d4aa0194b</guid>
            <category><![CDATA[machchimasuperai]]></category>
            <category><![CDATA[superai]]></category>
            <category><![CDATA[cudnn]]></category>
            <category><![CDATA[ubuntu]]></category>
            <category><![CDATA[cuda]]></category>
            <dc:creator><![CDATA[Isada Sukprapa]]></dc:creator>
            <pubDate>Sun, 24 Jan 2021 17:17:33 GMT</pubDate>
            <atom:updated>2021-09-23T05:08:06.316Z</atom:updated>
            <content:encoded><![CDATA[<h3>เผยวิธี install cuDNN สำหรับใช้งาน CUDA บน Ubuntu 16.04</h3><blockquote>สอนลง cuDNN บน Unbuntu 16.04 แบบ step-by-step สำหรับ VM บน Huawei Cloud</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zoSA8yyeiEWrcBahALnSLQ.jpeg" /><figcaption>Photo by <a href="https://pixabay.com/users/nanadua11-4908484/">nanadua11</a> on <a href="https://pixabay.com/">pixabay</a></figcaption></figure><p><strong>Hi,</strong> เนื่องจากที่โครงการ Super AI Engineer 2020 ได้มีการเปิดให้ผู้เข้าร่วมแข่งขันสามารถใช้งาน Huawei Cloud และผมเองก็ได้มีโอกาสเข้าไปเรียนรู้วิธีการใช้งาน รวมถึงรับหน้าที่ในการ set environment ของ VM จึงอยากที่จะมาเผยแพร่ความรู้ที่ได้รับมาเพื่อจะเป็นประโยชน์แก่ผู้อ่าน สำหรับทาง Huawei Cloud ก็มี VM จำพวก GPU Accelerator ที่ช่วยเพิ่มประสิทธิภาพสำหรับการเทรน Neural Network-based Models อย่างเช่นการ์ดจอ NVIDIA Tesla T4 หรือ NVIDIA Tesla V100 มาให้บริการ และสามารถเลือกให้ลง OS เป็น Ubuntu หรือ CentOS</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/882/1*imFIbkbETyXxWk65ACZ6lA.png" /></figure><p>หลังจากลองเล่นตัว VM ไปสักพัก ทีมพบว่าผมและพี่ๆในทีม ใช้เวลาส่วนใหญ่ในการหาวิธีลง cuDNN เพื่อให้สามารถใช้งาน CUDA ได้ นั้นจึงเป็นเหตุผลที่ผมเลือกหยิบบทความนี้มาเขียน เพราะ<strong>ผมมองว่าบทความนี้จะเป็นประโยชน์ต่อผู้เข้าร่วมโครงการในแง่ของการประหยัดเวลา หรือว่าจะเป็นแนวทางให้กับผู้ที่ต้องการที่จะ setup cuDNN บน Ubuntu version 16.04 หรือ version อื่นๆ ถือว่าเป็น Knowledge Sharing</strong></p><h3><strong>cuDNN คืออะไร</strong></h3><p>อย่างที่ทุกคนทราบกันดีกว่า library อย่าง Tensorflow หรือ PyTorch ล้วนใช้ประโยชน์จาก CUDA (Parallel Computing Platfrom จาก Nvidia) ในการทำงานทั้งสิ้น <strong>NVIDIA cuDNN </strong>เป็น library สำหรับตัวกลาง ในการแปลง Neural Network modules เพื่อไปรันบน CUDA และแปลงผลลัพธ์จากคำนวนของ CUDA กลับไป software นั้นเอง</p><h3><strong>วิธีการ Instrall cuDNN</strong></h3><h4><strong>1. หลังจาก SSH เข้า เ</strong>ครื่อง <strong>VM ที่ต้องการจะลงแล้ว ให้ทำการเช็ค CUDA version</strong></h4><ul><li>ตัวอย่างการ SSH</li></ul><pre>$ ssh username@ipv4</pre><p>ipv4 คือ IP ของเครื่อง VM</p><p>ถ้ายังไม่ได้ set username ให้ทำการ login ด้วย $ ssh root@ipv4 แล้วไปสร้าง username และ assign สิทธิ์ในการรัน sudo ดังต่อไปนี้</p><pre>$ useradd -m username<br>$ usermod -aG sudo username</pre><p>ในการใช้ Unix เราควรหลีกเลี่ยงการใช้ root เพราะว่า 1. เมื่อ build file ผ่าน root file จะติด permission ทำให้ user ที่ต่ำกว่าไม่สามารถใช้งานไฟล์นั้นๆได้ 2. มันเคยมีเคสที่ว่า library มาที่โหลดเกิดมี bug ทำการลบไฟล์ต่างๆ ได้โดยไม่ต้องขอ permission เพราะงั้นเพื่อลด damage เหล่านี้เราจึงควรใช้ user ปกติแทน</p><p>จากนั้นทำการ login ผ่าน SSH โดยใช้ $ ssh username@ipv4</p><ul><li>command สำหรับเช็ค CUDA version</li></ul><pre>$ nvidia-smi</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/803/1*MBk1y2e7OE5yGIQIzpM5og.png" /><figcaption>ตัวอย่าง Nvidia-smi. <a href="https://kumarvinay.com/how-to-install-cuda-and-cudnn-on-ubuntu/">source</a></figcaption></figure><h4><strong>2. ถ้ารันได้แสดงว่าเครื่องนี้มีการติดตั้ง CUDA version มาแล้ว จากนั้น ให้ทำการเช็ค CUDA version</strong></h4><ul><li>จากรูป CUDA version คือ</li></ul><pre>CUDA version 10.1</pre><p><strong>หมายเหตุ</strong> กรณีถ้ารันแล้วไม่ขึ้นแสดงตามภาพข้างต้น ผู้อ่านหาต้องวิธีลง CUDA เอง สำหรับไกด์ไลน์คร่าวๆ คือ download NVIDIA CUDA Toolkit version ที่การ์ดจอ support มา install เองครับ ดูวิธีได้จาก <a href="https://developer.nvidia.com/cuda-10.1-download-archive-base">ลิงค์นี้</a> แต่ในกรณีนี้ทาง Huawei Cloud ได้ทำการลง CUDA มาให้พร้อมใช้งานแล้วครับ</p><h4>3. ต่อมาให้เอา CUDA version ไปเช็ค TensorFlow, cuDNN, Python, Compiler ที่ support</h4><ul><li>ไปเช็คได้ที่ <a href="https://www.tensorflow.org/install/source">https://www.tensorflow.org/install/source</a></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*75-LpP9Qdwojev7jw4bMIg.png" /><figcaption>ตัวอย่าง Version ที่ support</figcaption></figure><ul><li>จากในรูป CUDA 10.1 ต้องใช้ cuDNN 7.6 และรองรับ Python3.8, Tensorflow 2.3.0</li></ul><h4><strong>4. เมื่อรู้แล้วว่าเราต้อง Install cuDNN 7.6 เราก็ไป download ตัว Installer มา</strong></h4><ul><li>ตัว Installer แบ่งเป็น 3 ไฟล์คือ <strong>Code Samples and User Guide, Runtime Library และ Developer Library</strong> ให้โหลดเป็นไฟล์ (.deb)</li><li>สามารถดาว์โหลดได้จาก <a href="https://developer.nvidia.com/rdp/cudnn-archive">ลิงค์นี้</a></li><li>ถ้ายังไม่มี account ของ Nvidia ให้ทำการสมัครแล้วจึงสามารถดาว์โหลดได้</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/761/1*v0Ys5VyXveiA1r5aG5EpJQ.png" /><figcaption>ตัวอย่างเวอร์ชั่นที่ต้องดาว์โหลด</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/729/1*PbAY5LaJZFN-PSE0A7LI4w.png" /><figcaption>ตัวอย่างไฟล์ที่ต้องดาว์โหลด</figcaption></figure><ul><li>ถ้าโหลดมาเข้าเครื่อง local แล้วต้องการโยนไฟล์เข้าไปเครื่อง server ให้ใช้คำสั่ง SCP ตามตัวอย่าง</li></ul><pre>$ scp “path/to/target_file.txt” remote_username@10.10.0.2:/remote/directory</pre><h4><strong>5. ทำการ Install cuDNN ทั้งสามไฟล์</strong></h4><ul><li>เนื่องจากเราโหลดมาเป็นไฟล์ Debian ให้ทำการ install โดย<strong>ใช้คำสั่งต่อไปนี้ ตามลำดับ</strong></li><li>5.1 ลงตัว runtime library (กด tap 2 ที เพื่อ auto type directory)</li></ul><pre>$ sudo dpkg -i libcudnn7_7.6.5.32-1+cudax.x_amd64.deb</pre><ul><li>5.2 ลงตัว developer library</li></ul><pre>$ sudo dpkg -i libcudnn7-dev_7.6.5.32-1+cudax.x_amd64.deb</pre><ul><li>5.3 ลงตัว code samples และ cuDNN library documentation</li></ul><pre>$ sudo dpkg -i libcudnn7-samples_7.6.5.32-1+cudax.x_amd64.deb</pre><h4><strong>6. ทำการ verify ว่าเราสามารถใช้งาน cuDNN หลังจากที่เรา install เรียบร้อยแล้ว</strong></h4><ul><li>ก๊อปปี้ cuDNN samples ไป path home โดยสามารถใช้คำสั่งตามนี้ได้เลยแต่ต้องแน่ใจว่าชื่อไฟล์ถูกต้อง</li></ul><pre>$ cp -r /usr/src/cudnn_samples_v7/ $HOME</pre><ul><li>cd ไปที่ cudnn_samples_v7/mnistCUDNN เสริมนิดนึงอันนี้ คือเราจะเทสรัน CUDA โดยใช้ MNIST dataset</li></ul><pre>$ cd  $HOME/cudnn_samples_v7/mnistCUDNN</pre><ul><li>Compile mnistCUDNN sample</li></ul><pre>$ make clean &amp;&amp; make</pre><ul><li>รัน mnistCUDNN sample.</li></ul><pre>$ ./mnistCUDNN</pre><ul><li>ถ้า cuDNN รันปกติเราจะได้รับ massage:</li></ul><pre>Test passed!</pre><p>เมื่อทำตามครบหมดนี้ ก็เท่ากับว่าเราสามารถใช้ cuDNN และ CUDA ได้ตามปกติครับ หวังว่าบทความนี้จะเป็นประโยชน์ไม่มากก็น้อยครับ</p><h4>Reference</h4><ul><li><a href="https://gist.github.com/matheustguimaraes/43e0b65aa534db4df2918f835b9b361d">https://gist.github.com/matheustguimaraes/43e0b65aa534db4df2918f835b9b361d</a></li><li><a href="https://docs.nvidia.com/deeplearning/cudnn/install-guide/index.html?ncid=afm-chs-44270&amp;ranMID=44270&amp;ranEAID=a1LgFw09t88&amp;ranSiteID=a1LgFw09t88-IEZehiXBkZJe_l4Tpajw2A">https://docs.nvidia.com/deeplearning/cudnn/install-guide/index.html?ncid=afm-chs-44270&amp;ranMID=44270&amp;ranEAID=a1LgFw09t88&amp;ranSiteID=a1LgFw09t88-IEZehiXBkZJe_l4Tpajw2A</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=42d4aa0194b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/super-ai-engineer/%E0%B9%80%E0%B8%9C%E0%B8%A2%E0%B8%A7%E0%B8%B4%E0%B8%98%E0%B8%B5-install-cudnn-%E0%B8%AA%E0%B8%B3%E0%B8%AB%E0%B8%A3%E0%B8%B1%E0%B8%9A%E0%B9%83%E0%B8%8A%E0%B9%89%E0%B8%87%E0%B8%B2%E0%B8%99-cuda-%E0%B8%9A%E0%B8%99-ubuntu-16-04-42d4aa0194b">เผยวิธี install CuDNN สำหรับใช้งาน CUDA บน Ubuntu 16.04</a> was originally published in <a href="https://medium.com/super-ai-engineer">Super AI Engineer</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Practice of Fabric Defect Detection by Using CNN]]></title>
            <link>https://sadanalog.medium.com/a-practice-of-fabric-defect-detection-by-using-cnn-c3e7c2a1088d?source=rss-3f26000581b8------2</link>
            <guid isPermaLink="false">https://medium.com/p/c3e7c2a1088d</guid>
            <category><![CDATA[smart-factory]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[convolutional-network]]></category>
            <category><![CDATA[edge-ai]]></category>
            <category><![CDATA[defect-detection]]></category>
            <dc:creator><![CDATA[Isada Sukprapa]]></dc:creator>
            <pubDate>Thu, 14 May 2020 05:21:05 GMT</pubDate>
            <atom:updated>2024-01-11T03:55:11.571Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>We demonstrate Fabric Defect Detection using CNN to provide general knowledge about implementing CNN</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g7Cx0HJeSVwqtus03JqJVQ.jpeg" /><figcaption>Fig 1: The fabric photo by Engin Akyurt. <a href="https://pixabay.com/photos/towel-textile-fabric-cotton-color-1838210/">Source</a></figcaption></figure><h3>Introduction</h3><p>Recently there has been a rise in popularity for edge-based AI implementation, which is an implementation of AI outside of the main computing unit to lessen load requirements of the central server and help out in some smaller computation processes such as preprocessing or classification using pre-trained models. An example of edge-based AI implementation is defect detection using edge devices where the central server does not necessarily need to know what went wrong with each unit in real-time. Directly receiving image feed from the production line and looking for defects will take away a significant amount of traffic from the server, and thus edge implementation to detect defects will lessen this load. While AI is not considered a new technology nowadays, and neither do IoT devices, we will be attempting to implement a rudimental defect detection using CNN in this article.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*DBb8Wi9OxAgRTEoV" /><figcaption>Fig 2: Convolutional Neural Network (CNN). <a href="http://vision.stanford.edu/cs598_spring07/papers/Lecun98.pdf">Source</a></figcaption></figure><blockquote>In 1998, Yann LeCun, et al. published the Convolutional Neural Network (CNN) for the first time in the journal paper titled “<a href="https://doi.org/10.1109/5.726791">Gradient-Based Learning Applied to Document Recognition</a>.” Thenceforth, the CNN model has been considered as the most powerful deep neural network, which is mostly used for analyzing images.</blockquote><p>Presently, defect detection in manufacture is based on Deep Learning. For instance, <a href="https://ieeexplore.ieee.org/document/8666503">D. Hou et al., 2019</a> implemented laser chip defect detection using CNN based on GoogleNet with an accuracy of 97 percent. Additionally, <a href="https://ieeexplore.ieee.org/document/8939905">K. Lee et al., 2019</a> demonstrated the comparison among the three techniques: SVM, DNN, and CNN, resulting in CNN as the best performer with 95.1 percent accuracy.</p><p>Therefore, CNN is considered the best option for defect detection usage on our dataset, which will be a set of monotone images of fabric labeled as having defects and not having a defect.</p><h4>Dataset</h4><p>The dataset is provided by J. Silvestre-Blanes et al., 2019, in the paper “<a href="https://doi.org/10.2478/aut-2019-0035"><em>A Public Fabric Database for Defect Detection Methods and Results</em></a><em>.</em>” The dataset has 245 images with seven different fabrics. There are 140 non-defect images and 20 for each type of fabric. With different types of defects, there are 105 images. Images have a size of 4096×256 pixels.</p><p>A sample of the defect image</p><pre># Load picture<br>pic = project_path + “/dataset/Defect_images/0003_002_00.png”<br>im = imageio.imread(pic)<br>print(“picture shape: {}”.format(im.shape))<br>print(“picture matrix: \n {}”.format(im))<br># Set display size<br>plt.figure(figsize=(20,10))<br>plt.imshow(im, cmap=&quot;gray&quot;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/248/0*ZGAPjWinYhZlE8IU" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*aXHjabLcRZ5-IbeN" /></figure><p>In this practice, we would like to classify only the two classes, which are defect-free and defected, based on the CNN technique.</p><p><strong>Note that the </strong><strong>project_path is our project directory</strong></p><h3>Implementation</h3><p>In the upcoming steps, we will be elaborating on how to implement the fabric defect classification according to the CNN model.</p><h4>Prerequisite</h4><p>Let us define the libraries and tools that have been used.</p><p><strong>Dependency</strong></p><p>In this article, we will be using CNN to identify defects on clothing surfaces. Moreover, here are the dependencies:</p><pre>python &gt;= 3.6<br>tensorflow &gt;= 2.2.0<br>pandas &gt;= 1.0.3<br>glob &gt;= 0.7<br>imageio &gt;= 2.4.1<br>matplotlib &gt;= 3.2.1<br>sklearn &gt;= 0.22.2</pre><p><strong>Optional but recommended</strong></p><p>Google Colaboratory is a free tool that provides powerful resources such as a GPU, accelerating deep learning training processes. Besides, the module installing process is easy and similar to Jupyter Notebook, that is,</p><pre>!pip install &lt;package&gt;</pre><p>All libraries used in this article are provided in Google Colaboratory</p><h4>Model Training Procedure</h4><ol><li><strong>Loading External File</strong></li></ol><p>In the first step, we have defined the load_file function to read image files. The function will return a NumPy array of the image object.</p><pre>def load_file(file_path, label):<br>    # Include the project path<br>    file_path = project_path + file_path<br>    <br>    # Declare the folder name<br>    folder_name = file_path.split(&quot;/&quot;)[-1]<br>    <br>    # Declare output list<br>    out_list = []<br>    <br>    # Load every file .png format<br>    for image_path in glob.glob(file_path + &quot;/*.png&quot;):<br>        # Read image file<br>        image = imageio.imread(image_path)<br>        <br>        # Declare temporary dict dtype<br>        temp = {}<br>        <br>        # Set the file name<br>        temp[&quot;name&quot;] = image_path.split(&quot;/&quot;)[-1]<br>        <br>        # Set the file label, 0 for non defect. 1 for defect<br>        temp[&quot;label&quot;] = label</pre><pre>        # There are somes images are tensor dtype<br>        # Thus I fix by selecting only a tensor index zero<br>        try:   <br>            temp[&quot;data&quot;] = image[:,:,0].astype(&quot;int&quot;) <br>        except:<br>            # Normal case<br>            temp[&quot;data&quot;] = image.astype(&quot;int&quot;)<br>        <br>        # Append temp into output list<br>        out_list.append(temp)<br>    <br>    # Print process status by checking size of output list<br>    if len(out_list) == 0:<br>        print(&quot;loading files from folder: {} is   failed&quot;.format(folder_name))<br>    else:<br>        print(&quot;loading file from folder: {} is successful&quot;.format(folder_name))<br>    <br>    # Convert list into numpy array dtype<br>    return np.array(out_list)</pre><p>The next step is to load the .png file by calling the previous function:</p><pre># Define the path<br>defect_images_path = &quot;/dataset/Defect_images&quot;<br>non_defect_images_path1 = &quot;/dataset/NoDefect_images/2306881-210020u&quot;<br>non_defect_images_path2 = &quot;/dataset/NoDefect_images/2306894-210033u&quot;<br>non_defect_images_path3 = &quot;/dataset/NoDefect_images/2311517-195063u&quot;<br>non_defect_images_path4 = &quot;/dataset/NoDefect_images/2311694-1930c7u&quot;<br>non_defect_images_path5 = &quot;/dataset/NoDefect_images/2311694-2040n7u&quot;<br>non_defect_images_path6 = &quot;/dataset/NoDefect_images/2311980-185026u&quot;<br>non_defect_images_path7 = &quot;/dataset/NoDefect_images/2608691-202020u&quot;<br>mask_images_path = &quot;/dataset/Mask_images&quot;</pre><pre>defect_images = load_file(defect_images_path, 1)<br>non_defect_images1 = load_file(non_defect_images_path1, 0)<br>non_defect_images2 = load_file(non_defect_images_path2, 0)<br>non_defect_images3 = load_file(non_defect_images_path3, 0)<br>non_defect_images4 = load_file(non_defect_images_path4, 0)<br>non_defect_images5 = load_file(non_defect_images_path5, 0)<br>non_defect_images6 = load_file(non_defect_images_path6, 0)<br>non_defect_images7 = load_file(non_defect_images_path7, 0)<br>mask_images = load_file(mask_images_path, -1)</pre><pre># contribute the non defect dataset into one file<br>non_defect_images = np.concatenate((non_defect_images1, non_defect_images2))<br>non_defect_images = np.concatenate((non_defect_images, non_defect_images3))<br>non_defect_images = np.concatenate((non_defect_images, non_defect_images4))<br>non_defect_images = np.concatenate((non_defect_images, non_defect_images5))<br>non_defect_images = np.concatenate((non_defect_images, non_defect_images6))<br>non_defect_images = np.concatenate((non_defect_images, non_defect_images7))</pre><p>Here, the size of the dataset:</p><pre>print(“defect_images.shape: {}\nnon_defect_images.shape: {}\nmask_images.shape:{} \n”.format(defect_images.shape, non_defect_images.shape, mask_images.shape))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/252/0*pa8x3mDbmncAlfQY" /></figure><p>The dataset also includes defect mask images which are binary images showing a specific defect location in the dataset. Other classification methods could use this, but this will not be utilized in the article.</p><p><strong>2. Data preparation</strong></p><p>In the stage of training the model, it remaps the image dataset onto a graph</p><p>with each axis representing these aspects:</p><ul><li><strong>X </strong>is a vector that each row that consists of an image matrix.</li><li><strong>y </strong>is a matrix label where 0 be a defect-free image and 1 be a defect image.</li></ul><p>To balance the dataset, because the number of defect images can not be increased, thus, 105 defect-free images have been selected to equal the number of defect images.</p><pre># We random by shuffling the order of defect-free and defect images<br>np.random.shuffle(non_defect_images)<br>np.random.shuffle(defect_images)</pre><pre># The class size is selected by the min of length compared between <br># defect-free and defect images<br>class_size = defect_images.shape[0] if defect_images.shape[0] &lt;= non_defect_images.shape[0] else non_defect_images.shape[0]</pre><pre># Declare dataset by concat defect_images and non_defect_images <br># with length from 0 until class_size<br>dataset = np.concatenate((defect_images[:class_size], non_defect_images[:class_size]))</pre><pre># Create an empty matrix X with is matrix of 256x4096<br># with row equals dataset&#39;s length <br>X = np.empty([dataset.shape[0], 256, 4096]).astype(int)</pre><pre># Create vector y that has dataset length<br>y = np.empty(dataset.shape[0]).astype(int)</pre><pre># Assign the X,y one-by-one<br>for i in range(dataset.shape[0]):<br>    X[i] = dataset[i][“data”]<br>    y[i] = dataset[i][“label”]</pre><pre># Since Keras acquire the Image input is a tensor type, we reshape X<br>X = X.reshape(X.shape[0], 256, 4096, 1)</pre><pre># Display size of the label 0 and label 1 <br>np.unique(y, return_counts=True)</pre><p>Now, the size of the dataset is:</p><pre>(array([0, 1]), array([105, 105]))</pre><p>As a show, our dataset has a size equal to <strong>210 images, containing 105 defect-free and 105 defect images</strong>. In general, the Deep Learning model acquires an amount of dataset (~10K). Therefore, the 210 dataset number is not decent and may cause low accuracy.</p><p><strong>3. Create the CNN model</strong></p><p>There are many ways to approach the CNN architecture design. We have chosen to use <strong>AlexNet</strong> (<a href="https://dl.acm.org/doi/10.1145/3065386">A. Krizhevsky et al., 2012</a>) as the basis and starting with five convolution layers and three fully connected layers. During implementation, the architecture was fine-tuned for optimization.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*EU5gve3DGehRcR6h" /><figcaption>Fig 3: AlexNet. <a href="https://papers.nips.cc/paper/4824-imagenet-classification-with-deep-convolutional-neural-networks.pdf">Source</a></figcaption></figure><p>In finally, our model consists of 7 layers which include:</p><ul><li>1st: Convolution-layer with 16 filters 7x7 stride 2x2 max-pooling</li><li>2nd: Convolution-layer with 32 filters 5x5 stride 2x2 max-pooling</li><li>3rd: Convolution-layer with 64 filters 3x3 stride 2x2 max-pooling</li><li>4th: Convolution-layer with 64 filters 3x3 stride 2x2 max-pooling</li><li>5th: Fully-connected-layer with 64 nodes</li><li>6th: Fully-connected-layer with 64 nodes</li><li>7th: Fully-connected-layer with one node</li></ul><p>The last layer is the model output. Each layer primarily uses <strong>ReLu</strong> as the activation function since<em> it does not cause the vanishing gradient problem,</em> except the output layer prefers using the <strong>sigmoid </strong>function. Furthermore, we <em>avoid overfitting</em> by adding <strong>dropout</strong> and <strong>batch normalization</strong>. For model Compilation, <strong>Stochastic Gradient Descent (SGD)</strong> was set as an optimizer and <strong>Binary Cross-Entropy</strong> as the loss function based on computational time.</p><pre>from tensorflow.keras import datasets, layers, models, optimizers, regularizers<br>from tensorflow.keras.callbacks import EarlyStopping, ModelCheckpoint</pre><pre>def create_model(image_shape=(256, 4096, 1), print_summary=False):<br>    # Initial model<br>    model = models.Sequential()</pre><pre>    # CONV layer: filter 16, stride 7x7<br>    model.add(layers.Conv2D(16, (7, 7),input_shape=image_shape))<br>    model.add(layers.BatchNormalization())<br>    model.add(layers.Activation(&quot;relu&quot;))<br>    model.add(layers.MaxPooling2D((2, 2)))<br>    model.add(layers.Dropout(0.25))</pre><pre>    # CONV layer: filter 32, stride 5x5<br>    model.add(layers.Conv2D(32, (5, 5), padding=”same”))<br>    model.add(layers.BatchNormalization())<br>    model.add(layers.Activation(&quot;relu&quot;))<br>    model.add(layers.MaxPooling2D((2, 2)))<br>    model.add(layers.Dropout(0.25))<br> <br>    # CONV layer: filter 64, stride 3x3<br>    model.add(layers.Conv2D(64, (3, 3), padding=”same”))<br>    model.add(layers.BatchNormalization())<br>    model.add(layers.Activation(&quot;relu&quot;))<br>    model.add(layers.MaxPooling2D((2, 2)))<br>    model.add(layers.Dropout(0.25))<br> <br>    # CONV layer: filter 64, stride 3x3<br>    model.add(layers.Conv2D(64, (3, 3), padding=”same”))<br>    model.add(layers.BatchNormalization())<br>    model.add(layers.Activation(&quot;relu&quot;))<br>    model.add(layers.MaxPooling2D((2, 2)))<br>    model.add(layers.Dropout(0.25))<br> <br>    model.add(layers.Flatten())<br> <br>    # Fully connected layer -&gt; nn layer with 64 nodes<br>    model.add(layers.Dense(64))<br>    model.add(layers.BatchNormalization())<br>    model.add(layers.Activation(&quot;relu&quot;))<br>    model.add(layers.Dropout(0.25))</pre><pre>    # Fully connected layer -&gt; nn layer with 64 nodes<br>    model.add(layers.Dense(64))<br>    model.add(layers.BatchNormalization())<br>    model.add(layers.Activation(&quot;relu&quot;))<br>    model.add(layers.Dropout(0.25))<br> <br>    # Output layer<br>    model.add(layers.Dense(1, activation=&quot;sigmoid&quot;))<br> <br>    # Set model compiler<br>    model.compile(optimizer=&quot;SGD&quot;, loss=&quot;binary_crossentropy&quot;,          metrics=[&quot;accuracy&quot;])<br> <br>    # Show the CNN model detail<br>    if print_summary:<br>        model.summary()<br>    <br>    return model</pre><p>The summary of the model is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/514/0*dA7xobmNH0wPa5i5" /><figcaption>Layer 1st to Layer 3rd</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/507/0*zdNrOz9c64DlOiXx" /><figcaption>Layer 4th to Layer 6th</figcaption></figure><p>For a description of each layer,</p><ul><li><strong><em>Conv2d layer.</em></strong> Convolution layer</li><li><strong><em>Max pooling layer.</em></strong> To reduce the size of the matrix.</li><li><strong><em>Activation layer. </em></strong>The output function for the previous layer</li><li><strong><em>BatchNormalization layer. </em></strong>Normalize by re-centering and re-scaling</li><li><strong><em>Dropout layer. </em></strong>To avoid overfitting.</li><li><strong><em>Dense layer. </em></strong>The fully connected layer</li><li><strong><em>Flatten layer</em></strong><em>.</em><strong><em> </em></strong>Flatten the convolution layer into a vector.</li></ul><h4>4. Train and Evaluate the CNN model</h4><p>To efficiently measure the model performance, we use the stratified k-fold method, where the algorithm consists of test and train cycles as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*FgjWcKKW8gg3SYL_.png" /><figcaption>Fig 4: Stratified k-fold Partition. <a href="https://scikit-learn.org/stable/auto_examples/model_selection/plot_cv_indices.html#sphx-glr-auto-examples-model-selection-plot-cv-indices-py">Source</a></figcaption></figure><p>For stratified k-fold, each fold separates the dataset to be two groups:</p><ol><li><strong><em>Training dataset.</em></strong> Use in the CNN mode training.</li><li><strong><em>Validate dataset.</em></strong> Evaluate the model at the end of a training epoch.</li></ol><p>In each iteration, we have to train the model several times. For simplifying the process, let us write a train function:</p><pre>def train_model(model, xtrain, ytrain, xval, yval, n_epoch, batch_size):<br>    # Train CNN model<br>    # Batch size to reduce memory usage<br>    # Set early stopping to avoid overfitting<br> <br>    earlystopping = EarlyStopping(monitor=&quot;val_accuracy&quot;, patience=2)</pre><pre>    history = model.fit(xtrain, ytrain, epochs=n_epoch, batch_size=batch_size, validation_data=(xval, yval), callbacks=[earlystopping])<br>    return history</pre><p>During training, we use the callback function named earlystopping to halt the training process when the model does not improve. We set a parameter with a two epochs patience threshold, meaning <strong>if the validation accuracy cannot increase in 2 iterations, the training process will automatically stop</strong>. The function helps us save time.</p><p>Now, we are ready to evaluate the model:</p><pre>from sklearn.model_selection import StratifiedKFold</pre><pre># Set number of split<br>kfold_splits = 4<br># Set number of epoch<br>n_epoch = 10<br># Set batch size<br>batch_size = 10</pre><pre># Create StratifiedKFold<br>skf = StratifiedKFold(n_splits=kfold_splits, shuffle=True)</pre><pre>for index, (train_indices, val_indices) in enumerate(skf.split(X, y)):<br>    print(“Training on fold {}/{}…”.format(index+1, kfold_splits))<br>    <br>    # Declare x train and x validate<br>    xtrain, xval = X[train_indices], X[val_indices]<br>    # Declare y train and y validate<br>    ytrain, yval = y[train_indices], y[val_indices]</pre><pre>    # Print number of class portion<br>    print(“ytrain: number of samples each class: {}”.format(np.unique(ytrain, return_counts=True)))<br>    print(“yval: number of samples each class: {}”.format(np.unique(yval, return_counts=True)))<br>    <br>    # Clear the model<br>    model = None<br>    # Create cnn model<br>    model = create_model()</pre><pre>    print(“Training new iteration on {} training samples, {} validation samples, this may be a while…”.format(xtrain.shape[0], xval.shape[0]))<br> <br>    # Train CNN model<br>    history = train_model(model, xtrain, ytrain, xval, yval, n_epoch, batch_size)</pre><pre>    print(“— — — — — &quot;*5)</pre><p>Since the model is evaluated, we can calculate the average of the accuracy and loss, which will be shown in the result section.</p><h4>5. Export CNN model</h4><p>To export the model, we need to alter the code in that we have split the dataset into a testing set and a training set before the training process. <strong>The model will not be aware of the test set until the final evaluation process. In contrast, the validation set is used to tune the model in the training process.</strong></p><pre>from sklearn.model_selection import train_test_split</pre><pre>X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.15, random_state=42)</pre><pre>print(“y_train: number of samples each class: {}”.format(np.unique(y_train, return_counts=True)))</pre><pre>print(“y_test: number of samples each class: {}”.format(np.unique(y_test, return_counts=True)))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/553/1*Rb2K2aD2sXkhoXy8amnHeQ.png" /></figure><p>In the process, we include a callback named ModelCheckpoint. It helps us save the best performer when val_accuracy has improved.</p><pre>cnn_model = None<br>cnn_model = create_model(image_shape=(256, 4096, 1))</pre><pre># Define the EarlyStopping function<br>earlystopping = EarlyStopping(monitor=&quot;val_accuracy&quot;, patience=2)</pre><pre># Define the path for ModelCheckpoint function<br>filepath = project_path + “/model/weights_best.hdf5”</pre><pre># Define the ModelCheckpoint function<br>checkpoint = ModelCheckpoint(filepath, monitor=&quot;val_accuracy&quot;, verbose=1, save_best_only=True, mode=&quot;max&quot;)</pre><pre>callbacks_list = [checkpoint, earlystopping]</pre><pre># Train model<br>cnn_model.fit(X_train, y_train, batch_size=10, epochs=10, validation_split=0.2, callbacks=callbacks_list)</pre><p>We exported the model weights into a file weights_best.hdf5. The requirements for model reconstruction are:</p><ol><li><strong><em>Model.</em></strong> The original model from create_model()</li><li><strong><em>Weights.</em></strong> Neural connection weights which produced after being trained by the dataset</li></ol><h4>(Optional) Import model into the edge device</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-Eal21X9ucVzJJ_xv0IrWw.jpeg" /><figcaption>Fig 5: Raspberry PI with a camera. <a href="https://projects.raspberrypi.org/en/projects/getting-started-with-picamera">Source</a></figcaption></figure><p>The application can be used in the manufacturing process to detect fabric defects by using our model based on the Edge AI concept. Although we do not have the devices, this article can guideline the procedure, which is not a complex implementation. Let us assume that a <strong>Raspberry PI connected with a camera or image feed is provided</strong>. Since we need to use the same CNN model, the prerequisite program of Raspberry PI should be the same as our article (e.g. <strong>Python</strong>, <strong>TensorFlow</strong>, etc.), as you can read in <a href="https://magpi.raspberrypi.org/articles/tensorflow-ai-raspberry-pi"><em>How-to-install-TensorFlow-on-Raspberry-Pi</em></a>. Also, dependencies for using camera devices acquire to install such as <strong>PiCamera</strong>, <strong>OpenCV, </strong>etc. Read here:<em> </em><a href="https://www.pyimagesearch.com/2015/03/30/accessing-the-raspberry-pi-camera-with-opencv-and-python/"><em>Accessing-the-Raspberry-Pi-Camera-with-OpenCV-and-Python</em></a>. For the predictive program, it should consist of create_model(), model.fit(), and parts of reading the input image from the camera.</p><p>For the example code:</p><p><a href="https://gist.github.com/ad9eef4b24a30c7aa1ea8c5d0eaec57d">https://gist.github.com/ad9eef4b24a30c7aa1ea8c5d0eaec57d</a></p><pre># DefectDetectionPrdictive.py</pre><pre># Import the necessary dependency<br>from tensorflow.keras import datasets, layers, models, optimizers, regularizers<br>from tensorflow.keras.callbacks import EarlyStopping, ModelCheckpoint<br>from picamera.array import PiRGBArray<br>from picamera import PiCamera</pre><pre>...</pre><pre># Initial create CNN, Same function as 3.<br>model = create_model()<br># Apply weights to CNN<br>model.load_weights(&quot;weights_best.hdf5&quot;)<br># Initialize PiCamera<br>camera = PiCamera()<br># Capture image from camera<br>rawCapture = PiRGBArray(camera)</pre><pre>...</pre><pre># Grab an image from the camera<br>camera.capture(rawCapture, format=&quot;gray&quot;)<br># Predict the input image<br>print(model.predict(image))</pre><pre>...</pre><p>To compile the program:</p><pre>python3 DefectDetectionPrdictive.py</pre><p><strong>Note — This part is not an actual demonstration. Therefore, errors may occur.</strong> This is simply the concept of such implementation. Furthermore, the program can be adjusted depending on the proposed system specification. This idea of its application in edge device implementation for the smart factory has been discussed extensively in various research. For instance, <a href="https://ieeexplore.ieee.org/document/8392817">D. Huang et al., 2018</a> presented the architecture of the smart factory in the defect detection systems.</p><h3>Result</h3><p>The graphs below illustrate the performance of the model between each training epoch.</p><p>Our model accuracy:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T1C68wAwFZn88Gie76LhjQ.png" /><figcaption>Higher is better</figcaption></figure><p>The maximum epoch count is ten iterations. But due to the early stopping threshold, the model would halt learning when there is no significant improvement between epoch, hence 3 to 7 epochs on the performance graph.</p><p>Our model loss:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jG-YS6Or4GsIinGWt-_h6w.png" /><figcaption>Lower is better</figcaption></figure><p>We select the best epoch for each fold to calculate the <strong>validation average</strong>:</p><pre>average accuracy: 0.5862, average loss: 0.968</pre><p>All in all, the result is within satisfaction given the less than ideal size of the datasets, and the demonstration for the implementation of this concept is still clear.</p><p>The exported model performance:</p><pre>model = create_model()<br>model.load_weights(project_path + “/model/weights_best.hdf5”)<br>score, acc = model.evaluate(X_test, y_test, verbose=0)<br>print(score, acc)</pre><p>In which the result is:</p><pre>(0.7061388492584229, 0.625)</pre><p>This is the model evaluation by test set where “score” represents the model loss, and “acc” means the model accuracy.</p><h3>Conclusion</h3><p>In this article, we have demonstrated and go over many steps regarding CNN based implementation for edge-based defect detection, including:</p><ul><li>Fabric Defect Detection using CNN implementation</li><li>The defect image dataset from <a href="https://doi.org/10.2478/aut-2019-0035">J. Silvestre-Blanes et al., 2019</a></li><li>AlexNet model Infrastructure</li><li>Stratified K-fold model evaluation</li><li>Our model has an average accuracy of 0.5862 and an average loss of 0.968</li><li>Edge Device Implementation</li></ul><p>While the model performance is as expected given the lack of a sizable dataset, a major problem that we can observe is overfitting, which can be remedied in many ways such as:</p><ol><li>Increase the dataset — Collect more data, data synthesis, or data augmentation.</li><li>Change the architecture — Try other CNN architecture such as <a href="https://arxiv.org/abs/1409.1556">VGG-16</a> or <a href="https://arxiv.org/abs/1512.03385">ResNet-50</a>.</li><li>Tuning model — Better architecture fine-tuning can cause the model to achieve better performance.</li><li>Transfer Learning — This is a method of deploying a pre-trained model and later train additionally using our dataset by freeze the pre-trained layers.</li></ol><p>In conclusion, while the methodology in this article can use many improvements, we hope that this demonstration is a positive contribution as a stepping stone to the growing popularity of edge-based AI and that you, the readers, may find it useful.</p><h3>GitHub</h3><p>The source code with comments is provided. Please check:</p><p><a href="https://github.com/sadanalog/defect-detection-using-cnn">sadanalog/defect-detection-using-cnn</a></p><h4>Acknowledgment</h4><p>This report is a part of ICT730 Hardware Designs for Embedded Systems in the TAIST-Tokyo Tech program, which has been written by Isada Sukprapa and Naruson Srivaro.</p><h3>Reference</h3><ul><li>Y. Lecun, L. Bottou, Y. Bengio, and P. Haffner. Gradient-based learning applied to document recognition. Proceedings of the IEEE, vol. 86, no. 11, pp. 2278–2324, Nov. 1998. DOI: <a href="https://doi.org/10.1109/5.726791">https://doi.org/10.1109/5.726791</a></li><li>J. Silvestre-Blanes, T. Albero-Albero, I. Miralles, R. Pérez-Llorens, and J. Moreno, (2019). A Public Fabric Database for Defect Detection Methods and Results. Autex Research Journal, 19(4), 363–374. DOI: <a href="https://doi.org/10.2478/aut-2019-0035">https://doi.org/10.2478/aut-2019-0035</a></li><li>A. Krizhevsky, I. Sutskever, and G. E. Hinton. 2017. ImageNet classification with deep convolutional neural networks. Commun. ACM 60, 6 (June 2017), 84–90. DOI: <a href="https://doi.org/10.1145/3065386">https://doi.org/10.1145/3065386</a></li><li>K. He, X. Zhang, S. Ren, and J. Sun. Deep Residual Learning for Image Recognition. 2016 IEEE Conference on Computer Vision and Pattern Recognition (CVPR), Las Vegas, NV, 2016, 770–778. DOI: <a href="https://doi.org/10.1109/CVPR.2016.90">https://doi.org/10.1109/CVPR.2016.90</a></li><li>S. Ioffe &amp; C. Szegedy. 2015. Batch Normalization: Accelerating Deep Network Training by Reducing Internal Covariate Shift. Proceedings of the 32nd International Conference on Machine Learning, in PMLR 37:448–456. DOI: <a href="https://dl.acm.org/doi/10.5555/3045118.3045167">https://dl.acm.org/doi/10.5555/3045118.3045167</a></li><li>Jason Brownlee. (2016, July 1). Object Classification with CNNs using the Keras Deep Learning Library. Machine Learning Mastery. <a href="https://machinelearningmastery.com/object-recognition-convolutional-neural-networks-keras-deep-learning-library/">https://machinelearningmastery.com/object-recognition-convolutional-neural-networks-keras-deep-learning-library</a></li><li>Laurent H. (2017, Jul 13). Stratified k-fold with Keras. Medium. <a href="https://medium.com/@literallywords/stratified-k-fold-with-keras-e57c487b1416">https://medium.com/@literallywords/stratified-k-fold-with-keras-e57c487b1416</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c3e7c2a1088d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>