मुख्य सामग्री पर जाएँ

keras: R में डीप लर्निंग

In this tutorial to deep learning in R with RStudio's keras package, you'll learn how to build a Multi-Layer Perceptron (MLP).
· 15 मि॰ पढ़ें

AI के साथ खोजें

जैसा कि आप अब तक जानते हैं, मशीन लर्निंग कंप्यूटर साइंस (CS) का एक उपक्षेत्र है। डीप लर्निंग, मशीन लर्निंग का ही एक उपक्षेत्र है, जिसमें ऐसे एल्गोरिदम शामिल हैं जो मस्तिष्क की संरचना और कार्य से प्रेरित होते हैं और जिन्हें आमतौर पर आर्टिफिशियल न्यूरल नेटवर्क्स (ANN) कहा जाता है। वर्तमान में डीप लर्निंग, मशीन लर्निंग के सबसे चर्चित रुझानों में से एक है, और कई समस्याएँ हैं जहाँ डीप लर्निंग उत्कृष्ट प्रदर्शन करता है, जैसे रोबोटिक्स, इमेज रिकग्निशन और आर्टिफिशियल इंटेलिजेंस (AI)।

आज के इस ट्यूटोरियल में आप R में Keras के साथ keras पैकेज का उपयोग करते हुए डीप लर्निंग की संक्षिप्त परिचयात्मक जानकारी पाएँगे:

क्या आप ओरिजिनल Keras या डीप लर्निंग की महत्वपूर्ण अवधारणाएँ जैसे पर्सेप्ट्रॉन और मल्टी-लेयर पर्सेप्ट्रॉन (MLPs) के बारे में अधिक जानना चाहते हैं? DataCamp का Deep Learning in Python कोर्स करने या Keras Tutorial: Deep Learning in Python करने पर विचार करें।

टिप: हमारा Keras चीट शीट यहाँ देखें।

R में डीप लर्निंग: पैकेजों का संक्षिप्त अवलोकन

डीप लर्निंग की बढ़ती लोकप्रियता के साथ, CRAN में अधिक R डीप लर्निंग पैकेज शामिल हो गए हैं; नीचे आप इन पैकेजों का एक अवलोकन देख सकते हैं, जो Machine Learning and Statistical Learning CRAN टास्क व्यू से लिया गया है। “Percentile” कॉलम RDocumentation पर पाए गए परसेंटाइल को दर्शाता है:

R पैकेजPercentileविवरण
nnet96thएकल hidden लेयर के साथ फीड-फॉरवर्ड न्यूरल नेटवर्क्स और मल्टीनोमियल लॉग-लीनियर मॉडलों के लिए सॉफ़्टवेयर।
neuralnet96thबैकप्रोपेगेशन का उपयोग करके न्यूरल नेटवर्क्स का प्रशिक्षण
h2o95thH2O के लिए R स्क्रिप्टिंग कार्यक्षमता
RSNNS88thStuttgart Neural Network Simulator (SNNS) का इंटरफ़ेस
tensorflow88thTensorFlow का इंटरफ़ेस
deepnet84thR में डीप लर्निंग टूलकिट
darch79thडीप आर्किटेक्चर और रेस्ट्रिक्टेड बोल्ट्ज़मैन मशीनों के लिए पैकेज
rnn73rdरीकरंट न्यूरल नेटवर्क्स (RRNs) को लागू करने के लिए पैकेज
FCNN4R52ndFCNN लाइब्रेरी का इंटरफ़ेस जो उपयोगकर्ता-विस्तार योग्य ANNs की अनुमति देता है
rcppDL7thकई लेयर (डीप लर्निंग) वाले मूल मशीन लर्निंग तरीकों का कार्यान्वयन, जिसमें dA (Denoising Autoencoder), SdA (Stacked Denoising Autoencoder), RBM (Restricted Boltzmann machine) और DBN (Deep Belief Nets) शामिल हैं
deepr??*darch और deepnet पर आधारित डीप लर्निंग के लिए प्रशिक्षण, फाइन-ट्यूनिंग और प्रेडिक्टिंग प्रक्रियाओं को सरल बनाने वाला पैकेज
MXNetR??*पैकेज जो R में लचीला और कुशल GPU कंप्यूटिंग और अत्याधुनिक डीप लर्निंग लाता है

टिप: R में डीप लर्निंग पैकेजों की तुलना के लिए यह ब्लॉग पोस्ट पढ़ें। RDocumentation में रैंकिंग और स्कोर के बारे में अधिक जानकारी के लिए यह ब्लॉग पोस्ट देखें।

deepr और MXNetR, RDocumentation.org पर नहीं मिले, इसलिए इन दोनों पैकेजों के लिए परसेंटाइल अज्ञात है।

Keras, keras और kerasR

हाल ही में, दो नए पैकेज R समुदाय तक पहुँचे: kerasR पैकेज, जिसे Taylor Arnold ने बनाया है, और RStudio का keras पैकेज।

दोनों पैकेज, Python के डीप लर्निंग पैकेज Keras के लिए R इंटरफ़ेस प्रदान करते हैं, जिसके बारे में आपने शायद पहले ही सुना होगा, या शायद आपने इसके साथ काम भी किया होगा! जो लोग नहीं जानते कि Python उपयोगकर्ताओं के लिए Keras क्या प्रदान करता है, उनके लिए यह “एक हाई-लेवल न्यूरल नेटवर्क्स API है, जो Python में लिखा गया है और जो TensorFlow, Microsoft Cognitive Toolkit (CNTK) या Theano में से किसी के ऊपर चलने में सक्षम है”।

इंटरफ़ेस?

देखिए, Python में डीप लर्निंग से परिचित होने के लिए Keras से शुरुआत करना सबसे आसान तरीकों में से एक है, और यही वजह है कि kerasR और keras पैकेज R उपयोगकर्ताओं के लिए इस शानदार पैकेज का इंटरफ़ेस प्रदान करते हैं।

इस संदर्भ में, यह समझना आपके लिए उपयोगी है कि जब कोई पैकेज, जैसे R का keras, किसी अन्य पैकेज—Python Keras—का “इंटरफ़ेस” होता है, तो उसका क्या मतलब है। सरल शब्दों में, इसका मतलब है कि इंटरफ़ेस वाला keras R पैकेज आपको R प्रोग्रामिंग का लाभ देते हुए Python Keras पैकेज की क्षमताओं तक पहुँचने की सुविधा देता है।

ध्यान दें कि यह कोई असामान्य बात नहीं है: उदाहरण के लिए, h2o पैकेज भी एक इंटरफ़ेस प्रदान करता है, लेकिन इस मामले में—और जैसा कि नाम से ही आभास होता है—H2O के लिए, जो बिग डेटा के लिए ओपन सोर्स मैथ इंजन है, जिसका उपयोग आप पैरेलल डिस्ट्रीब्यूटेड मशीन लर्निंग एल्गोरिद्म चलाने के लिए कर सकते हैं। अन्य पैकेज जिन्हें आप जानते होंगे जो इंटरफ़ेस प्रदान करते हैं, उनमें RWeka (Weka के लिए R इंटरफ़ेस), tensorflow (TensorFlow के लिए R इंटरफ़ेस), openml-r (OpenML के लिए R इंटरफ़ेस), … शामिल हैं। सूची लंबी है!

Keras, keras और kerasR में क्या अंतर है?

अब जब आप यह सब जानते हैं, तो आपके मन में पहला सवाल यह आ सकता है: आप ओरिजिनल Python पैकेज की तुलना R पैकेजों से कैसे करेंगे?

मूल रूप से, आपको R पैकेजों और ओरिजिनल Python पैकेज के बीच बहुत अधिक अंतर नहीं मिलेगा, मुख्यतः क्योंकि फ़ंक्शन नाम लगभग समान हैं; जो अंतर आप नोटिस करेंगे, वे मुख्यत: प्रोग्रामिंग भाषाओं में ही होंगे (वेरिएबल असाइनमेंट, लाइब्रेरी लोड करना, …), लेकिन सबसे महत्वपूर्ण बात यह है कि ओरिजिनल फंक्शनैलिटी का कितना हिस्सा R पैकेज में शामिल किया गया है।

ध्यान दें कि यह टिप्पणी सिर्फ keras लाइब्रेरी के लिए ही नहीं, बल्कि ऊपर उल्लेखित tensorflow, openml-r, … और अन्य इंटरफ़ेस पैकेजों के लिए भी मान्य है!

दूसरे, आप यह भी जानना चाह सकते हैं कि इन दो R पैकेजों में फिर क्या अंतर है। खैर, यदि आप इन दोनों के अंतर पर विचार करना चाहते हैं, तो आप निम्नलिखित बिंदुओं पर विचार कर सकते हैं:

  • keras पैकेज pipe ऑपरेटर (%>%) का उपयोग फ़ंक्शंस या ऑपरेशंस को जोड़ने के लिए करता है, जबकि आप इसे kerasR में नहीं पाएँगे: उदाहरण के लिए, kerasR के साथ अपना मॉडल बनाने के लिए, आपको $ ऑपरेटर का उपयोग करना होगा। pipe ऑपरेटर का उपयोग आम तौर पर आपके कोड की पठनीयता में सुधार करता है, और यदि आपने पहले Tidyverse पैकेजों के साथ काम किया है, तो आपने निश्चित रूप से इस ऑपरेटर को देखा होगा।

  • आप देखेंगे कि kerasR में ऐसे फ़ंक्शन शामिल हैं जिनके नाम समान हैं, लेकिन ओरिजिनल Keras पैकेज से बिल्कुल एक जैसे नहीं हैं। उदाहरण के लिए, आरंभिक (Python) compile() फ़ंक्शन को keras_compile() कहा जाता है; यही बात अन्य फ़ंक्शंस पर भी लागू होती है, जैसे fit(), जो keras_fit() बन जाता है, या predict(), जो keras_predict होता है जब आप kerasR पैकेज का उपयोग करते हैं। ये सभी कस्टम रैपर हैं।

  • आप कह सकते हैं कि RStudio का keras पैकेज इंस्टॉल करना, kerasR पैकेज की तुलना में आसान है; बाद वाला इंस्टॉल करने के लिए, आपको पहले यह सुनिश्चित करना होता है कि आप कौन-सा Python संस्करण उपयोग करेंगे और यदि आपके पीसी में कई एन्वायरनमेंट या Python संस्करण इंस्टॉल हैं, तो यह मुश्किल हो सकता है। लेकिन इस पर निर्णय आपको करना है :)

data science courses banner

अब जब आपके पास कुछ पृष्ठभूमि है, तो R में Keras के साथ वास्तविक रूप से शुरू करने का समय है। जैसा कि आपने इस ट्यूटोरियल की प्रस्तावना में पढ़ा होगा, आप सबसे पहले अपने वर्कस्पेस की सेटअप पर जाएँगे। फिर, आप कुछ डेटा लोड करेंगे और एक संक्षिप्त डेटा अन्वेषण और प्रीप्रोसेसिंग चरण के बाद, आप अपना MLP बनाना शुरू कर पाएँगे!

चलिए शुरू करते हैं!

keras पैकेज इंस्टॉल करना

हमेशा की तरह, किसी भी पैकेज के साथ शुरू करने का पहला कदम है अपना वर्कस्पेस सेट करना: लाइब्रेरी को RStudio या जिस भी एन्वायरनमेंट में आप काम कर रहे हैं, उसमें इंस्टॉल और लोड करना।

चिंता न करें, इस ट्यूटोरियल के लिए पैकेज आपके लिए लोड कर दिया जाएगा!

सबसे पहले, सुनिश्चित करें कि आप keras इंस्टॉल करें: आप इसे अपने कंसोल में devtools::install_github("rstudio/keras") चलाकर आसानी से कर सकते हैं। इसके बाद, आप पैकेज लोड कर सकते हैं और TensorFlow इंस्टॉल कर सकते हैं:

# Load in the keras package
library(keras)

# Install TensorFlow
install_tensorflow()

जब आप यह कर लें, तो आप तैयार हैं! तेज़ है, है न?

टिप: इंस्टॉलेशन प्रक्रिया पर अधिक जानकारी के लिए, पैकेज वेबसाइट देखें।

डेटा लोड करना

अब जबकि इंस्टॉलेशन प्रक्रिया स्पष्ट है और आपका वर्कस्पेस तैयार है, आप अपना डेटा लोड करना शुरू कर सकते हैं! इस बिंदु पर, डेटा के संदर्भ में आपके पास तीन बड़े विकल्प हैं: आप keras पैकेज के साथ आने वाले बिल्ट-इन डेटासेट में से किसी एक का उपयोग कर सकते हैं, आप अपने स्वयं के डेटासेट को, उदाहरण के लिए, CSV फ़ाइलों से लोड कर सकते हैं, या आप कुछ डमी डेटा बना सकते हैं।

आप किसी भी स्थिति में हों, आप देखेंगे कि आप पैकेज के साथ जल्दी शुरू कर पाएँगे। यह सेक्शन इन तीनों विकल्पों पर संक्षेप में जाएगा और बताएगा कि आप शुरुआत करने के लिए आवश्यक डेटा को कैसे लोड (या बनाए) सकते हैं!

बिल्ट-इन डेटासेट

यदि आपके पास Python में Keras पैकेज का कुछ अनुभव है, तो आपने संभवतः mnist.load_data(), cifar10.load_data(), या imdb.load_data() जैसे फ़ंक्शंस के साथ Keras के बिल्ट-इन डेटासेट पहले ही एक्सेस किए होंगे।

यहाँ कुछ उदाहरण हैं जहाँ आप keras पैकेज के साथ MNIST, CIFAR10 और IMDB डेटा लोड करते हैं:

# Read in MNIST data
mnist <- dataset_mnist()

# Read in CIFAR10 data
cifar10 <- dataset_cifar10()

# Read in IMDB data
imdb <- dataset_imdb()

ध्यान दें कि keras के साथ बिल्ट-इन डेटासेट लोड करने के सभी फ़ंक्शन एक ही पैटर्न का पालन करते हैं; MNIST डेटा के लिए, आप अपना डेटा लोड करने के लिए dataset_mnist() फ़ंक्शन का उपयोग करेंगे।

डमी डेटा

वैकल्पिक रूप से, आप जल्दी से शुरुआत करने के लिए कुछ डमी डेटा भी बना सकते हैं। आप matrix() फ़ंक्शन का आसानी से उपयोग कर सकते हैं:

# Make your dummy data
data <- matrix(rexp(1000*784), nrow = 1000, ncol = 784)

# Make dummy target values for your dummy data
labels <- matrix(round(runif(1000*10, min = 0, max = 9)), nrow = 1000, ncol = 10)

ध्यान दें कि अपने डेटा की संरचना जाँचना एक अच्छा विचार है; आप किस डेटा के साथ काम कर रहे हैं, यह पहले से जानना महत्वपूर्ण है क्योंकि यह बाद के चरणों के लिए आवश्यक होगा। इसके बारे में आप आगे ट्यूटोरियल में और सीखेंगे!

फ़ाइलों से डेटा पढ़ना

बिल्ट-इन डेटासेट के अलावा, आप फ़ाइलों से भी डेटा लोड कर सकते हैं। इस ट्यूटोरियल के लिए, आप CSV फ़ाइलों से डेटा लोड करने पर ध्यान देंगे, लेकिन यदि आप R में फ़ाइल आयात करने के बारे में अधिक जानना चाहते हैं, तो DataCamp का R Data Import Tutorial देखें।

आइए read.table पैकेज के read.csv() फ़ंक्शन का उपयोग करके UCI मशीन लर्निंग रिपॉज़िटरी से एक डेटा सेट लोड करें:

# Read in `iris` data
iris <- read.csv(url("http://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data"), header = FALSE) 

# Return the first part of `iris`
head(....)

# Inspect the structure
str(....)

# Obtain the dimensions
dim(....)

यह हमेशा एक अच्छा विचार है कि यह जाँच लें कि आपका डेटा इम्पोर्ट सफल रहा या नहीं। आप आम तौर पर head(), str() और dim() जैसे फ़ंक्शंस का उपयोग करते हैं, जैसा कि ऊपर DataCamp Light खंड में है।

इन तीनों फ़ंक्शंस के परिणाम तुरंत कोई असामान्यता नहीं दिखाते; str() फ़ंक्शन के आउटपुट को देखकर, आप देखते हैं कि Species कॉलम की स्ट्रिंग्स को फैक्टर्स के रूप में पढ़ा गया है। यह कोई समस्या नहीं है, लेकिन अगले चरणों के लिए—जहाँ आप डेटा का अन्वेषण और प्रीप्रोसेस करेंगे—यह जानना निश्चित रूप से अच्छा है।

डेटा अन्वेषण

इस ट्यूटोरियल के लिए, आप read.csv() फ़ंक्शन से इम्पोर्ट किए गए प्रसिद्ध iris डेटासेट के साथ काम करना जारी रखेंगे।

जिनके पास इस डेटा के साथ काम करने के लिए आवश्यक जीवविज्ञान का ज्ञान नहीं है, उनके लिए कुछ पृष्ठभूमि जानकारी: सभी फूलों में सेपल और पंखुड़ी (पेटल) होती है। सेपल, पंखुड़ियों को घेरता है और आमतौर पर हरा और पत्ती जैसी संरचना का होता है, जबकि पंखुड़ियाँ सामान्यतः रंगीन पत्तियाँ होती हैं। आइरिस फूलों के मामले में, यह थोड़ा अलग है, जैसा कि आप निम्न चित्र में देख सकते हैं:

deep learning Python

आपने पिछले सेक्शन में शायद देखा होगा कि इम्पोर्ट के बाद iris डेटा फ्रेम में कोई कॉलम नाम नहीं थे। अब, ट्यूटोरियल के शेष भाग के लिए, यह बहुत महत्वपूर्ण नहीं है: भले ही read.csv() फ़ंक्शन आपको डेटा को data.frame के रूप में लौटाता है, लेकिन fit() फ़ंक्शन को जो डेटा पास करना है, वह मैट्रिक्स या एरे होना चाहिए।

अभी-अभी उल्लेखित इन दो डेटा संरचनाओं के बारे में ध्यान रखने योग्य कुछ बातें: - मैट्रिक्स और एरे में कॉलम नाम नहीं होते; - मैट्रिक्स एकल डेटा प्रकार की दो-आयामी वस्तुएँ हैं; - एरे एकल डेटा प्रकार की बहु-आयामी वस्तुएँ हैं;

टिप: यदि आप R में डेटा संरचनाओं का रीकैप चाहते हैं, तो यह वीडियो देखें!

ध्यान दें कि डेटा फ्रेम, दूसरी ओर, एक विशेष प्रकार की नामित लिस्ट है जहाँ सभी तत्वों की लंबाई समान होती है। यह एक बहु-आयामी वस्तु है जो एकाधिक डेटा प्रकार रख सकती है। आपने यह पहले ही देखा था जब आपने पिछले सेक्शन में iris डेटा फ्रेम की संरचना की जाँच की थी। यह जानते हुए और यह ध्यान में रखते हुए कि आपको एकल डेटा प्रकार की दो या बहु-आयामी वस्तु की ओर बढ़ना है, आपको अपने न्यूरल नेटवर्क के निर्माण से पहले कुछ प्रीप्रोसेसिंग करने के लिए तैयार रहना चाहिए!

फिलहाल, कॉलम नाम अन्वेषण उद्देश्यों के लिए सहायक हो सकते हैं, और वे निश्चित रूप से आपके डेटा की समझ को आसान बनाएँगे, इसलिए आइए names() फ़ंक्शन की मदद से कुछ कॉलम नाम जोड़ते हैं। अगला, आप तुरंत अपने डेटा अन्वेषण में iris वेरिएबल का उपयोग कर सकते हैं! उदाहरण के लिए, plot() फ़ंक्शन से देखें कि पंखुड़ी की लंबाई और चौड़ाई में कैसा सहसंबंध है।

names(iris) <- c("Sepal.Length", "Sepal.Width", "Petal.Length", "Petal.Width", "Species")

plot(iris$Petal.Length, 
     iris$Petal.Width, 
     pch=21, bg=c("red","green3","blue")[unclass(iris$Species)], 
     xlab="Petal Length", 
     ylab="Petal Width")

ध्यान दें कि आप unclass() फ़ंक्शन का उपयोग स्पीशीज़ के नामों—“setosa, versicolor” और “virginica”—को 1, 2, और 3 की संख्याओं में बदलने के लिए करते हैं।

अब plotting फ़ंक्शन के परिणाम पर क़रीबी नज़र डालें:

plot

ग्राफ़, आइरिस फूलों की विभिन्न प्रजातियों के लिए Petal.Length और Petal.Width के बीच पॉज़िटिव कोरिलेशन का संकेत देता है। हालाँकि, यह वह चीज़ है जिसे आप शायद cor() फ़ंक्शन से जाँचना चाहेंगे, जो आपको डेटा सेट में शामिल सभी विशेषताओं के बीच समग्र सहसंबंध देगा:

# Overall correlation between `Petal.Length` and `Petal.Width` 
cor(................., iris$Petal.Width)

इसके अतिरिक्त, आप corrplot पैकेज का उपयोग cor() फ़ंक्शन के साथ मिलाकर अपने डेटा की विशेषताओं के बीच सहसंबंधों को प्लॉट कर सकते हैं; इस मामले में, आप iris डेटा फ्रेम की सभी विशेषताओं के लिए समग्र सहसंबंध की गणना करते हैं। आप इस गणना के परिणाम को वेरिएबल M में स्टोर करते हैं और उसे corrplot() फ़ंक्शन में पास करते हैं।

साथ ही, यह बताना न भूलें कि आप डेटा को किस विधि से प्लॉट करना चाहते हैं, इसके लिए method आर्ग्युमेंट निर्दिष्ट करें!

आप नीचे दिए गए DataCamp Light खंड में विज़ुअलाइज़ेशन विधि के साथ और प्रयोग कर सकते हैं:

# Store the overall correlation in `M`
M <- cor(iris[,1:4])

# Plot the correlation plot with `M`
corrplot(M, method="circle")

chart

अपने डेटा का और अन्वेषण करने के लिए R कंसोल का उपयोग करें।

यदि आप इस डेटा के लिए ggvis पैकेज—जो इंटरेक्टिव ग्रामर ऑफ़ ग्राफ़िक्स है—से प्लॉट बनाना चाहते हैं, तो DataCamp का Machine Learning in R For Beginners ट्यूटोरियल देखें या DataCamp का ggvis कोर्स करें।

डेटा प्रीप्रोसेसिंग

मॉडल बनाने से पहले, आपको यह भी सुनिश्चित करना होगा कि आपका डेटा साफ़, नार्मलाइज़ (यदि लागू हो) और ट्रेनिंग व टेस्ट सेट में विभाजित हो। चूँकि डेटासेट UCI मशीन लर्निंग रिपॉज़िटरी से आता है, आप उम्मीद कर सकते हैं कि यह पहले से कुछ हद तक साफ़ होगा, लेकिन फिर भी अपने डेटा की गुणवत्ता की दोबारा जाँच कर लेते हैं।

पहली नज़र में, जब आपने head() से डेटा का निरीक्षण किया, तो कुछ असामान्य नहीं दिखा, है न? आइए summary() और str() का उपयोग करके संक्षेप में वह दोहराएँ जो आपने सीखा था जब आपने जाँचा था कि आपका डेटा इम्पोर्ट सफल हुआ या नहीं:

# Pull up a summary of `iris`
summary(....)

# Inspect the structure of `iris`
str(....)

अब जब आप आश्वस्त हैं कि डेटा पर्याप्त रूप से साफ़ है, तो आप यह जाँचना शुरू कर सकते हैं कि इस ट्यूटोरियल के लिए जिन डेटा पर आप काम कर रहे हैं, उनमें से किसी को नार्मलाइज़ करना आवश्यक है या नहीं।

यूज़र डेफ़ाइंड फ़ंक्शन (UDF) से डेटा नार्मलाइज़ करना

ऊपर दिए गए DataCamp Light खंड में summary() फ़ंक्शन के परिणाम से, आप देखते हैं कि Iris डेटासेट को नार्मलाइज़ करने की आवश्यकता नहीं है: Sepal.Length विशेषता के मान 4.3 से 7.9 तक जाते हैं और Sepal.Width में 2 से 4.4 तक मान हैं, जबकि Petal.Length के मान 1 से 6.9 तक और Petal.Width 0.1 से 2.5 तक जाती है। दूसरे शब्दों में, Iris डेटासेट की सभी विशेषताओं के सभी मान 0.1 और 7.9 के भीतर आते हैं, जिसे आप स्वीकार्य मान सकते हैं।

हालाँकि, अपने डेटा पर नार्मलाइज़ेशन के प्रभाव का अध्ययन करना अभी भी एक अच्छा विचार हो सकता है; आप यहाँ तक कर सकते हैं कि अपने मॉडल को नार्मलाइज़्ड डेटा पास करें और देखें कि कोई प्रभाव है या नहीं। यह इस ट्यूटोरियल के दायरे से बाहर है, लेकिन बेझिझक स्वयं आज़माएँ! इस ट्यूटोरियल में सारा कोड मौजूद है :)

आप iris डेटा को नार्मलाइज़ करने के लिए अपना फ़ंक्शन बना सकते हैं; इस मामले में, यह min-max नार्मलाइज़ेशन फ़ंक्शन है, जो आपके डेटा को रैखिक रूप से (x-min)/(max-min) में ट्रांसफ़ॉर्म करता है। इस दृष्टि से, इस सूत्र को R में ट्रांसलेट करना सरल है: आप एक फ़ंक्शन बनाते हैं जिसमें आप x या कुछ डेटा पास करते हैं। आप पहले घटाव x-min का परिणाम गणना करके num में स्टोर करेंगे। इसके बाद, आप max-min भी गणना करते हैं और परिणाम को denom में स्टोर करते हैं। आपकी normalize() फ़ंक्शन को num को max से भाग देकर परिणाम लौटाना चाहिए।

इस यूज़र-डिफ़ाइंड फ़ंक्शन को अपने iris डेटा (टार्गेट वैल्यू को छोड़कर) पर लागू करने के लिए, आपको डेटा को नार्मलाइज़ करने के लिए normalize के साथ-साथ lapply() फ़ंक्शन का भी उपयोग करना होगा, ठीक नीचे की तरह:

# Build your own `normalize()` function
normalize <- function(x) {
  num <- x - min(x)
  denom <- max(x) - min(x)
  return (num/denom)
}

# Normalize the `iris` data
iris_norm <- as.data.frame(lapply(iris[1:4], .........))

# Return the first part of `iris` 
head(....)

टिप: नार्मलाइज़ेशन से पहले (iris) और बाद (iris_norm) में Iris डेटा के वितरण का अध्ययन करने के लिए R कंसोल में hist() फ़ंक्शन का उपयोग करें।

keras से अपना डेटा नार्मलाइज़ करें

keras पैकेज के normalize() फ़ंक्शन का उपयोग करने के लिए, आपको पहले सुनिश्चित करना होगा कि आप मैट्रिक्स के साथ काम कर रहे हैं। जैसा कि आपने पहले से याद किया होगा, मैट्रिक्स की विशेषता है कि उसमें सभी डेटा एलिमेंट्स एक ही बुनियादी प्रकार के होते हैं; इस मामले में, आपके पास टार्गेट वैल्यू हैं जो फैक्टर टाइप की हैं, जबकि बाकी सब संख्यात्मक है।

इसे पहले बदलना होगा।

आप as.numeric() फ़ंक्शन का उपयोग करके डेटा को संख्याओं में बदल सकते हैं:

iris[,5] <- ...........(iris[,5]) -1

# Turn `iris` into a matrix
iris <- as.matrix(iris)

# Set `iris` `dimnames` to `NULL`
dimnames(....) <- NULL

संख्यात्मक डेटा फ्रेम ठीक है, लेकिन यदि आप keras पैकेज का उपयोग करना चाहते हैं तो आपको डेटा को एरे या मैट्रिक्स में बदलना होगा। आप as.matrix() फ़ंक्शन से यह आसानी से कर सकते हैं; यहाँ dimnames को NULL सेट करना न भूलें।

जैसा कि आपने ऊपर के सेक्शन में पढ़ा होगा, Iris डेटा को नार्मलाइज़ करना आवश्यक नहीं है। फिर भी, नार्मलाइज़ेशन और उसके प्रभाव का अध्ययन करना, और यह देखना कि इसे UDF के साथ-साथ keras के बिल्ट-इन normalize() फ़ंक्शन से कैसे किया जा सकता है, एक अच्छा विचार है।

अपना डेटा मैट्रिक्स में बदलने के बाद, आप वास्तव में keras पैकेज का उपयोग करके अपने डेटा पर संभावित नार्मलाइज़ेशन के प्रभाव का अध्ययन भी कर सकते हैं:

# Normalize the `iris` data
iris <- normalize(....[,1:4])

# Return the summary of `iris`
summary(....)

ध्यान दें कि यहाँ आप dimnames() का उपयोग iris के dimnames को NULL सेट करने के लिए करते हैं। यह सुनिश्चित करता है कि आपके डेटा में कोई कॉलम नाम न हों।

ट्रेनिंग और टेस्ट सेट

अब जब आपने अपने डेटा की गुणवत्ता जाँच ली है और आप जानते हैं कि अपने डेटा को नार्मलाइज़ करना आवश्यक नहीं है, तो आप मूल डेटा के साथ काम जारी रख सकते हैं और उसे ट्रेनिंग और टेस्ट सेट में बाँट सकते हैं ताकि आप आखिरकार अपना मॉडल बनाना शुरू कर सकें। ऐसा करके, आप बाद में अपने प्रेडिक्टेड मॉडल के प्रदर्शन का ईमानदार आकलन कर सकते हैं।

अपने डेटा को ट्रेनिंग और टेस्ट सेट में बाँटने से पहले, बेहतर होगा कि आप पहले एक seed सेट करें। आप set.seed() से यह आसानी से कर सकते हैं: इसी फ़ंक्शन का उपयोग करें और इसमें कोई भी यादृच्छिक पूर्णांक पास करें। एक seed, R के रैंडम नंबर जेनरेटर का एक नंबर होता है। seed सेट करने का बड़ा लाभ यह है कि आप जब भी समान seed देंगे, तो रैंडम नंबर जेनरेटर वही रैंडम नंबरों का क्रम देगा।

यह आपके कोड की पुनरुत्पादकता के लिए बेहतरीन है!

आप sample() फ़ंक्शन का उपयोग करके एक सैंपल लेते हैं जिसका आकार Iris डेटासेट की पंक्तियों की संख्या, यानी 150, के बराबर है। आप replacement के साथ सैंपल लेते हैं: आप 2 एलिमेंट वाले वेक्टर से चुनते हैं और Iris डेटासेट की 150 पंक्तियों में से प्रत्येक को 1 या 2 असाइन करते हैं। एलिमेंट्स का असाइनमेंट 0.67 और 0.33 की probability वेट्स के अधीन है।

# Determine sample size
ind <- sample(2, nrow(....), replace=TRUE, prob=c(0.67, 0.33))

# Split the `iris` data
iris.training <- ....[ind==1, 1:4]
iris.test <- iris[ind==2, 1:4]

# Split the class attribute
iris.trainingtarget <- iris[...==1, 5]
iris.testtarget <- iris[ind==2, 5]

sample() फ़ंक्शन का replace आर्ग्युमेंट TRUE पर सेट है, जिसका अर्थ है कि आप किसी विशेष पंक्ति को 1 या 2 असाइन करते हैं और फिर 2 के वेक्टर को उसकी मूल अवस्था में रीसेट करते हैं।

दूसरे शब्दों में, आपके डेटा सेट की अगली पंक्तियों के लिए, आप हर बार फिर से 1 या 2 असाइन कर सकते हैं। 1 या 2 चुनने की संभावना शेष आइटमों के बीच वेट्स के अनुपात में नहीं होनी चाहिए, इसलिए आप probability वेट्स निर्दिष्ट करते हैं।

साइड नोट: यदि आप किसी बिल्ट-इन डेटासेट का उपयोग करते, जैसे कि dataset_imdb() फ़ंक्शन के साथ, उदाहरण के लिए, तो आपका डेटा $ ऑपरेटर का उपयोग करके आसानी से विभाजित किया जा सकता है:

x_train <- imdb$train$x
y_train <- imdb$train$y
x_test <- imdb$test$x
y_test <- imdb$test$y

वन-हॉट एनकोडिंग

आपने सफलतापूर्वक अपना डेटा विभाजित कर लिया है, लेकिन मॉडल बनाना शुरू करने के लिए अभी भी एक चरण बाकी है। क्या आप अंदाज़ा लगा सकते कौन-सा?

जब आप न्यूरल नेटवर्क के साथ मल्टी-क्लास क्लासिफिकेशन समस्याओं का मॉडल बनाना चाहते हैं, तो आम तौर पर यह अच्छा अभ्यास है कि आप अपने टार्गेट एट्रीब्यूट को उस वेक्टर से बदलें जिसमें प्रत्येक क्लास वैल्यू के लिए मान होते हैं, ऐसे मैट्रिक्स में जो प्रत्येक क्लास वैल्यू के लिए बूलियन दर्शाता है और यह भी कि दिए गए उदाहरण में वह क्लास वैल्यू है या नहीं।

यह वन-हॉट एनकोडिंग (OHE) की एक ढीली व्याख्या है। यह थोड़ा जटिल लगता है, है न?

खुशकिस्मती से, keras पैकेज में to_categorical() फ़ंक्शन है जो यह सब आपके लिए कर देगा; iris.trainingtarget और iris.testtarget को इस फ़ंक्शन में पास करें और परिणाम को iris.trainLabels और iris.testLabels में स्टोर करें:

# One hot encode training target values
iris.trainLabels <- to_categorical(...................

# One hot encode test target values
iris.testLabels <- to_categorical(...............)

# Print out the iris.testLabels to double check the result
print(.............)

अब आप औपचारिक रूप से इस ट्यूटोरियल में अन्वेषण और प्रीप्रोसेसिंग चरणों के अंत तक पहुँच चुके हैं। अब आप keras के साथ अपना न्यूरल नेटवर्क बनाने के लिए आगे बढ़ सकते हैं!

मॉडल का निर्माण

मॉडल बनाना शुरू करने के लिए, आपको पहले keras_model_sequential() फ़ंक्शन की मदद से एक सीक्वेंशियल मॉडल इनिशियलाइज़ करना चाहिए। फिर, आप मॉडलिंग शुरू करने के लिए तैयार हैं।

हालाँकि, शुरू करने से पहले, इस डेटासेट के बारे में अपने मूल प्रश्न पर वापस जाना अच्छा विचार है: क्या आप किसी विशेष आइरिस फूल की स्पीशीज़ का पूर्वानुमान लगा सकते हैं? संख्यात्मक डेटा के साथ काम करना आसान होता है, और आपने डेटा को प्रीप्रोसेस किया है और टार्गेट वेरिएबल के मानों को वन-हॉट एनकोड किया है: कोई फूल या तो versicolor, setosa या virginica प्रकार का होता है और यह बाइनरी 1 और 0 मानों से परिलक्षित होता है।

ऐसी समस्या पर अच्छा प्रदर्शन करने वाली नेटवर्क की एक किस्म मल्टी-लेयर पर्सेप्ट्रॉन है। इस प्रकार का न्यूरल नेटवर्क अक्सर फुली-कनेक्टेड होता है। इसका मतलब है कि आप इस समस्या को हल करने के लिए फुली-कनेक्टेड लेयर्स का एक अपेक्षाकृत सरल स्टैक बनाना चाहते हैं। जहाँ तक एक्टिवेशन फ़ंक्शंस की बात है, परिचयात्मक उद्देश्य के लिए यहाँ सबसे सामान्य में से एक का उपयोग करना बेहतर है—relu एक्टिवेशन फ़ंक्शन। यह रेक्टिफ़ायर एक्टिवेशन फ़ंक्शन hidden लेयर में उपयोग किया जाता है, जो सामान्यतः अच्छा अभ्यास है।

इसके अलावा, आप देखते हैं कि आउटपुट लेयर में softmax एक्टिवेशन फ़ंक्शन का उपयोग किया गया है। आप ऐसा इसलिए करते हैं ताकि आउटपुट मान 0 और 1 की सीमा में हों और उन्हें प्रेडिक्टेड प्रॉबेबिलिटी के रूप में उपयोग किया जा सके:

# Initialize a sequential model
model <- ......................

# Add layers to the model
model %>% 
    layer_dense(units = 8, activation = 'relu', input_shape = c(4)) %>% 
    layer_dense(units = 3, activation = 'softmax')

ध्यान दें कि आउटपुट लेयर 3 आउटपुट मान बनाती है, प्रत्येक Iris क्लास (versicolor, virginica या setosa) के लिए एक। दूसरी ओर, पहली लेयर, जिसमें 8 hidden नोड्स हैं, का input_shape 4 है। ऐसा इसलिए है क्योंकि आपके ट्रेनिंग डेटा iris.training में 4 कॉलम हैं।

आप अपने मॉडल का आगे निरीक्षण निम्नलिखित फ़ंक्शंस से कर सकते हैं:

  • summary() फ़ंक्शन का उपयोग करके आप अपने मॉडल का एक सारांश प्रतिनिधित्व प्रिंट कर सकते हैं;
  • get_config() एक सूची लौटाएगा जिसमें मॉडल का कॉन्फ़िगरेशन शामिल होगा;
  • get_layer() लेयर कॉन्फ़िगरेशन लौटाएगा।
  • layers एट्रीब्यूट का उपयोग मॉडल की लेयरों की फ्लैट लिस्ट प्राप्त करने के लिए किया जा सकता है;
  • इनपुट टेन्सर्स की सूची के लिए, आप inputs एट्रीब्यूट का उपयोग कर सकते हैं; और
  • अंत में, आउटपुट टेन्सर्स प्राप्त करने के लिए, आप outputs एट्रीब्यूट का उपयोग कर सकते हैं।
# Print a summary of a model
summary(model)

# Get model configuration
get_config(model)

# Get layer configuration
get_layer(model, index = 1)

# List the model's layers
model$layers

# List the input tensors
model$inputs

# List the output tensors
model$outputs

Compile and Fit the Model

Now that you have set up the architecture of your model, it’s time to compile and fit the model to the data. To compile your model, you configure the model with the adam optimizer and the categorical_crossentropy loss function. Additionally, you also monitor the accuracy during the training by passing 'accuracy' to the metrics argument.

# Compile the model
model %>% compile(
     loss = 'categorical_crossentropy',
     optimizer = 'adam',
     metrics = 'accuracy'
 )

The optimizer and the loss are two arguments that are required if you want to compile the model.

Some of the most popular optimization algorithms used are the Stochastic Gradient Descent (SGD), ADAM and RMSprop. Depending on whichever algorithm you choose, you’ll need to tune certain parameters, such as learning rate or momentum. The choice for a loss function depends on the task that you have at hand: for example, for a regression problem, you’ll usually use the Mean Squared Error (MSE).

As you see in this example, you used categorical_crossentropy loss function for the multi-class classification problem of determining whether an iris is of type versicolor, virginica or setosa. However, note that if you would have had a binary-class classification problem, you should have made use of the binary_crossentropy loss function.

Next, you can also fit the model to your data; In this case, you train the model for 200 epochs or iterations over all the samples in iris.training and iris.trainLabels, in batches of 5 samples.

# Fit the model 
model %>% fit(
     iris.training, 
     iris.trainLabels, 
     epochs = 200, 
     batch_size = 5, 
     validation_split = 0.2
 )

Tip if you want, you can also specify the verbose argument in the fit() function. By setting this argument to 1, you indicate that you want to see progress bar logging.

What you do with the code above is training the model for a specified number of epochs or exposures to the training dataset. An epoch is a single pass through the entire training set, followed by testing of the verification set. The batch size that you specify in the code above defines the number of samples that going to be propagated through the network. Also, by doing this, you optimize efficiency because you make sure that you don’t load too many input patterns into memory at the same time.

Visualize the Model Training History

Also, it’s good to know that you can also visualize the fitting if you assign the lines of code in the DataCamp Light chunk above to a variable. You can then pass the variable to the plot() function, as you see in this particular code chunk!

# Store the fitting history in `history` 
history <- model %>% fit(
     iris.training, 
     iris.trainLabels, 
     epochs = 200,
     batch_size = 5, 
     validation_split = 0.2
 )

# Plot the history
plot(history)

Make sure to study the plot in more detail.

plot

At first sight, it’s no surprise that this all looks a tad messy. You might not entirely know what you’re looking at, right?

One good thing to know is that the loss and acc indicate the loss and accuracy of the model for the training data, while the val_loss and val_acc are the same metrics, loss and accuracy, for the test or validation data.

But, even as you know this, it’s not easy to interpret these two graphs. Let’s try to break this up into pieces that you might understand more easily! You’ll split up these two plots and make two separate ones instead: you’ll make one for the model loss and another one for the model accuracy. Luckily, you can easily make use of the $ operator to access the data and plot it step by step.

Check out the DataCamp Light box below to see how you can do this:

# Plot the model loss of the training data
plot(history$metrics$loss, main="Model Loss", xlab = "epoch", ylab="loss", col="blue", type="l")

# Plot the model loss of the test data
lines(history$metrics$val_loss, col="green")

# Add legend
legend("topright", c("train","test"), col=c("blue", "green"), lty=c(1,1))

chart

In this first plot, you plotted the loss of the model on the training and test data. Now it’s time to also do the same, but then for the accuracy of the model:

# Plot the accuracy of the training data 
plot(history$metrics$acc, main="Model Accuracy", xlab = "epoch", ylab="accuracy", col="blue", type="l")

# Plot the accuracy of the validation data
lines(history$metrics$val_acc, col="green")

# Add Legend
legend("bottomright", c("train","test"), col=c("blue", "green"), lty=c(1,1))

model accuracy

Some things to keep in mind here are the following:

  • If your training data accuracy keeps improving while your validation data accuracy gets worse, you are probably overfitting: your model starts to just memorize the data instead of learning from it.
  • If the trend for accuracy on both datasets is still rising for the last few epochs, you can clearly see that the model has not yet over-learned the training dataset.

Predict Labels of New Data

Now that your model is created, compiled and has been fitted to the data, it’s time to actually use your model to predict the labels for your test set iris.test. As you might have expected, you can use the predict() function to do this. After, you can print out the confusion matrix to check out the predictions and the real labels of the iris.test data with the help of the table() function.

# Predict the classes for the test data
classes <- model %>% predict_classes(iris.test, batch_size = 128)

# Confusion matrix
table(iris.testtarget, classes)

What do you think of the results? At first sight, does this model that you have created make the right predictions?

Evaluating your Model

Even though you already have a slight idea of how your model performed by looking at the predicted labels for iris.test, it’s still important that you take the time to evaluate your model. Use the evaluate() function to do this: pass in the test data iris.test, the test labels iris.testLabels and define the batch size. Store the result in a variable score, like in the code example below:

# Evaluate on test data and labels
score <- model %>% evaluate(iris.test, iris.testLabels, batch_size = 128)

# Print the score
print(score)

By printing score, you’ll get back the loss value and the metric value (in this case 'accuracy') back.

Fine-tuning your Model

Fine-tuning your model is probably something that you’ll be doing a lot, especially in the beginning, because not all classification and regression problems are as straightforward as the one that you saw in the first part of this tutorial. As you read above, there are already two key decisions that you’ll probably want to adjust: how many layers you’re going to use and how many “hidden units” you will choose for each layer.

In the beginning, this will really be quite a journey.

Besides playing around with the number of epochs or the batch size, there are other ways in which you can tweak your model in the hopes that it will perform better: by adding layers, by increasing the number of hidden units and by passing your own optimization parameters to the compile() function. This section will go over these three options.

Adding Layers

What would happen if you add another layer to your model? What if it would look like this?

# Initialize the sequential model
model <- keras_model_sequential() 

# Add layers to model
model %>% 
    layer_dense(units = 8, activation = 'relu', input_shape = c(4)) %>% 
    layer_dense(units = 5, activation = 'relu') %>% 
    layer_dense(units = 3, activation = 'softmax')

# Compile the model
model %>% compile(
     loss = 'categorical_crossentropy',
     optimizer = 'adam',
     metrics = 'accuracy'
 )

# Fit the model to the data
model %>% fit(
     iris.training, iris.trainLabels, 
     epochs = 200, batch_size = 5, 
     validation_split = 0.2
 )

# Evaluate the model
score <- model %>% evaluate(iris.test, iris.testLabels, batch_size = 128)

# Print the score
print(score)

Note that you can also visualize the loss and accuracy metrics of this new model! Try this out in the DataCamp Light chunk below:

# Initialize a sequential model
model <- keras_model_sequential() 

# Add layers to the model
model %>% 
    layer_dense(units = 8, activation = 'relu', input_shape = c(4)) %>% 
    layer_dense(units = 5, activation = 'relu') %>% 
    layer_dense(units = 3, activation = 'softmax')

# Compile the model
model %>% compile(
     loss = 'categorical_crossentropy',
     optimizer = 'adam',
     metrics = 'accuracy'
 )

# Save the training history in history
history <- model %>% fit(
  iris.training, iris.trainLabels, 
  epochs = 200, batch_size = 5,
  validation_split = 0.2
 )

# Plot the model loss
plot(history$metrics$loss, main="Model Loss", xlab = "epoch", ylab="loss", col="blue", type="l")
lines(history$metrics$val_loss, col="green")
legend("topright", c("train","test"), col=c("blue", "green"), lty=c(1,1))

# Plot the model accuracy
plot(history$metrics$acc, main="Model Accuracy", xlab = "epoch", ylab="accuracy", col="blue", type="l")
lines(history$metrics$val_acc, col="green")
legend("bottomright", c("train","test"), col=c("blue", "green"), lty=c(1,1))

deep learning model layers

Keras Layers model

Hidden Units

Also try out the effect of adding more hidden units to your model’s architecture and study the impact on the evaluation, just like this:

# Initialize a sequential model
model <- keras_model_sequential() 

# Add layers to the model
model %>% 
    layer_dense(units = 28, activation = 'relu', input_shape = c(4)) %>% 
    layer_dense(units = 3, activation = 'softmax')

# Compile the model
model %>% compile(
     loss = 'categorical_crossentropy',
     optimizer = 'adam',
     metrics = 'accuracy'
 )

# Fit the model to the data
model %>% fit(
     iris.training, iris.trainLabels, 
     epochs = 200, batch_size = 5, 
     validation_split = 0.2
 )

# Evaluate the model
score <- model %>% evaluate(iris.test, iris.testLabels, batch_size = 128)

# Print the score
print(score)

Note that, in general, this is not always the best optimization because, if you don’t have a ton of data, the overfitting can and will be worse. That’s why you should try to use a small network with small datasets like this one.

Why don’t you try visualizing the effect of the addition of the hidden nodes in your model? Try it out below:

# Initialize the sequential model
model <- keras_model_sequential() 

# Add layers to the model
model %>% 
    layer_dense(units = 28, activation = 'relu', input_shape = c(4)) %>% 
    layer_dense(units = 3, activation = 'softmax')

# Compile the model
model %>% compile(
     loss = 'categorical_crossentropy',
     optimizer = 'adam',
     metrics = 'accuracy'
 )

# Save the training history in the history variable
history <- model %>% fit(
  iris.training, iris.trainLabels, 
  epochs = 200, batch_size = 5, 
  validation_split = 0.2
 )

# Plot the model loss
plot(history$metrics$loss, main="Model Loss", xlab = "epoch", ylab="loss", col="blue", type="l")
lines(history$metrics$val_loss, col="green")
legend("topright", c("train","test"), col=c("blue", "green"), lty=c(1,1))

# Plot the model accuracy
plot(history$metrics$acc, main="Model Accuracy", xlab = "epoch", ylab="accuracy", col="blue", type="l")
lines(history$metrics$val_acc, col="green")
legend("bottomright", c("train","test"), col=c("blue", "green"), lty=c(1,1))

neural network model

hidden units ann

Optimization Parameters

Besides adding layers and playing around with the hidden units, you can also try to adjust (some of) the parameters of the optimization algorithm that you give to the compile() function. Up until now, you have always passed a vector with a string, adam, to the optimizer argument.

But that doesn’t always need to be like this!

Also, try out experimenting with other optimization algorithms, like the Stochastic Gradient Descent (SGD). Try, for example, using the optimizer_sgd() function to adjust the learning rate lr. Do you notice an effect?

# Initialize a sequential model
model <- keras_model_sequential() 

# Build up your model by adding layers to it
model %>% 
    layer_dense(units = 8, activation = 'relu', input_shape = c(4)) %>% 
    layer_dense(units = 3, activation = 'softmax')

# Define an optimizer
sgd <- optimizer_sgd(lr = 0.01)

# Use the optimizer to compile the model
model %>% compile(optimizer=sgd, 
                  loss='categorical_crossentropy', 
                  metrics='accuracy')

# Fit the model to the training data
model %>% fit(
     iris.training, iris.trainLabels, 
     epochs = 200, batch_size = 5, 
     validation_split = 0.2
 )

# Evaluate the model
score <- model %>% evaluate(iris.test, iris.testLabels, batch_size = 128)

# Print the loss and accuracy metrics
print(score)

Besides using another optimizer, you can also try using a smaller learning rate to train your network. This is one of the most common fine-tuning techniques; A common practice is to make the initial learning rate 10 times smaller than the one that you used to train the model before.

Let’s visualize the training history one more time to see the effect of this small adjustment:

# Define an optimizer
sgd <- optimizer_sgd(lr = 0.01)

# Compile the model
model %>% compile(optimizer=sgd, 
                  loss='categorical_crossentropy', 
                  metrics='accuracy')

# Fit the model to the training data
history <- model %>% fit(
  iris.training, iris.trainLabels, 
  epochs = 200, batch_size = 5, 
  validation_split = 0.2
 )

# Plot the model loss
plot(history$metrics$loss, main="Model Loss", xlab = "epoch", ylab="loss", col="blue", type="l")
lines(history$metrics$val_loss, col="green")
legend("topright", c("train","test"), col=c("blue", "green"), lty=c(1,1))

# Plot the model accuracy
plot(history$metrics$acc, main="Model Accuracy", xlab = "epoch", ylab="accuracy", col="blue", type="l")
lines(history$metrics$val_acc, col="green")
legend("bottomright", c("train","test"), col=c("blue", "green"), lty=c(1,1))

neural network model

hidden units ann

Saving, Loading or Exporting your Model

There is one last thing that remains in your journey with the keras package and that is saving or exporting your model so that you can load it back in at another moment.

  • Firstly, you can easily make use of the save_model_hdf5() and load_model_hdf5() functions to save and load your model into your workspace:
save_model_hdf5(model, "my_model.h5")
model <- load_model_hdf5("my_model.h5")
  • Additionally, you can also save and load the model weights with the save_model_weights_hdf5() and load_model_weights_hdf5() functions:
save_model_weights_hdf5("my_model_weights.h5")
model %>% load_model_weights_hdf5("my_model_weights.h5")
  • Lastly, it’s good to know that you can also export your model configuration to JSON or YAML. Here, the functions model_to_json() and model_to_yaml() will help you out. To load the configurations back into your workspace, you can just use the model_from_json() and model_from yaml() functions:
json_string <- model_to_json(model)
model <- model_from_json(json_string)

yaml_string <- model_to_yaml(model)
model <- model_from_yaml(yaml_string)

Learn Python for Data Science With DataCamp

Deep Learning with Keras

Congrats! You’ve made it through this deep learning tutorial in R with keras. This tutorial was just one small step in your deep learning journey with R; There’s much more to cover! If you haven’t taken DataCamp’s Deep Learning in Python course, you might consider doing so.

In the meantime, also make sure to check out the Keras documentation and the RStudio keras documentation if you haven’t done so already. You’ll find more examples and information on all functions, arguments, more layers, etc… Also, check out François Chollet’s book “Deep Learning with Python”. All these resources will undoubtedly be indispensable in learning how to work with neural networks in R!

विषय