<?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 Ahsana Rizky Mashura on Medium]]></title>
        <description><![CDATA[Stories by Ahsana Rizky Mashura on Medium]]></description>
        <link>https://medium.com/@ahsanarizkym?source=rss-b41a392ecd84------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*8OaFl0ITVhjf3JM_mKiBXg.jpeg</url>
            <title>Stories by Ahsana Rizky Mashura on Medium</title>
            <link>https://medium.com/@ahsanarizkym?source=rss-b41a392ecd84------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 03:45:45 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ahsanarizkym/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[Self Organizing Maps (SOM) Using R & Kohonen (case study: Wines dataset)]]></title>
            <link>https://ahsanarizkym.medium.com/self-organizing-maps-som-using-r-kohonen-case-study-wines-dataset-4bdbad42e41?source=rss-b41a392ecd84------2</link>
            <guid isPermaLink="false">https://medium.com/p/4bdbad42e41</guid>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[self-organizing-map]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[rstudio]]></category>
            <category><![CDATA[data-visualization]]></category>
            <dc:creator><![CDATA[Ahsana Rizky Mashura]]></dc:creator>
            <pubDate>Fri, 16 Jul 2021 18:05:56 GMT</pubDate>
            <atom:updated>2021-07-16T18:05:56.321Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/656/1*rOsdFtQdqgE4cdx2JmtWrA.jpeg" /></figure><p><strong><em>Hello Data Enthusiasts!</em></strong></p><p><em>This time we will try to demonstrate Self Organizing Maps (SOM) Using R &amp; Kohonen. We’re gonna use the Wines dataset. First thing first, let’s bond with this technology!</em></p><h3><em>Self Organizing Maps (SOM)</em></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/866/1*NavCyksLxoGPlVM-tUFcOA.png" /></figure><blockquote><em>Self Organizing Maps (SOM) algorithm is an NN method introduced by Professor Teuvo Kohonen in 1982. SOM is a topology form of Unsupervised Artificial Neural Network (Unsupervised ANN) where the training process does not require supervision (target output). SOM is used to group (cluster) data based on the characteristics or features of the data. -Shieh &amp; Liao, 2012.</em></blockquote><p><em>In the SOM algorithm, the input data is a vector consisting of n components (tuples) which will be grouped into a maximum of m groups (called sample vectors). The network output is the group that is closest to or similar to the given input. There are several measures of proximity that can be used. The measure that is often used is the minimum Euclidean distance (Siang, 2009).</em></p><p><em>SOM is the leading method of the artificial neural network approach to clustering, after competitive learning (Han &amp; Kamber 2001). SOM differs from competitive learning in that the nerves in one environment learn to recognize the environmental part of the input space. SOM recognizes the distribution (such as competitive learning) and the topology of the input vector through the training process (Demuth &amp; Beale 2003)</em></p><h3>Kohonen</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/517/1*F6oE6833h7qTbGRP0IFveQ.jpeg" /><figcaption>Teuvo Kohonen</figcaption></figure><p><em>Kohonen networks are a type of neural network that performs clustering, also known as a KNET or a self-organizing map. This type of network can be used to cluster the dataset into distinct groups when you don’t know what those groups are at the beginning. Records are grouped so that records within a group or cluster tend to be similar to each other, and records in different groups are dissimilar. -IBM</em></p><p><em>The basic units are </em><strong><em>neurons</em></strong><em>, and they are organized into two layers: the </em><strong><em>input layer</em></strong><em> and the </em><strong><em>output layer</em></strong><em> (also called the </em><strong><em>output map</em></strong><em>). All of the input neurons are connected to all of the output neurons, and these connections have </em><strong><em>strengths</em></strong><em>, or </em><strong><em>weights</em></strong><em>, associated with them. During training, each unit competes with all of the others to “win” each record. The output map is a two-dimensional grid of neurons, with no connections between the units.</em></p><p><em>Since we have learned the main ideas about SOM &amp; Kohonen, so it’s time for us to get to the main part of this article! There are several focuses that we would like to cover by demonstrating this analysis, so it would be very good to know the case study we’re doing today.</em></p><h3><em>SOM &amp; Kohonen in R Demonstration</em></h3><p><em>In the </em><a href="https://archive.ics.uci.edu/ml/datasets/wine"><strong><em>Wine Dataset</em></strong></a><em> available as open data in the</em><a href="https://archive.ics.uci.edu/ml/index.php"><strong><em> UCI Machine Learning</em></strong></a><em> Repository, there are 177 wines with 13 attributes as mentioned: alcohol, malic acid, ash, alkalinity of ash, magnesium, total phenols, flavonoids, non-flavanoids phenols, proanthocyanins, color intensity, hue, OD280/OD325 diluted wines, proline.</em></p><p><strong><em>a. First thing first, we need to install the “kohonen” package in RStudio. This is the package that provides all the functions and the dataset that we require.</em></strong></p><blockquote>install.packages(“kohonen”)<br>library(kohonen)<br>search()<br>ls(2)</blockquote><p><strong><em>b. We can see the description &amp; structure of the Wine dataset using head(), scale(), dim(), and str().</em></strong></p><blockquote>data(wines)<br>head(wines)<br>scale(wines)<br>head(scale(wines))<br>dim(wines)<br>str(wines)</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/834/1*1BKvMTPRxIFICrjVpFwFXw.png" /></figure><p><em>Above we can see the packages, functions, &amp; some of the top data from the 13 attributes in the Wine Dataset available as open data in the UCI Machine Learning Repository and here are parts of the scaled data:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/879/1*K8nIo0uW4uJnmXjYDrr9bA.png" /></figure><p><em>The structure of the object “som.wines”:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/929/1*2JGEWp9lJ6Jd1orv2yNWcw.png" /></figure><p><strong><em>c. Next, we will build the SOM map.</em></strong></p><blockquote>grid = somgrid(xdim = 5, ydim = 5, topo = “hexagonal”)<br>som.wines = som(scale(wines),grid = somgrid(xdim = 5, ydim = 5,<br> “hexagonal”))<br>str(som.wines)<br>plot(som.wines, type = “mapping”)</blockquote><p><em>The following is the output mapping plot, where 177 wines are grouped into 25 circles. There are 5 rows and 5 circles per row.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/883/1*tvV_fV5mbnYMfufYSk6otg.png" /></figure><p><strong>d. Grouping wines data into mapping plots.</strong></p><blockquote>som.wines$grid$pts<br>som.wines$unit.classif<br>plot(som.wines)</blockquote><p><em>Grouping of 177 wines data into 25 circles. So in “unit.classif” there is no number greater than 25 because there are only 25 circles in the mapping plot. Examples of how to read it are: the seventh data goes into circle 19, the eighth data goes into circle 20, and so on.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/582/1*m3z4cuLxQWEMadN8hjTvjQ.png" /></figure><p><strong><em>e. Making mapping plots with text.</em></strong></p><blockquote>text(som.wines$grid$pts, labels = som.wines$unit.classif, cex = 1.5)<br>str(som.wines)<br>som.wines$codes[[1]]<br>hclust(dist(som.wines$codes[[1]]))<br>peta = cutree(hclust(dist(som.wines$codes[[1]])), 5)<br>plot(peta)<br>plot(som.wines, type = “codes”, bgcol = rainbow(5)<br> [peta])</blockquote><p><em>Output data wines grouped in 25 circles, marked with codes: V1, V2, V3, V4, V5, V6, V7, V8, V9, V10, V11, V12, V13, V14, V15, V16, V17, V18, V19, V20, V21, V22, V23, V24, and V25.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/577/1*7COrhfD-r7NZLfRb_bGVEw.png" /></figure><p><em>Codes plot shows the location of each object grouped by variable. For example: in the 25th circle/group, the size of the perianth variable is very large, followed by ash alkalinity, ash, alcohol, and malic acid. Plot color shows variable description</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/495/1*QYnhhTyhNiDKjsAw4UanjQ.png" /></figure><p><em>Codes plot shows the location of each object grouped by variable. The way to read it is the same as the code plot without text, the difference lies in the addition of the index of the wines object in the circle. Because there is so much data, the text overlaps.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/517/1*DB2sSIeyfCCbT3KdwfhkbA.png" /></figure><p><strong><em>f. Output clustering using Euclidean distance and output “unit.classif”.</em></strong></p><blockquote>add.cluster.boundaries(som.wines,peta)<br>som.wines$unit.classif</blockquote><p><strong><em>g. Predict new data &amp; making the codes plot</em></strong></p><blockquote>uji = c(1.03, -0.68, 0.92, 0.144, 1.08, 1.04, 1.37, 0.302, 0.23, 0.664, 0.755, -0.048, 1.22)<br>uji<br>dim(wines)<br>dim(uji)<br>class(wines)<br>class(uji)<br>ujimatrix = as.matrix(uji)<br>class(ujimatrix)<br>dim(ujimatrix)<br>dim(ujimatrix) = c(1, 13)<br>dim(ujimatrix)</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/554/1*hHK6EV8AH8Oqgn2uVQOt6A.png" /></figure><p><em>Based on the results above, it is known that the new data entered was in the 16th circle object, with a distances value of 311.1677.</em></p><p><strong><em>f. Final SOM plot &amp; conclusion.</em></strong></p><blockquote>map(som.wines, scale(ujimatrix, center = attr(scale(wines), “scaled:center”), scale = attr(scale(wines), “scaled:scale”)))</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/698/1*i6q8DDqH4DIfrJSaUxPbIw.png" /></figure><p><em>The final plot codes show grouping by map. Purple (2), Dark blue (1), Green (4), Red (8), Yellow (10). These plot codes can be referred to as models obtained from SOM.</em></p><p><strong>BIG THANKS FOR:</strong></p><ul><li><a href="https://medium.com/@BAYUGALIH/self-organizing-maps-som-dengan-kohonen-pada-r-part-1-b106b6f377c6">Self -Organizing Maps (SOM) dengan Kohonen pada R— Part 1</a></li><li><a href="https://www.ibm.com/docs/en/spss-modeler/18.1.1?topic=models-kohonen-node">Kohonen Node</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4bdbad42e41" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementation of k-NN & Machine Learning to Build Document Classification System in R]]></title>
            <link>https://medium.com/analytics-vidhya/implementation-of-k-nn-machine-learning-to-build-document-classification-system-in-r-10e28e56c657?source=rss-b41a392ecd84------2</link>
            <guid isPermaLink="false">https://medium.com/p/10e28e56c657</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[knn]]></category>
            <category><![CDATA[rstudio]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[r]]></category>
            <dc:creator><![CDATA[Ahsana Rizky Mashura]]></dc:creator>
            <pubDate>Fri, 16 Jul 2021 13:45:56 GMT</pubDate>
            <atom:updated>2021-08-01T15:16:55.464Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8F0rX1YutUXcckkuVTTEnQ.png" /><figcaption>source: Docentric AX</figcaption></figure><p><strong><em>Hello Data Enthusiasts!</em></strong></p><p><em>The other day, while I was surfing YouTube looking for interesting topics about k-NN, I came across a cool tutorial from Tim D’Auria entitled “</em><a href="https://www.youtube.com/watch?v=j1V2McKbkLo"><strong><em>How to Build a Text Mining, Machine Learning Document Classification System in R!</em></strong></a><em>” and right then and there I decided to put it into practice!</em></p><p><em>This time we will try to implement the K-Nearest Neighbor (k-NN) algorithm and Machine Learning to build a document classification system in R/RStudio. First thing first, let’s bond with this technology!</em></p><h3><em>k-Nearest Neighbor (k-NN)</em></h3><p><em>k-Nearest Neighbor algorithm is a supervised learning algorithm where the results of the new instance are classified according to the majority of the k-nearest neighbor categories. The purpose of this algorithm is to classify new objects based on attributes and samples of training data. The k-Nearest Neighbor algorithm uses the Neighborhood Classification as the predictive value of the new instance value.</em></p><p><em>For example, let’s just say I have the body measurements of 20 teenagers in a dataset, then I need to determine which clothes size fits each of them the best. Their school only wants 3 different sizes, they are Small (S), Medium (M), and Large (L). The measurements said are height and weight and then I classify these teenagers into 3 groups based on their measurements. Two days later, I found out that a teenager showed up late to the measuring and now I need to put him into one of those groups without ruining the already existing data. Here’s where I can use k-NN to find his closest neighbors in terms of body measurements.</em></p><p><em>There are 3 steps in k-NN : (1) First, we must determine the number of neighbors that we will count (k), (2) Calculate the distance of each neighbor to the object, then sort the results by distance, starting from the smallest to the largest, (3) Take (k) neighbors who are closest, then we see whether each of the neighbors is included in the classification.</em></p><p><em>In determining the value of k, </em><strong><em>if the number of our classifications is even</em></strong><em> then we should use </em><strong><em>an odd value of k</em></strong><em>, and i</em><strong><em>f the number of our classifications is odd</em></strong><em> then we should use an </em><strong><em>even value of k</em></strong><em> because otherwise, there is a possibility that we will not get a result</em>.</p><h3>Machine Learning</h3><p><em>Machine learning (ML) technology is a machine developed to be able to learn by itself without direction from its users. Machine learning is developed based on other disciplines such as statistics, mathematics, and data mining so that machines can learn by analyzing data without needing to be reprogrammed or ordered.</em></p><p><em>In this case, machine learning has the ability to obtain existing data with its own commands. ML can also study the existing data and the data it obtains so that it can perform certain tasks. The tasks that can be done by ML are also very diverse, depending on what he learns.</em></p><p>A. SUPERVISED LEARNING</p><p><em>Supervised learning technique is a technique that you can apply to machine learning that can receive information that already exists in the data by giving certain labels. It is hoped that this technique can provide a target for the output made by comparing past learning experiences.</em></p><p>B. UNSUPERVISED LEARNING</p><p><em>Unsupervised learning techniques are techniques that you can apply to machine learning that is used on data that does not have information that can be applied directly. It is expected that this technique can help find hidden structures or patterns in unlabeled data. This one is slightly different from supervised learning because you do not have any data that will be used as a reference beforehand.</em></p><h3>Implementing k-NN &amp; Machine Learning to Build Document Classification System</h3><p><em>Now that we’ve grasped the initial ideas of k-NN &amp; ML, let’s get to the point! We are going to input documents, build a system, and classify/predict to whom a document belongs (author name). By recognizing the documents’ pattern, this system is expected to identify the speaker of unmarked presidential campaign speeches.</em></p><p><strong><em>a. We’re gonna use Barack Obama’s &amp; Mitt Romney’s speeches as the documents I’m about to classify. You can obtain the speech scripts here: </em></strong><a href="http://obamaspeeches.com/"><strong><em>Obama</em></strong></a><strong><em>, </em></strong><a href="https://s3.documentcloud.org/documents/6768911/Romney-RemarksPreparedForDelivery.pdf"><strong><em>Romney1</em></strong></a><strong>, </strong><a href="https://www.pri.org/stories/2012-01-11/mitt-romney-new-hampshire-primary-victory-speech"><strong><em>Romney2</em></strong></a><strong><em> (you can also add/replace the speeches with ones you already have for other candidates). We’ll copy the speeches into my Notepad &amp; stored them in text (.txt) format.</em></strong></p><p><strong><em>b. Make a directory for each script and store them into 2 different folders (1 for Obama &amp; 1 for Romney). Here’s what I got:</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uLJnXX8l-seoPHb1UIWAug.png" /><figcaption>example: “ObamaSpeeches1.txt” displayed by Notepad</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lP7-A0dzSlgrStqyU8lXyA.png" /><figcaption>example: inside Obama’s folder</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qDi487m-Q37DWUey3XcdSg.png" /><figcaption>example: Romney’s folder</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VjxOSgqKfAqjWDJOUPkP0Q.png" /><figcaption>example of the folders</figcaption></figure><p><strong>c. <em>Initialize our environment. We need to give information to the system what are the libraries or the directories we’re gonna be using. Load the libraries that we intend to use the functions from: “tm”, “plyr”, and “class”</em></strong></p><p><em>Library “tm” comes from a package from R with the same name, tm itself stands for </em><a href="https://cran.r-project.org/web/packages/tm/vignettes/tm.pdf"><strong><em>Text Mining</em></strong></a><strong><em>. </em></strong><em>The main structure for managing documents in tm is a so-called Corpus, representing a collection of text documents. A corpus is an abstract concept, and there can exist several implementations in parallel. Library “plyr” comes from the </em><a href="https://cran.r-project.org/web/packages/plyr/plyr.pdf"><strong><em>PLYR</em></strong></a><em> package. It’s a </em>set of tools that solves a common set of problems: <em>you need to break a big problem down into manageable pieces, operate on each piece, and then put all the pieces back together. And then we also need to activate the “</em><a href="https://cran.r-project.org/web/packages/class/class.pdf"><strong><em>class</em></strong></a><em>” library that contains various functions for classification, including k-Nearest Neighbor, Learning Vector Quantization, and Self-Organizing Maps.</em></p><blockquote>#initialize environtment<br>libs = c(“tm”, “plyr”, “class”)<br>lapply(libs, require, character.only = TRUE)</blockquote><p><strong>d. <em>When you read text data into R, it occasionally converts it from text/string/character into nominal/categorical variables. We don’t wanna that to happen here, we’re about to keep it as it is. So we set off the parameter “stringAsFactors”</em>.</strong></p><blockquote>#set options<br>options(stringsAsFactors = FALSE)</blockquote><p><strong>e. <em>Moving on, let’s specify the names of our directories that we’ve created previously and the path to get there.</em></strong></p><blockquote>#set parameters<br>candidates = c(“romney”, “obama”)</blockquote><blockquote>#example of path to get to our directory <br>pathname = “D:/Ahsana’s Archive/PENGANTAR DATA MINING/Text Mining &amp; Classification”</blockquote><p><strong>f. <em>Then we will clean the text because texting is inherently “dirty”. A lot of things need to get “cleaned up” in order for the system to perform nicely. Because we have 2 candidates (Obama &amp; Romney), might as well make a function so it can be applied to several candidates.</em></strong></p><p><strong><em>This function takes all the speeches from all of our directories and incorporates them in one candidate per corpus.</em></strong></p><blockquote>#clean text function<br>cleanCorpus = function(corpus) { #pass in corpus<br> corpus.tmp = tm_map(corpus, removePunctuation) #to remove punctuations<br> corpus.tmp = tm_map(corpus.tmp, stripWhitespace) #to remove white spaces<br> corpus.tmp = tm_map(corpus.tmp, content_transformer(tolower)) #lowercase</blockquote><blockquote>#remove parts of speeches that don’t have to much meaning<br> corpus.tmp = tm_map(corpus.tmp, removeWords, stopwords(“english”))</blockquote><blockquote>#give the result <br> return(corpus.tmp)<br>}</blockquote><p><strong>g. <em>When we’re done with cleaning the text, we will build what’s called a Term Document Matrix (TDM), this thing is the thing that works magic to convert text into quantitative format (which we can analyze!)</em></strong></p><blockquote>#build TDM<br>generateTDM = function(cand, path) {<br> s.dir = sprintf(“%s/%s”, path, cand) #print to variables together<br> s.cor = VCorpus(DirSource(directory = s.dir), readerControl = list(reader=readPlain)) <br> s.cor.cl = cleanCorpus(s.cor) #apply clean-up function to corpus<br> s.tdm = TermDocumentMatrix(s.cor.cl)</blockquote><blockquote>#set an acceptable level of sparseness and remove the rest<br> s.tdm = removeSparseTerms(s.tdm, 0.7) <br> result = list(name = cand, tdm = s.tdm)<br>}</blockquote><blockquote>tdm = lapply(candidates, generateTDM, path = pathname)</blockquote><p><strong>h. <em>Attach each of the candidates’ names to the TDM.</em></strong></p><blockquote>#attach name<br>bindCandidateToTDM = function(tdm) {</blockquote><blockquote>#convert TDM into numeric, each speech as row and each term as column<br> s.mat = t(data.matrix(tdm[[“tdm”]]))</blockquote><blockquote>#convert matrix into data frame<br> s.df = as.data.frame(s.mat, stringsAsFactors = FALSE)<br> <br> s.df = cbind(s.df, rep(tdm[[“name”]], nrow(s.df)))<br> colnames(s.df)[ncol(s.df)] = “targetcandidate”<br> return(s.df)<br>}</blockquote><blockquote>candTDM = lapply(tdm, bindCandidateToTDM)<br>str(candTDM)</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/439/1*Hb3QCvO03jp6v0igzyjsXA.png" /><figcaption>str(TDM)</figcaption></figure><p><em>What we’re seeing up here is a list of the structure of each term that we have, where, and how many times are they being repeated.</em></p><p><strong>i.<em> Take the previous matrices and stack them on top of the other ’cause we’re gonna fit it all in one time into our model.</em></strong></p><blockquote>#stack<br>tdm.stack = do.call(rbind.fill, candTDM)</blockquote><blockquote>#replace NA’s or set NA’s equal to zero<br>tdm.stack[is.na(tdm.stack)] = 0<br>head(tdm.stack)</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/838/1*rexbZ1dJP0k6LVPAlc6yCA.png" /><figcaption>a few of the top words in TDM.stack</figcaption></figure><blockquote>nrow(tdm.stack)<br>ncol(tdm.stack)</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/386/1*pAZRTYUGYwtX-gVPd45RsA.png" /><figcaption>number of rows and columns of TDM.stack</figcaption></figure><p><em>So, now we know that we have 12 total speeches and 552 terms in total across the speeches.</em></p><p><strong>j. <em>Next, we’re gonna create a hold-out sample. A hold-out sample is a random sample from a data set that is withheld and not used in the model fitting process. After the model is fit to the main data (the “training” data), it is then applied to the hold-out sample. This gives an unbiased assessment of how well the model might do if applied to new data.</em></strong></p><ul><li><strong><em>NOTE:</em></strong><em> </em><strong><em>you can actually change the percentage of rows that you wish to include in the train set. Common combinations for train set : test set are 70% : 30%, 80% : 20%, or 75% : 25%. For me, I’ll set it as 75% (which later on I’m gonna explain why)</em></strong></li></ul><blockquote>#hold-out</blockquote><blockquote>#we take 75% of the rows to train the model<br>train.idx = sample(nrow(tdm.stack), ceiling(nrow(tdm.stack)*0.75))<br>test.idx = (1:nrow(tdm.stack))[-train.idx]</blockquote><blockquote>head(train.idx)<br>head(test.idx)</blockquote><p><strong>k. <em>Build k-NN model.</em></strong></p><blockquote>#k-NN model<br>tdm.cand = tdm.stack[, “targetcandidate”]<br>tdm.stack.nl = tdm.stack[, !colnames(tdm.stack) %in% “targetcandidate”]</blockquote><blockquote>knn.pred = knn(tdm.stack.nl[train.idx, ], tdm.stack.nl[test.idx, ], <br> tdm.cand[train.idx])</blockquote><p><strong>l. To c<em>ount the accuracy of our model’s prediction, we build a confusion matrix. It’s basically a matrix that shows how our model predicted the test set against the actual candidates who carried on the speeches.</em></strong></p><blockquote>#accuracy</blockquote><blockquote>#confusion matrix, consist of prediction result and actual candidate<br>conf.mat = table(“Predictions” = knn.pred, Actual = tdm.cand[test.idx])<br>conf.mat</blockquote><blockquote>(accuracy = sum(diag(conf.mat))/length(test.idx)*100)</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/560/1*jBKQRB6Zghg6CwhMnggy1A.png" /><figcaption>the output of confusion matrix &amp; model’s accuracy</figcaption></figure><p><em>The confusion matrix above explains that our model succeeded in predicting a speech that belongs to Obama &amp; 2 speeches that belong to Romney. If we count this, where we got 3 correctly predicted speeches from a total of 3 speeches in the test set, then we have (3/3)*100 which of course means 100. The accuracy of our model’s prediction is 100%! Eureka!</em></p><p><strong>SOME EXPLANATION <em>(*fingers crossed)</em></strong></p><p><em>There’s something that I need to say a little bit on why I chose the combination of train set : test set as 75% : 25%. I’ve tried other combinations as well:</em></p><ul><li><em>50% : 50% gave this result:</em></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/770/1*M1Sx6H1x4X4FyCIHLjhRdA.png" /></figure><p><em>Let’s count this, we got 4 correctly predicted speeches from a total of 6 speeches in the test set, then we have (4/6)*100 = 66,67 (or something around that). The accuracy of this model’s prediction is 66,67%</em></p><ul><li><em>80% : 20% gave this result:</em></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/778/1*5gzOXhh7sqZjlpK5E8sZSA.png" /></figure><p><em>Again get your calculator out, we got 2 correctly predicted speeches from a total of 3 speeches in the test set, then we have (2/3)*100 = 66,67. The accuracy of this model’s prediction is 66,67%</em></p><p><strong><em>The only reason </em></strong><em>I chose to put the 75% : 25% combination was because it gave </em><strong><em>the highest accuracy</em></strong><em> compared to the other two. It doesn’t necessarily mean the other combinations are bad. It just didn’t give the best result on my device (of course it might give different results from one device to the other).</em></p><p><strong>CONCLUSION</strong></p><p><em>Based on this trial, one of the weaknesses of classification methods that combines ML is that it may perform differently on different devices. To achieve a similar result, we can set some random numbers using set.seed(), then treat those random numbers as indexes of the train set or test set. If this still fails to reassure you getting similar results, try checking your R/RStudio’s random number generator. The other example of a method in which results may differ is ANN &amp; NNET. Here are the weaknesses of k-NN:</em></p><ul><li><em>Accuracy depends on the quality of the data</em></li><li><em>With large data, the prediction stage might be slow</em></li><li><em>Sensitive to the scale of the data and irrelevant features</em></li><li><em>Require high memory (need to store all of the training data)</em></li><li><em>Given that it stores all of the training, it can be computationally expensive</em></li></ul><p><em>However, The k-NN uses neighborhood classification as the prediction value of the new query. It has advantages: nonparametric architecture, </em><strong><em>simple and powerful</em></strong><em>, requires no training time.</em></p><p><strong><em>That’s it for this article, hope it helps you Data Enthusiasts! ^^</em></strong></p><p><strong>BIG THANKS FOR:</strong></p><ul><li><a href="https://medium.com/bee-solution-partners/cara-kerja-algoritma-k-nearest-neighbor-k-nn-389297de543e">Cara Kerja Algoritma k-Nearest Neighbor (k-NN)</a></li><li><a href="https://www.mygreatlearning.com/blog/knn-algorithm-introduction/">A Quick Introduction to KNN Algorithm</a></li><li><a href="https://www.projectrhea.org/rhea/index.php/KNN-K_Nearest_Neighbor_OldKiwi#:~:text=K%20Nearest%20Neighbors%20(KNN)&amp;text=The%20KNN%20uses%20neighborhood%20classification,classification%20and%20estimation%20are%20slow.">KNN-K Nearest Neighbor OldKiwi - Rhea</a></li><li><a href="https://stackoverflow.com/questions/21657575/what-does-this-mean-in-lme4-function-dataptr-not-provided-by-package-rcpp">What does this mean in lme4: function &#39;dataptr&#39; not provided by package &#39;Rcpp&#39;</a></li></ul><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fj1V2McKbkLo%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3Dj1V2McKbkLo&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2Fj1V2McKbkLo%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/01fbcd713d73ba90d902687ab6e560b2/href">https://medium.com/media/01fbcd713d73ba90d902687ab6e560b2/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=10e28e56c657" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/implementation-of-k-nn-machine-learning-to-build-document-classification-system-in-r-10e28e56c657">Implementation of k-NN &amp; Machine Learning to Build Document Classification System in R</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Face Recognition using OpenCV Module in Python (2)]]></title>
            <link>https://ahsanarizkym.medium.com/face-recognition-using-opencv-module-in-python-2-782ea8329767?source=rss-b41a392ecd84------2</link>
            <guid isPermaLink="false">https://medium.com/p/782ea8329767</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[face-recognition]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Ahsana Rizky Mashura]]></dc:creator>
            <pubDate>Sat, 09 Jan 2021 16:54:20 GMT</pubDate>
            <atom:updated>2021-01-09T16:54:20.259Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Hmqbvj-Y5jCkz5-53o8G_g.jpeg" /><figcaption>Source : The Official Microsoft Blog — Microsoft</figcaption></figure><p><strong><em>Hello Data Enthusiasts!</em></strong></p><p>Pada artikel sebelumnya, kita telah berhasil membangun sebuah sistem <em>face recognition </em>yang bisa mengenali 1 wajah. Kali ini kita akan mencoba melakukan pengenalan wajah (<em>face recognition</em>) menggunakan OpenCV di Python untuk 2 wajah.</p><p>Bagi teman-teman <em>Data Enthusiast</em> yang belum mengikuti pembuatan sistem <em>face recognition </em>dari awal, silahkan klik link <a href="https://ahsanarizkym.medium.com/face-recognition-using-opencv-module-in-python-2bad15b60b53">ini</a> ya!</p><h3>Implementasi Face Recognition untuk Mengenali 2 Wajah</h3><p>Bagaimana caranya agar sistem <em>face recognition </em>kita yang sebelumnya hanya mengenali 1 wajah, bisa mengenali 2 wajah? Pada dasarnya, <em>coding </em>yang akan kita gunakan adalah <em>coding </em>yang sama, kita hanya perlu menambahkan wajah baru kedalam <em>database </em>telah kita miliki. Yuk kita coba bersama!</p><p><strong>a. Buka folder tempat kita menyimpan kode-kode dan <em>database </em>sebelumnya, kemudian jalankan file “tangkapwajah.py” :</strong></p><pre>import cv2, time<br>camera = 0<br>video = cv2.VideoCapture(camera,cv2.CAP_DSHOW)<br>a = 0<br>faceDetect = cv2.CascadeClassifier(&#39;haarcascade_frontalface_default.xml&#39;)id = raw_input(&#39;masukkan id user &#39;)while True:<br>  a = a + 1  <br>  check, frame = video.read()  <br>  print(check)<br>  print(frame)  <br>  gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)    <br>  faces=faceDetect.detectMultiScale(gray,1.3,5);<br>  for (x,y,w,h) in faces:cv2.imwrite(&quot;DataSet/User.&quot;+str(id)+&quot;.&quot;+str(a)+&quot;.jpg&quot;,<br>    gray[y:y+h,x:x+w])<br>    cv2.rectangle(frame,(x,y),(x+w,y+h),(0,0,255),2)<br>  cv2.imshow(&quot;wajah&quot;,frame)<br>  #key = cv2.waitKey(1)  <br>  if (a&gt;24):<br>       break<br>  print(a)<br>video.release()<br>cv2.destroyAllWindows()</pre><p>Pastikan indentasi <em>coding </em>sesuai dengan gambar berikut :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/654/1*aqE3Eb8LBenG9I45ymWe-w.png" /></figure><p>Jalankan di <em>command prompt </em>dengan perintah :</p><pre>python tangkapwajah.py</pre><p>Jika berhasil maka akan muncul pertanyaan, “masukkan id user”. Karena kita sudah menggunakan “1” sebagai ID wajah pertama, contoh : pada artikel part 1, penulis mendefinisikan wajah penulis sendiri sebagai ID = 1. Maka, kita harus menggunakan ID yang berbeda, seperti 1, 2, 3, dst.</p><p>Sebagai contoh, penulis akan mencoba membuat sistem yang mengenali wajah penulis dan wajah ibu. Wajah ibu akan penulis definisikan dengan ID =2. Kita akan mendapatkan tangkapan layar dari wajah penulis dan wajah ibu dalam folder “DataBase”.</p><p><strong>b. Lakukan <em>training </em>menggunakan <em>database </em>wajah baru dengan menjalankan lagi “training.py” di <em>command prompt.</em></strong></p><p><em>Coding </em>secara lengkapnya adalah sebagai berikut :</p><pre>import cv2, os<br>import numpy as np<br>from PIL import Imagerecognizer = cv2.face.LBPHFaceRecognizer_create()<br>detector = cv2.CascadeClassifier(&quot;haarcascade_frontalface_default.xml&quot;);def getImagesWithLabels(path):<br>    imagePaths=[os.path.join(path,f) for f in os.listdir(path)] <br>    faceSamples=[]<br>    Ids=[]        <br>    for imagePath in imagePaths:<br>        pilImage=Image.open(imagePath).convert(&#39;L&#39;)<br>        imageNp=np.array(pilImage,&#39;uint8&#39;)<br>        Id=int(os.path.split(imagePath)[-1].split(&quot;.&quot;)[1])<br>        faces=detector.detectMultiScale(imageNp)<br>        for (x,y,w,h) in faces:<br>            faceSamples.append(imageNp[y:y+h,x:x+w])<br>            Ids.append(Id)<br>    return faceSamples, Idsfaces, Ids = getImagesWithLabels(&#39;DataSet&#39;)<br>recognizer.train(faces, np.array(Ids))<br>recognizer.save(&#39;training/training.xml&#39;)</pre><p>Pastikan indentasi <em>coding </em>sama dengan gambar berikut :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*P-gbYdmROtzscyoB.png" /></figure><p>Jalankan di <em>command prompt </em>dengan perintah :</p><pre>python training.py</pre><p><strong>c. Agar wajah baru secara otomatis dikenali oleh sistem setiap kali kita menjalankan <em>coding, </em>kita perlu jalankan lagi file “kenalwajah.py”. Namun karena wajah dalam <em>database </em>kita telah bertambah, maka kita tambahkan :</strong></p><pre>if (id==1):<br>   id = &quot;nama1&quot;<br>elif (id==2):<br>   id = &quot;nama2&quot;</pre><p>Karena nama penulis adalah Ahsana Rizky, maka penulis memasukkan id = “Ahsana Rizky” untuk id==1 dan memasukkan nama ibu kedalam id = “Siti Qomariyah” untuk id==2. Sehingga <em>coding </em>menjadi :</p><pre>import os<br>from PIL import Image<br>camera = 0<br>video = cv2.VideoCapture(camera,cv2.CAP_DSHOW)<br>a = 0<br>recognizer = cv2.face.LBPHFaceRecognizer_create()<br>faceDetect = cv2.CascadeClassifier(&#39;haarcascade_frontalface_default.xml&#39;)<br>recognizer.read(&#39;C://Users/ASUS/Downloads/fr1/training/training.xml&#39;)<br>id = 0<br>fontFace = cv2.FONT_HERSHEY_SIMPLEX<br>fontScale = 1<br>fontColor = (0,255,255)<br>while True:<br>  a = a + 1  <br>  check, frame = video.read()  <br>  print(check)<br>  print(frame)  <br>  gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)<br>  faces=faceDetect.detectMultiScale(gray,1.3,5);<br>  for (x,y,w,h) in faces:<br>      cv2.imwrite(&quot;DataSet/User.&quot;+str(id)+&quot;.&quot;+str(a)+&quot;.jpg&quot;, gray[y:y+h,x:x+w])<br>      cv2.rectangle(frame,(x,y),(x+w,y+h),(0,0,255),2)<br>      id, conf=recognizer.predict(gray[y:y+h,x:x+w])<br>      if (id == 1) :<br>        id = &#39;Ahsana Rizky&#39;<br>      elif (id == 2) :<br>        id = &#39;Siti Qomariyah&#39;<br>      cv2.putText(frame,str(id),(x+w,y+h),fontFace,fontScale,fontColor)<br>  cv2.imshow(&quot;wajah&quot;,frame)<br>  #key = cv2.waitKey(1)  <br>  if (cv2.waitKey(1)==ord(&#39;q&#39;)):<br>       break<br>  print(a)<br>video.release()<br>cv2.destroyAllWindows()</pre><p>Pastikan indentasi sesuai dengan gambar berikut :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/766/1*38zFiTP8FT30sLFPLqla0Q.png" /></figure><p>Jalankan di <em>command prompt </em>dengan perintah :</p><pre>python kenalwajah.py</pre><p>Berikut hasil akhirnya!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CY4CXi3xRzrv4VvDrFgdJw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*nd8zBQqfa4biNqCerG6vxQ.png" /></figure><p>Nah, begitulah hasil percobaan kita kali ini, teman-teman <em>Data Enthusiast! </em>Jika kalian tertarik untuk mempelajari <em>face recognition </em>lebih lanjut, silahkan cek referensi yang penulis cantumkan di akhir artikel ya!</p><p>Semoga bermanfaat dan sampai jumpa lagi!</p><p>Referensi :</p><ul><li><a href="https://medium.com/@986110101/pengenalan-wajah-4-a00b3213e49d">Pengenalan Wajah (4)</a></li><li><a href="https://www.pyimagesearch.com/2018/09/24/opencv-face-recognition/">OpenCV Face Recognition - PyImageSearch</a></li><li><a href="https://stackoverflow.com/questions/19876079/cannot-find-module-cv2-when-using-opencv">Cannot find module cv2 when using OpenCV</a></li></ul><p><a href="https://www.datacamp.com/community/tutorials/face-detection-python-opencv">https://www.datacamp.com/community/tutorials/face-detection-python-opencv</a></p><p>The Codacus, Face Recognition OpenCV — Training A Face Recognizer</p><p>“Capture Webcam with Python (opencv): Step by step”, Dr. Vytautas Bielinskas</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=782ea8329767" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Face Recognition using OpenCV Module in Python]]></title>
            <link>https://ahsanarizkym.medium.com/face-recognition-using-opencv-module-in-python-2bad15b60b53?source=rss-b41a392ecd84------2</link>
            <guid isPermaLink="false">https://medium.com/p/2bad15b60b53</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[face-recognition]]></category>
            <dc:creator><![CDATA[Ahsana Rizky Mashura]]></dc:creator>
            <pubDate>Sat, 09 Jan 2021 16:00:09 GMT</pubDate>
            <atom:updated>2021-01-09T16:55:06.776Z</atom:updated>
            <content:encoded><![CDATA[<h3>Face Recognition using OpenCV Module in Python (1)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dxGA0bE6-nAoU1n5VOcDvA.jpeg" /><figcaption>Source : Percento Technologies</figcaption></figure><p><strong><em>Hello Data Enthusiasts!</em></strong></p><p>Kali ini kita akan mencoba melakukan pengenalan wajah (<em>face recognition</em>) menggunakan OpenCV di Python. <em>Face recognition </em>yang akan kita coba termasuk implementasi sederhana dari banyaknya bentuk teknologi <em>recognition </em>yang lain. Sebelum masuk ke <em>coding </em>dan bagian intinya, yuk kita kenalan dulu dengan teknologi satu ini!</p><h3>Face Recognition</h3><p><em>Face recognition </em>adalah teknologi yang mampu mencocokkan wajah manusia dari gambar digital atau bingkai video dengan database wajah, biasanya digunakan untuk mengautentikasi pengguna melalui layanan verifikasi ID, bekerja dengan menunjukkan dan mengukur fitur wajah dari gambar tertentu. Meskipun awalnya merupakan bentuk aplikasi komputer, sistem pengenalan wajah telah digunakan secara luas belakangan ini pada ponsel cerdas dan dalam bentuk teknologi lain, seperti robotika.</p><p>Karena pengenalan wajah terkomputerisasi melibatkan pengukuran karakteristik fisiologis manusia, sistem pengenalan wajah dikategorikan sebagai biometrik. Meskipun keakuratan sistem pengenalan wajah sebagai teknologi biometrik lebih rendah daripada pengenalan iris dan pengenalan sidik jari, sistem ini diadopsi secara luas karena prosesnya yang tanpa kontak dan non-invasif. Sistem pengenalan wajah telah diterapkan dalam interaksi manusia-komputer tingkat lanjut, pengawasan video, dan pengindeksan gambar otomatis.</p><h3>Implementasi Face Recognition</h3><p>Setelah tau apa itu <em>face recognition </em>secara sederhana, kita akan masuk ke praktik menggunakan Python dari dasar ya!</p><p><strong>a. Pertama, kita download OpenCV terlebih dahulu. Penulis menggunakan OpenCV versi 4.5.0 ya. Teman-teman <em>Data Enthusiasts </em>bisa menggunakan versi yang sama, versi ter-<em>update </em>atau <em>simply </em>gunakan saja versi yang sesuai dengan versi Python kalian! Penulis cantumkan link <em>download</em> disini </strong><a href="https://opencv.org/releases/"><strong>download OpenCV 4.5.0.</strong></a></p><p>Pilih Windows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0C-Wg0ivRH4ZW3871msECA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6ClDZd-0hoBZ3r0xpwdUuQ.png" /></figure><p>OpenCV akan ter<em>download </em>secara otomatis.</p><p><strong>b. Bukalah <em>command prompt </em>dengan mengetikkan “cmd” di <em>folder </em>yang ingin kita jadikan <em>working directory. </em>Kemudian <em>input :</em></strong></p><pre>pip install numpy</pre><p><strong>c. Ekstrak <em>file </em>.zip OpenCV yang telah terunduh. Kemudian, carilah sebuah <em>file </em>bernama cv2.py. Pindahkan <em>file </em>tersebut kedalam <em>folder site-packages </em>yang ada di <em>folder </em>Python.</strong></p><p>Contoh : C:\Python\Python38–32\Lib\site-packages</p><p><strong>d. Buatlah 1 folder baru yang akan kita pakai untuk menyimpan kode-kode yang akan kita buat.</strong></p><p>Contoh :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/91/1*DiKc8_g9f6zG0GAHL55ZDQ.png" /><figcaption>Folder</figcaption></figure><p><strong>e. Bukalah <em>notepad++ </em>atau aplikasi sejenisnya, kemudian masukkan kode berikut :</strong></p><pre>import cv2, time</pre><pre>video = cv2.VideoCapture(0)<br>video.release()</pre><p>Simpan kode tersebut dengan nama, misal “tangkap.py”.</p><p><strong>f. Buka <em>command prompt </em>melalui folder yang telah kita buat, karena kita menginginkan folder ini menjadi <em>working directory </em>dan <em>output </em>akan otomatis tersimpan di dalamnya.</strong></p><p>Jalankan <em>“</em>tangkap.py” di <em>command prompt </em>menggunakan perintah :</p><pre>python tangkap.py</pre><p><strong>g. Apabila teman-teman tidak mengalami <em>error, </em>maka kita bisa lanjut untuk membuat <em>object frame</em> untuk menangkap gambar dari kamera. Perbarui “tangkap.py” seperti ini :</strong></p><pre>import cv2, time</pre><pre>video = cv2.VideoCapture(0)</pre><pre>check, frame = video.read()<br>print(check)<br>print(frame)</pre><pre>video.release()</pre><p>Jalankan di <em>command prompt.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/666/1*0MvhVcjNobViYNmwMgZ8GA.png" /></figure><p><strong>h. Jika hasil berbentuk matriks yang semua datanya 0 (nol) seperti gambar diatas, maka perbarui “tangkap.py” menjadi :</strong></p><pre>import cv2, time<br>camera = 0<br>video = cv2.VideoCapture(camera, cv2.CAP_DSHOW)<br>check, frame = video.read()<br>print(check)<br>print(frame)<br>video.release()</pre><p>Kemudian jalankan kembali dan akan didapatkan hasil sebagai berikut :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/976/1*GEB7WNZew7PkbYxgyD_Ukw.png" /></figure><p>Hasil diatas merupakan tangkapan layar dalam bentuk <em>pixel.</em></p><p><strong>i. Kemudian kita perbarui kembali kode di “tangkap.py”. Kita tambahkan perintah untuk menangkap satu kali <em>frame</em> gambar dan menambahkan perintah untuk keluar dari tangkapan gambar tersebut. Sehingga kita akan bisa melihat wajah kita yang terekam.</strong></p><pre>import cv2, time</pre><pre>camera = 0<br>video = cv2.VideoCapture(camera,cv2.CAP_DSHOW)</pre><pre>check, frame = video.read()<br>print(check)<br>print(frame)</pre><pre>cv2.imshow(&quot;tangkap&quot;, frame)<br>cv2.waitKey(0)</pre><pre><br>video.release()</pre><p>Jalankan “tangkap.py” di <em>command prompt.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/810/1*wuWflnw4OxNMN6TQ5dwwCw.png" /></figure><p><strong>j. Agar gambar terkonversi ke warna abu-abu (<em>gray</em>), perbarui kembali kode di “tangkap.py” menjadi :</strong></p><pre>import cv2, time</pre><pre>camera = 0<br>video = cv2.VideoCapture(camera, cv2.CAP_DSHOW)</pre><pre>check, frame = video.read()</pre><pre>print(check)<br>print(frame)</pre><pre>gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)</pre><pre>cv2.imshow(&quot;tangkap&quot;, gray)<br>cv2.waitKey(0)</pre><pre>video.release()</pre><p>Jalankan “tangkap.py” di <em>command prompt. </em>Kita akan mendapatkan hasil sebagai berikut :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/804/1*93UE_XILXRSt-jAwEPo79g.png" /></figure><p><strong>k. Untuk membuat tangkapan layar secara terus-menerus, perbarui kembali kode di “tangkap.py” menjadi :</strong></p><pre>import cv2, time<br>camera = 0<br>video = cv2.VideoCapture(camera,cv2.CAP_DSHOW)<br>a = 0<br>while True:<br>  a = a + 1  <br>  check, frame = video.read()  <br>  print(check)<br>  print(frame)  <br>  gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)       <br>  cv2.imshow(&quot;tangkap&quot;, gray)<br>  #cv2.waitKey(0)  <br>  key = cv2.waitKey(1)  <br>  if key == ord(&#39;q&#39;):<br>       break<br>print(a)<br>video.release()<br>cv2.destroyAllWindows()</pre><p>Pastikan indentasi sama seperti gambar berikut :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/518/1*wuqNBEV8lvNz07uk1UeF1w.png" /></figure><p>Jalankan “tangkap.py”. Apabila kode tidak <em>error,</em> kita akan mendapatkan hasil seperti ini :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*BvJcgrlahGY0Ti0I-fByZA.png" /></figure><p><strong>l. Karena kita sudah berhasil membuat komputer kita menangkap gambar wajah kita, maka langkah selanjutnya kita perlukan suatu algoritma untuk mendeteksi wajah dari keseluruhan gambar pada frame.</strong></p><p>Masukkan terlebih dahulu perintah untuk mendapatkan koding <em>classifying </em>wajah yang telah disediakan oleh OpenCV. Bukalah <em>link </em>berikut : <a href="https://github.com/opencv/opencv/tree/master/data/haarcascades">https://github.com/opencv/opencv/tree/master/data/haarcascades</a> dan simpan file “haarcascade_frontalface_default.xml” di folder yang telah kita buat sebelumnya.</p><p><strong>m. Masukkan kode berikut dan simpan dengan nama “tangkapwajah.py” di dalam folder yang sama, contoh : folder “fr1”.</strong></p><p>Dalam folder “fr1” akan terdapat 2 file baru, yaitu file “haarcascade_frontalface_default.xml” dan file “tangkapwajah.py”.</p><p><strong>n. Jalankan kode berikut di <em>command prompt.</em></strong></p><pre>python tangkapwajah.py</pre><p>Jika berhasil maka akan muncul seperti ini :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/798/1*qD7s61JnBjtil0KSS-Fj2g.png" /></figure><p><strong>o. Siapkan folder baru didalam “fr1” dengan nama “DataSet”.</strong></p><p><strong>p. Untuk mengidentifikasi nama pemilik wajah yang terdeteksi, kita perbarui “tangkapwajah.py” menjadi :</strong></p><pre>import cv2, time<br>camera = 0<br>video = cv2.VideoCapture(camera,cv2.CAP_DSHOW)<br>a = 0<br>faceDetect = cv2.CascadeClassifier(&#39;haarcascade_frontalface_default.xml&#39;)<br>id = raw_input(&#39;masukkan id user &#39;)<br>while True:<br>  a = a + 1  <br>  check, frame = video.read()  <br>  print(check)<br>  print(frame)  <br>  gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)    <br>  faces=faceDetect.detectMultiScale(gray,1.3,5);<br>  for (x,y,w,h) in faces:         <br>    cv2.imwrite(&quot;DataSet/User.&quot;+str(id)+&quot;.&quot;+str(a)+&quot;.jpg&quot;,<br>    gray[y:y+h,x:x+w])<br>    cv2.rectangle(frame,(x,y),(x+w,y+h),(0,0,255),2)<br>  cv2.imshow(&quot;wajah&quot;,frame)<br>  key = cv2.waitKey(1)  <br>  if key == ord(&#39;q&#39;):<br>       break<br>  print(a)<br>video.release()<br>cv2.destroyAllWindows()</pre><p>Jalankan di <em>command prompt </em>dengan perintah :</p><pre>python tangkapwajah.py</pre><p>Jika berhasil maka akan muncul pertanyaan, “masukkan id user”, ketiklah dengan angka “1”. Kita akan mendapatkan hasil :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*je5ti2ZnorIa9EYrppIvMg.png" /></figure><p>Proses ini akan terus berlangsung sampai huruf “q” pada keyboard ditekan (atau dengan menekan ctrl+C). Hasil tangkapan wajah akan tersimpan dalam : C:\Users\ASUS\Downloads\fr1\DataSet atau dalam folder “DataSet”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NTHtKVh0LwodikHjpHYZdA.png" /></figure><p><strong>q. Kita dapat pula membatasi tangkapan layar hingga maksimal 25 tangkapan layar agar tidak terlalu banyak. Perbarui “tangkapwajah.py” dengan kode berikut :</strong></p><pre>import cv2, time<br>camera = 0<br>video = cv2.VideoCapture(camera,cv2.CAP_DSHOW)<br>a = 0<br>faceDetect = cv2.CascadeClassifier(&#39;haarcascade_frontalface_default.xml&#39;)</pre><pre>id = raw_input(&#39;masukkan id user &#39;)</pre><pre>while True:<br>  a = a + 1  <br>  check, frame = video.read()  <br>  print(check)<br>  print(frame)  <br>  gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)    <br>  faces=faceDetect.detectMultiScale(gray,1.3,5);<br>  for (x,y,w,h) in faces:</pre><pre>cv2.imwrite(&quot;DataSet/User.&quot;+str(id)+&quot;.&quot;+str(a)+&quot;.jpg&quot;,<br>    gray[y:y+h,x:x+w])<br>    cv2.rectangle(frame,(x,y),(x+w,y+h),(0,0,255),2)<br>  cv2.imshow(&quot;wajah&quot;,frame)<br>  #key = cv2.waitKey(1)  <br>  if (a&gt;24):<br>       break<br>  print(a)<br>video.release()<br>cv2.destroyAllWindows()</pre><p>Pastikan indentasi sama seperti pada gambar berikut :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/654/1*aqE3Eb8LBenG9I45ymWe-w.png" /></figure><p>Jalankan di <em>command prompt </em>dengan :</p><pre>python tangkapwajah.py</pre><p><strong>r. Buatlah sebuah folder baru bernama “training” di dalam folder “fr1”.</strong></p><p><strong>s. Selanjutnya, kita akan mencoba mengenali gambar dalam folder “DataSet” atau kita akan melatih sistem untuk mengenali dengan tepat gambar wajah tersebut. Untuk melakukannya, kita membutuhkan sebuah algoritma <em>recognizer</em> yang telah disediakan oleh OpenCV :</strong></p><pre>recognizer = cv2.face.LBPHFaceRecognizer_create()</pre><p>Dengan fungsi perulangan untuk mempelajari mengenali gambar dan setiap labelnya :</p><pre>def getImagesWithLabels(path):</pre><p>Ambil gambar dari folder “DataSet” dan lakukan <em>training </em>menggunakan semua gambar yang ada :</p><pre>import osimagePaths=[os.path.join(path,f) for f in os.listdir(path)]</pre><p>Buat 2 definisi dua definisi yang didalamnya akan berisi gambar wajah dan labelnya.</p><pre>faceSamples = []<br>Ids = []</pre><p>Konversi ke skala <em>gray, </em>lalu <em>looping </em>digunakan untuk mempelajari wajah :</p><pre>for imagePath in imagePaths:<br>    pilImage=Image.open(imagePath).convert(&#39;L&#39;)</pre><p>Kita juga membutuhkan module untuk mengelola gambar bernama PIL (<em>Python Imaging Library</em>) yang digunakan untuk membuka, memanipulasi dan menyimpan gambar dari berbagai format file.</p><pre>from PIL import Imagefor imagePath in imagePaths:<br>    pilImage=Image.open(imagePath).convert(&#39;L&#39;)<br>    imageNp=np.array(pilImage,&#39;uint8&#39;)<br>    Id=int(os.path.split(imagePath)[-1].split(&quot;.&quot;)[1])<br>    faces=detector.detectMultiScale(imageNp)<br>    for (x,y,w,h) in faces:<br>        faceSamples.append(imageNp[y:y+h,x:x+w])<br>        Ids.append(Id)</pre><p><em>Coding </em>secara lengkapnya adalah sebagai berikut :</p><pre>import cv2, os<br>import numpy as np<br>from PIL import Image</pre><pre>recognizer = cv2.face.LBPHFaceRecognizer_create()<br>detector = cv2.CascadeClassifier(&quot;haarcascade_frontalface_default.xml&quot;);</pre><pre>def getImagesWithLabels(path):<br>    imagePaths=[os.path.join(path,f) for f in os.listdir(path)] <br>    <br>    faceSamples=[]<br>    Ids=[]    </pre><pre>    for imagePath in imagePaths:<br>        pilImage=Image.open(imagePath).convert(&#39;L&#39;)<br>        imageNp=np.array(pilImage,&#39;uint8&#39;)<br>        Id=int(os.path.split(imagePath)[-1].split(&quot;.&quot;)[1])<br>        faces=detector.detectMultiScale(imageNp)<br>        for (x,y,w,h) in faces:<br>            faceSamples.append(imageNp[y:y+h,x:x+w])<br>            Ids.append(Id)<br>    return faceSamples, Ids</pre><pre>faces, Ids = getImagesWithLabels(&#39;DataSet&#39;)<br>recognizer.train(faces, np.array(Ids))<br>recognizer.save(&#39;training/training.xml&#39;)</pre><p>Pastikan indentasi <em>coding </em>sama dengan gambar berikut :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*1dpxb7rZZJUP2I9UU7ebhw.png" /></figure><p>Simpan <em>coding </em>diatas dengan nama “training.py” di dalam folder “fr1” dan jalankan dengan perintah :</p><pre>python training.py</pre><p>Apabila <em>coding </em>tidak mengalami <em>error, </em>maka kita akan mendapatkan sebuah file baru bernama “training.xml”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/678/1*JQ4z41Mc2JFThfVTZVbWGg.png" /></figure><p><strong>t. Kita akan menambahkan sedikit perintah untuk pengenalan wajah agar wajah otomatis dikenali oleh sistem setiap kali kita menjalankan <em>coding.</em></strong></p><pre>import cv2, time<br>import os<br>from PIL import Imagecamera = 0<br>video = cv2.VideoCapture(camera,cv2.CAP_DSHOW)<br>a = 0<br>recognizer = cv2.face.LBPHFaceRecognizer_create()<br>faceDetect = cv2.CascadeClassifier(&#39;haarcascade_frontalface_default.xml&#39;)<br>recognizer.read(&#39;c://capture/training/training.yml&#39;)<br><br>id = 0<br>fontFace = cv2.FONT_HERSHEY_SIMPLEX<br>fontScale = 1<br>fontColor = (0,255,255)while True:<br>  a = a + 1  <br>  check, frame = video.read()  <br>  print(check)<br>  print(frame)  <br>  gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)<br>  faces=faceDetect.detectMultiScale(gray,1.3,5);<br>  for (x,y,w,h) in faces:<br>      cv2.imwrite(&quot;DataSet/User.&quot;+str(id)+&quot;.&quot;+str(a)+&quot;.jpg&quot;, gray[y:y+h,x:x+w])<br>      cv2.rectangle(frame,(x,y),(x+w,y+h),(0,0,255),2)<br>      id, conf=recognizer.predict(gray[y:y+h,x:x+w])<br>      cv2.putText(frame,str(id),(x+w,y+h),fontFace,fontScale,fontColor)<br>  cv2.imshow(&quot;wajah&quot;,frame)<br>  #key = cv2.waitKey(1)  <br>  if (cv2.waitKey(1)==ord(&#39;q&#39;)):<br>       break<br>  print(a)<br>video.release()<br>cv2.destroyAllWindows()</pre><p>Pastikan indentasi <em>coding </em>sama dengan gambar berikut :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/705/1*bQ7KfOOC7f7We7xxutg9Iw.png" /></figure><p>Simpan <em>coding </em>dengan nama “kenalwajah.py”,kemudian jalankan di <em>command prompt </em>menggunakan perintah :</p><pre>python kenalwajah.py</pre><p>Apabila <em>coding </em>tidak mengalami <em>error, </em>maka wajah akan secara otomatis dikenali dengan ID = 1.</p><p><strong>u. Lantas, bagaimana jika kita ingin sistem mengenali wajah kita sebagai nama, bukan dengan ID? Maka kita perlu menambahkan <em>coding :</em></strong></p><pre>if (id==1) :<br>   id = &quot;nama&quot;</pre><p>Kita perbarui file “kenalwajah.py” dengan menambahkan <em>coding </em>diatas. Karena nama penulis adalah Ahsana Rizky, maka penulis memasukkan id = “Ahsana Rizky”. Teman-teman silahkan menyesuaikan ya!</p><pre>import cv2, time<br>from PIL import Image<br>camera = 0<br>video = cv2.VideoCapture(camera,cv2.CAP_DSHOW)<br>a = 0<br>recognizer = cv2.face.LBPHFaceRecognizer_create()<br>faceDetect = cv2.CascadeClassifier(&#39;haarcascade_frontalface_default.xml&#39;)<br>recognizer.read(&#39;C://Users/ASUS/Downloads/fr1/training/training.xml&#39;)<br>id = 0<br>fontFace = cv2.FONT_HERSHEY_SIMPLEX<br>fontScale = 1<br>fontColor = (255,0,0)</pre><pre>while True:<br>  a = a + 1  <br>  check, frame = video.read()  <br>  print(check)<br>  print(frame)  <br>  gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)<br>  faces=faceDetect.detectMultiScale(gray,1.3,5);<br>  for (x,y,w,h) in faces:<br>      cv2.imwrite(&quot;DataSet/User.&quot;+str(id)+&quot;.&quot;+str(a)+&quot;.jpg&quot;, gray[y:y+h,x:x+w])<br>      cv2.rectangle(frame,(x,y),(x+w,y+h),(0,255,0),2)<br>      id, conf=recognizer.predict(gray[y:y+h,x:x+w])<br>      if (id == 1) :<br>         id = &quot;Ahsana Rizky&quot;   <br>      cv2.putText(frame,str(id),(x+w,y+h),fontFace,fontScale,fontColor)<br>  cv2.imshow(&quot;wajah&quot;,frame)<br>  if (cv2.waitKey(1)==ord(&#39;q&#39;)):<br>       break<br>  print(a)<br>video.release()<br>cv2.destroyAllWindows()</pre><p>Pastikan indentasi <em>coding </em>sama dengan gambar berikut :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/703/1*YkepYk6Gj9A5MBbmfd5Exg.png" /></figure><p>Jalankan di <em>command prompt </em>menggunakan perintah :</p><pre>python kenalwajah.py</pre><p>Berikut hasil akhirnya!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/798/1*vAiynsG4T5F27bI6Zgk9QA.png" /></figure><p>Nah, begitulah hasil percobaan kita kali ini, teman-teman <em>Data Enthusiast! </em>Jika kalian tertarik untuk mempelajari <em>face recognition </em>lebih lanjut, silahkan cek referensi yang penulis cantumkan di akhir artikel ya!</p><p>Semoga bermanfaat dan sampai jumpa lagi!</p><h3>Referensi :</h3><ul><li><a href="https://medium.com/@986110101/pengenalan-wajah-1-6dc7d788fd07">Pengenalan Wajah (1)</a></li><li><a href="https://medium.com/@986110101/pengenalan-wajah-2-5152fa2ee5da">Pengenalan Wajah (2)</a></li><li><a href="https://medium.com/@986110101/pengenalan-wajah-3-c05a6422113e">Pengenalan Wajah (3)</a></li><li><a href="https://www.pyimagesearch.com/2018/09/24/opencv-face-recognition/">OpenCV Face Recognition - PyImageSearch</a></li><li><a href="https://stackoverflow.com/questions/19876079/cannot-find-module-cv2-when-using-opencv">Cannot find module cv2 when using OpenCV</a></li></ul><p><a href="https://www.datacamp.com/community/tutorials/face-detection-python-opencv">https://www.datacamp.com/community/tutorials/face-detection-python-opencv</a></p><p>The Codacus, Face Recognition OpenCV — Training A Face Recognizer</p><p>“Capture Webcam with Python (opencv): Step by step”, Dr. Vytautas Bielinskas</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2bad15b60b53" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Forecasting Comparation of The Gasoline Data using Extreme Learning Machine, Multilayer…]]></title>
            <link>https://ahsanarizkym.medium.com/forecasting-comparation-of-the-gasoline-data-using-extreme-learning-machine-multilayer-91c443deccfc?source=rss-b41a392ecd84------2</link>
            <guid isPermaLink="false">https://medium.com/p/91c443deccfc</guid>
            <dc:creator><![CDATA[Ahsana Rizky Mashura]]></dc:creator>
            <pubDate>Sat, 09 Jan 2021 09:35:53 GMT</pubDate>
            <atom:updated>2021-01-10T03:36:19.469Z</atom:updated>
            <content:encoded><![CDATA[<h3>Forecasting Time Series Data using <strong><em>Extreme Learning Machine, Multilayer Perceptrons &amp; </em></strong><em>Neural Network Autoregression in RStudio</em></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*O2IOdzkNgMPJJbS1oPI21Q.png" /><figcaption>Source : engangebay</figcaption></figure><p><strong><em>Hello Data Enthusiasts!</em></strong></p><p>Kali ini kita akan mencoba melakukan peramalan (<em>forecasting</em>) dari data historis “Gasoline” menggunakan metode <em>Extreme Learning Machine</em> (ELM), <em>Multilayer Perceptrons</em> (MLP) &amp; <em>Neural Network Autoregression</em> (NNETAR) di RStudio, kemudian membandingkan hasilnya.</p><p>Peramalan (<em>forecasting</em>) sendiri merupakan suatu usaha untuk meramalkan keadaan di masa mendatang melalui pengujian keadaan di masa lalu (Handoko, 1999). Dalam kasus ini, kita akan menggunakan data historis atau data runtun waktu “Gasoline” dari tahun-tahun sebelumnya untuk meramalkan data beberapa periode kedepan. Sebelum masuk dalam tahap analisis data, yuk kita kenalan dulu dengan metode-metode diatas!</p><h3><strong>Extreme Learning Machine (ELM)</strong></h3><p><em>Extreme Learning Machine</em> (ELM) adalah salah satu jenis dari <em>Spiking Neural Network</em> (SNN), dimana bobot lapisan pertama dipilih secara acak sedangkan lapisan keluaran dihitung sesuai dengan prinsip <em>Regularized Least Squares</em> (RLS). ELM banyak digunakan dalam <em>batch learning, sequential learning</em>, dan <em>incremental learning</em> karena kecepatan pembelajarannya yang cepat dan efisien, konvergensi yang cepat, kemampuan generalisasi yang baik, dan kemudahan implementasinya. ELM tidak memerlukan <em>gradient-based backpropagation, </em>tetapi menggunakan <em>Moore-Penrose generalized inverse</em> untuk mengatur bobotnya.</p><h3><em>Multilayer Perceptrons</em> (MLP)</h3><p>Dalam <em>Multilayer Perceptrons</em> (MLP), terdapat lebih dari satu lapisan linier (kombinasi neuron). Jika kita mengambil contoh sederhana jaringan tiga lapis (<em>three-layer-network</em>), <em>layer</em> pertama akan menjadi <em>input layer, layer </em>terakhir akan menjadi <em>output layer </em>dan <em>layer </em>tengah disebut <em>hidden layer</em>. Kita meng-<em>input</em> data ke dalam <em>input layer </em>dan mengambil <em>output</em> dari <em>output layer</em>. Kita bisa menambah jumlah <em>hidden layer</em> sebanyak yang kita mau, untuk membuat model lebih kompleks.</p><p>Neuron dalam MLP dilatih dengan algoritma <em>Backpropagation</em>. MLP dirancang untuk mendekati fungsi kontinu apa pun dan dapat memecahkan masalah yang tidak dapat dipisahkan secara linier. MLP banyak digunakan dalam kasus klasifikasi pola, peramalan, dsb.</p><h3><em>Neural Network Autoregression (NNETAR)</em></h3><p><em>Neural Network </em>(NN) telah menjadi salah satu model <em>machine learning </em>yang menarik karena strukturnya yang terinspirasi oleh otak manusia dan juga kemampuan untuk menambahkan lebih banyak kompleksitas.</p><p>NNETAR merupakan <em>feed-forward</em> <em>neural network </em>dengan satu <em>hidden layer </em>dan <em>lagged inputs </em>untuk memperkirakan deret waktu univariat. Fungsi NNETAR adalah untuk menyesuaikan model jaringan saraf ke deret waktu dengan <em>lagged values</em> sebagai input<em> </em>(dan mungkin beberapa <em>exogenous inputs</em>)<em>. </em>Jadi NNETAR adalah model <em>autogressive nonlinier</em> dan tidak mungkin untuk mendapatkan interval prediksi secara analitik.</p><p>Model NNETAR dapat dituliskan sebagai :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/133/1*sHFnEc0BWF6Rl1hxJxHbAg.png" /></figure><p>dimana</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/211/1*VbSfiE22OJwBMTvkieryGA.png" /></figure><p>adalah vektor yang berisi <em>lagged values </em>dari data <em>time series </em>dan f adalah jaringan saraf dengan 4 node tersembunyi dalam satu <em>layer.</em> <em>Error series :</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/36/1*bp65Ichc6WFDO9iAzHBm9A.png" /></figure><p>diasumsikan homoskedastik (dan mungkin juga berdistribusi normal). Kita dapat mensimulasikan pola data di masa depan dari model ini secara iteratif, dengan menghasilkan nilai <em>error series </em>secara acak, baik dari distribusi normal, atau dengan pengambilan sampel ulang dari data historis.</p><h3>Analisis Data Historis “Gasoline”</h3><p>Data historis “Gasoline” merupakan data runtun waktu (bulanan) dari bulan Januari tahun 2004 sampai dengan bulan Agustus tahun 2017, total sebanyak 164 data.</p><p>1<em>. Install</em> beberapa <em>package </em>khusus untuk melakukan analisis menggunakan metod-metode diatas di RStudio, yaitu <em>pacakge “</em>thief”, “nnfor”, “forecast”, dan “tibble”. Kita bisa menggunakan <em>syntax </em>dibawah ini atau memakai opsi “tools” di <em>taskbar </em>RStudio.</p><blockquote>install.packages(“thief”)<br>install.packages(“nnfor”)<br>install.packages(“forecast”)<br>install.packages(“tibble”)</blockquote><p>2. Panggil <em>library </em>dari <em>package-package </em>tersebut.</p><blockquote>library(thief)<br>library(nnfor)<br>library(forecast)<br>library(tibble)</blockquote><p>3. <em>Input </em>data historis “Gasoline”.</p><blockquote>gas&lt;-read.csv(“D://exam_stats/gasoline.csv”)<br>View(gas)</blockquote><p>4. <em>Split </em>data historis “Gasoline” menjadi <em>data training </em>dan <em>data testing. </em>Menurut Zhang (1997) beberapa peneliti membagi data <em>training </em>dan <em>testing </em>dengan proporsi 80 (<em>training</em>) : 20 (<em>testing</em>), maka proporsi inilah yang akan penulis gunakan, sehingga 131 data masuk kedalam kategori <em>training </em>dan 33 data masuk kedalam kategori <em>testing. </em>Perlu diingat bahwa <em>data training </em>berfungsi untuk menyusun dan melatih model, sedangkan <em>data testing </em>berfungsi untuk menguji model.</p><p>Teman-teman <em>Data Enthusiast </em>bebas mencoba proporsi <em>data training </em>dan <em>data</em> <em>testing </em>yang berbeda, ya!</p><blockquote># data training<br>gas=ts(gas$Gasoline, start=c(2004,1), frequency = 12)<br>gas.train=ts(gas[1:131], start=c(2004,1), freq=12)<br>gas.train<br>autoplot(gas.train,ylab=”Number of Gasoline”,ggtitle=”Training dataset”,<br> type=’o’,pch=12,theme_minimal=””)</blockquote><blockquote># data testing<br>gas.test=ts(gas[132:164], start=c(2014,12), freq=12)<br>gas.test<br>autoplot(gas.test,ylab=”Number of Gasoline”,ggtitle=”Testing dataset”,<br> theme_minimal=””)</blockquote><p>5. Berikutnya, kita memasuki bagian <em>fitting model </em>untuk masing-masing metode<em>, </em>melakukan peramalan (<em>forecast</em>) menggunakan model yang diperoleh dan visualisasi hasil peramalan.</p><blockquote># fitting ELM model<br>gas.fit.elm &lt;- elm(gas.train)<br>gas.fcst.elm &lt;- forecast(gas.fit.elm, h = 33)<br>gas.fcst.elm</blockquote><blockquote># visualize predictions using ELM model<br>autoplot(gas.test) +<br> autolayer(gas.fcst.elm, series = “ELM Forecast”, linetype = “dashed”,ylab=”Number of Gas<br> oline”)</blockquote><blockquote># fitting MLP model<br>gas.fit.mlp &lt;- mlp(gas.train)<br>gas.fcst.mlp &lt;- forecast(gas.fit.mlp, h = 33)<br>gas.fcst.mlp</blockquote><blockquote># visualize predictions using MLP model<br>autoplot(gas.test) +<br> autolayer(gas.fcst.mlp, series = “MLP Forecast”, linetype = “dashed”,<br> theme_minimal=”” ,ylab=”Number of Gasoline”)</blockquote><blockquote># fitting NNETAR model<br>gas.fit.nnetar &lt;- nnetar(gas.train)<br>gas.fcst.nnetar &lt;- forecast(gas.fit.nnetar, h = 33)<br>gas.fcst.nnetar</blockquote><blockquote># visualize predictions using NNETAR model<br>autoplot(gas.test) +<br> autolayer(gas.fcst.nnetar, series = “nnetar Forecast”, linetype = “dashed”,<br> theme_minimal=””,ylab=”Number of Gasoline”)</blockquote><p>6. Karena kita ingin membandingkan hasil peramalan untuk mendapatkan metode terbaik, maka kita perlu mengetahui rata-rata kesalahan peramalan dari masing-masing metode. Rata-rata tersebut dapat kita hitung menggunakan MAE (<em>Mean Absolute Error</em>).</p><blockquote># perbandingan<br>gas.mae&lt;- tibble(Test = gas.test,<br> nnetar = gas.fcst.nnetar$mean,<br> MLP = gas.fcst.mlp$mean,<br> ELM = gas.fcst.elm$mean)<br>gas.mae</blockquote><blockquote># calculate absolute error<br>gas.mae$ae.nnetar &lt;- with(gas.mae, abs(nnetar-Test))<br>gas.mae$ae.MLP &lt;- with(gas.mae, abs(MLP-Test))<br>gas.mae$ae.ELM &lt;- with(gas.mae, abs(ELM-Test))</blockquote><blockquote># calculate MAE<br>mae.score &lt;- apply(gas.mae, 2, mean)[5:7]<br>names(mae.score)=c(“MAE.nnetar”, “MAE.MLP”, “MAE.ELM”)<br>mae.score</blockquote><h3>Hasil Analisis Data Historis “Gasoline”</h3><p>Apabila Teman-teman <em>Data Enthusiasts </em>telah mengikuti langkah-langkah diatas di RStudio tanpa mengalami <em>error, </em>kita akan mendapatkan <em>output </em>sebagai berikut :</p><p>a. <em>Data train </em>dan <em>Data test</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/622/1*5QKRTBso3hkZPXhepHkiog.png" /><figcaption>Data Training</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/577/1*p1bROLKzJIRRSg86Sv9P_Q.png" /><figcaption>Plot Data Training</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/621/1*6Bttep1P0guSogj-ebdAOQ.png" /><figcaption>Data Testing</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/578/1*9F3Ob7QN06O-bzAlYLKf0w.png" /><figcaption>Plot Data Testing</figcaption></figure><p>b. <em>Output</em> analisis runtun waktu menggunakan metode<em> Extreme Learning Machine</em> (ELM)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/696/1*dCI5YKw8WZ0nfdUpKeyMZw.png" /><figcaption>Hasil Peramalan Metode ELM</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/573/1*PFGvKbJV9uxPSTY9SmbaLA.png" /><figcaption>Pola Data Hasil Peramalan Metode ELM vs Pola Data Aktual</figcaption></figure><p>Dari <em>plot </em>diatas kita bisa melihat bahwa ternyata pola data hasil peramalan menggunakan metode ELM untuk 33 periode kedepan (Desember 2014 2016 s/d Agustus 2017) jauh berbeda dari pola data aktual. Data aktual mengalami penurunan tajam pada awal tahun 2016 sedangkan data hasil peramalan mengalami peningkatan yang stabil hingga akhir periode peramalan.</p><p>c. <em>Output</em> analisis runtun waktu menggunakan metode<em> Multilayer Perceptrons</em> (MLP)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/697/1*gX6BsmcZu2qe00K-4Kggaw.png" /><figcaption>Hasil Peramalan Metode MLP</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/571/1*O5d4EmAQ6KDfVTtkKKwaBQ.png" /><figcaption>Pola Data Hasil Peramalan Metode MLP vs Pola Data Aktual</figcaption></figure><p>Berbeda dari metode sebelumnya, pola data hasil peramalan menggunakan metode MLP untuk 33 periode kedepan (Desember 2014 2016 s/d Agustus 2017) tidak mengalami peningkatan secara stabil, melainkan mengalami penurunan. Pola data ini juga masih berbeda dari pola data aktual, dengan perbedaan besar kembali terletak pada awal tahun 2016. Data aktual mengalami penurunan drastis kemudian peningkatan yang drastis pula, sedangkan metode MLP meramalkan data landai dengan peningkatan yang sangat kecil di periode yang sama.</p><p>d. <em>Output</em> analisis runtun waktu menggunakan metode<em> Neural Network Autoregression</em> (NNETAR)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/698/1*FlZMPXW8vMtPoMR1Iljviw.png" /><figcaption>Hasil Peramalan Metode NNETAR</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/571/1*jnkJ_YAJDi-Y7UsNpWvrkA.png" /><figcaption>Pola Data Hasil Peramalan Metode NNETAR vs Pola Data Aktual</figcaption></figure><p>Dibadingkan dengan kedua metode sebelumnya, pola data hasil peramalan menggunakan metode NNETAR untuk 33 periode kedepan (Desember 2014 2016 s/d Agustus 2017) paling mendekati pola data aktual, dengan adanya penurunan drastis dari awal periode sampai akhir tahun 2015, kemudian melandai sampai akhir periode peramalan.</p><p>e. Perbandingan MAE Ketiga Metode</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/264/1*lwlcfENzH7Z6mVKJQjJo4A.png" /><figcaption>MAE Ketiga Metode</figcaption></figure><p>Dari <em>output </em>diatas, kita mengetahui bahwa metode <em>Neural Network Autoregression</em> (NNETAR) memberikan data hasil peramalan yang paling mendekati data aktual dibandingkan dengan metode EML dan MPL. Hal ini juga diperkuat dengan perbandingan MAE ketiga metode yang dipakai, yang menunjukkan bahwa nilai MAE terkecil dimiliki oleh metode NNETAR. Metode NNETAR berhasil meramalkan data historis “Gasoline” selama 33 periode kedepan dengan rata-rata kesalahan sebesar 0.3063594 atau kurang lebih 31 satuan. Kita dapat menyimpulkan bahwa model yang kita peroleh dari metode NNETAR merupakan model terbaik dan metode NNETAR merupakan metode yang paling sesuai untuk meramalkan data historis “Gasoline”.</p><p>Nah, begitulah hasil percobaan kita kali ini, teman-teman <em>Data Enthusiast! </em>Jika kalian tertarik untuk mempelajari ketiga metode diatas lebih lanjut, silahkan cek referensi yang penulis cantumkan di akhir artikel ya!</p><p>Semoga bermanfaat dan sampai jumpa lagi!</p><h3>Referensi :</h3><ul><li><a href="https://medium.com/@reni_A/forecasting-time-series-with-neural-network-bf4d70651df3">FORECASTING TIME SERIES WITH NEURAL NETWORK</a></li><li><a href="https://www.sciencedirect.com/topics/computer-science/multilayer-perceptron">Multilayer Perceptron</a></li><li><a href="https://rstudio-pubs-static.s3.amazonaws.com/313595_2cd55f37d9214b15ab60d7b1a0663da8.html">Neural Network Models for Time Series Prediction</a></li><li><a href="https://towardsdatascience.com/introduction-to-extreme-learning-machines-c020020ff82b">Introduction to Extreme Learning Machines</a></li><li><a href="https://medium.com/@mukhlishatunnada02/implementasi-artificial-neural-network-ann-di-r-untuk-klasifikasi-prediksi-bahan-bakar-disel-99cf7ed0c351">IMPLEMENTASI ARTIFICIAL NEURAL NETWORK (ANN) DI R UNTUK KLASIFIKASI PREDIKSI BAHAN BAKAR DISEL</a></li><li><a href="https://medium.com/@samuelsena/pengenalan-deep-learning-part-2-multilayer-perceptron-e8f98d625b09">Pengenalan Deep Learning Part 2 : Multilayer Perceptron</a></li><li><a href="https://ai.facebook.com/blog/ar-net-a-simple-autoregressive-neural-network-for-time-series/">AR-Net: A simple autoregressive neural network for time series</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=91c443deccfc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Application of K-Means Clustering to Area Grouping in Russia Based on Industrial Production Index]]></title>
            <link>https://medium.com/statistics-uii/application-of-k-means-clustering-to-area-grouping-in-russia-based-on-industrial-production-index-5ccbf3535ccb?source=rss-b41a392ecd84------2</link>
            <guid isPermaLink="false">https://medium.com/p/5ccbf3535ccb</guid>
            <category><![CDATA[russia]]></category>
            <category><![CDATA[corporate]]></category>
            <category><![CDATA[k-means-clustering]]></category>
            <category><![CDATA[economy]]></category>
            <category><![CDATA[statistics]]></category>
            <dc:creator><![CDATA[Ahsana Rizky Mashura]]></dc:creator>
            <pubDate>Fri, 01 May 2020 13:58:21 GMT</pubDate>
            <atom:updated>2021-08-18T02:21:54.250Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*DIUmnh4tsS-9z5uCHSBQyA.png" /></figure><p>The corporate governance system recognizes conflicts that occur between the goals of shareholders and managers, and builds institutions, policies, and procedures for protecting the interests of shareholders.</p><p>Therefore a framework is made. Based on the jurnal “Corporate governance in Russia: a framework for analysis” written by Daniel J. McCarthy and Sheila M. Puffer, a corporate governance framework composed of company components and stakeholders illustrates the interrelated relationships in which a change experienced by one element will influence other elements and simultaneously affect the company’s main stakeholders. The components referred to consist of : Economy, Regulation or Politics, Technology, and Social or Culture. Whereas stakeholders in the framework environment include: Primary stakeholders, Secondary stakeholders, and Peripheral stakeholders.</p><p>This research focuses on the Industrial Production Index as an industrial indicator of corporate governance from economical aspect in Russia based on the latest update of “Industrial Production Index: Previous Month= 100: by Region” data as of February 2020 from Russian Premium Database in CEIC (Global Economic Data, Indicators, Charts &amp; Forecasts). The industrial production index (IPI) is a monthly economic indicator measuring real output in the manufacturing, mining, electric and gas industries, relative to a base year. Industrial production and capacity levels are expressed as an index level relative to a base year (2018). In other words, they do not express absolute production volumes or values, but the percentage change in production relative to 2018. Physioeconomically, Russia is divided into 9 major regions : the Central European Region, the North and Northwest European Region, the Volga Region, the North Caucasus, the Ural Region, Western Siberia, Eastern Siberia, Northern and Northwestern Siberia, and the Russian Far East. The method used to solve this case study is the K-Means Clustering. Total of 83 regions in Russia will be grouped into 6 clusters. Mapping of the final clusters is visualized by merging the data into a level 1 spasial data of Russia.</p><p>Before processing, Industrial Production Index data must be converted to decimal form because the raw data is presented in units of percent (%). The data for each region is divided by 100 and the new data is combined with Russian level 1 spatial data table from DIVA-GIS in GeoDa by using the merge table option. Then see the distribution of the data through a histogram.</p><p>The case study of grouping regions in Russia into clusters based on the Industrial Production Index is solved using the K-Means Algorithm. Definition of K-Means Algorithm is an algorithm that divides data objects into groups such as categories, parts, or groups into forms, entities, units, and examples.</p><p>Steps of k-means clustering :</p><p>1. Determine the number of clusters desired,</p><p>2. Group data according to the number of clusters that have been determined,</p><p>3. Determine the centroid value in each cluster,</p><p>4. Calculate the closest distance using Euclidean Formula,</p><p>5. Displays results based on the lowest distance from the calculation of step 4,</p><p>6. Perform iterations again if it does not get the correct results.</p><p><strong>Euclidean Formula</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/244/1*BjoiImKivi38gjjAeXNCAg.png" /><figcaption>Euclidean Formula</figcaption></figure><p>In order to start grouping data, it is necessary to determine the optimal number of clusters beforehand. The method used to determine optimal number of clusters are WSS (Within Sum of Square) and Silhouette method. WSS method is done by minimizing the total intra-cluster variation or total within-cluster sum of square. Total WSS is able to measure the compactness of the clustering which the smallest form of it is desired.</p><p>Steps of WSS method :</p><p>1. Compute clustering algorithm (e.g., k-means clustering) for different values of k. For instance, by varying k from 1 to 10 clusters,</p><p>2. For each k, calculate the total within-cluster sum of square,</p><p>3. Plot the curve of WSS according to the k,</p><p>4. The location of a bend (knee or elbow) in the plot is generally considered as an indicator of the appropriate number of clusters.</p><p>But WSS method can be ambiguous at times, so another method is needed for comparation. Silhouette method measures the quality of clustering. It determines how well each object lies within its cluster. A high average silhouette width indicates a good clustering. Average silhouette method computes the average silhouette of observations for different values of k. The optimal number of clusters k is the one that maximize the average silhouette over a range of possible values for k.</p><p>Steps of silhouette method :</p><p>1. Compute clustering algorithm (e.g., k-means clustering) for different values of k. For instance, by varying k from 1 to 10 clusters,</p><p>2. For each k, calculate the average silhouette of observations (avg.sil),</p><p>3. Plot the curve of average silhouette according to the number of clusters k,</p><p>4. The location of the maximum is considered as the appropriate number of clusters.</p><p>Before processing, Industrial Production Index data must be converted to decimal form because the raw data is presented in units of percent (%). The data for each region is divided by 100 and the new data is combined with Russian level 1 spatial data table from DIVA-GIS in GeoDa by using the merge table option. Then see the distribution of the data through a histogram.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/470/1*9OmW9YN66Iv-H6Drc2aNPw.png" /><figcaption>Histogram of Industrial Production Index Data</figcaption></figure><p>The histogram above illustrates the distribution of Industrial Production Index data (in decimal). There is one region that has an Industrial Production Index between 56.6–67.6 marked with a blue bar on the histogram. The green bar on the histogram illustrates the frequency of regions with the Industrial Production Index between 89.6–100.5 and there are 24 regions in that range. The range of Industrial Production Index between 100.5–111.5 marked with pink contains 38 regions, which means the majority of regions in Russia are included. Next, as many as 13 regions entered the region with the Industrial Production Index between 111.5–122.5 and marked with a red bar. Finally there are 3 regions where the Industrial Production Index is located between 122.5–133.5 and marked with an orange bar.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/441/1*9mTN6aYi-Daci4RqdPkdvg.png" /><figcaption>Data Description</figcaption></figure><p>After descripting the data, the next step is defining the optimal number of clusters for area grouping using 2 different method, WSS (Within Sum of Square) and Silhouette method. Syntax used can be seen below.</p><blockquote>data=read.delim(“clipboard”)</blockquote><blockquote>data</blockquote><blockquote>data1 = data.frame(data$INDUSTRIAL.PRODUCTION.INDEX..DECIMAL.)</blockquote><blockquote>data1</blockquote><blockquote>summary(data1)</blockquote><blockquote>#scalling data</blockquote><blockquote>sapply(data1, var) #variation between variable is still far</blockquote><blockquote>rge &lt;- sapply(data1, function(x) diff(range(x)))</blockquote><blockquote>rge</blockquote><blockquote>data2&lt;-sweep(data1,2,rge,FUN = “/”)</blockquote><blockquote>data2</blockquote><blockquote>sapply(data2, var) #variation between variable is near</blockquote><blockquote>?sweep</blockquote><blockquote>#distance</blockquote><blockquote>library(factoextra)</blockquote><blockquote>distance&lt;-get_dist(data2)</blockquote><blockquote>distance</blockquote><blockquote>#WSS METHOD</blockquote><blockquote>fviz_nbclust(data2, kmeans, method = “wss”)</blockquote><blockquote>#SILHOUETTE METHOD</blockquote><blockquote>fviz_nbclust(data2, kmeans, method = “silhouette”)</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/293/1*NQTukYHUh_8JXUtgANdSDQ.png" /><figcaption>Output WSS Method</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/303/1*iEz-726SvVHsVUWMv0t4bA.png" /><figcaption>Ouput Silhouette Method</figcaption></figure><p>Based on calculations using RStudio, obtained that the number of optimal clusters is 6. In figure 2 (WSS Method) it can be seen that the elbow is located on number 6 and in figure 3 (Silhouette Method) the number drawn by the line is number 6. Then from that, regions in Russia are grouped into 6 clusters. The next step is grouping using Microsoft Excel. The initial 6 data centers are determined for each cluster randomly and scattered.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/188/1*915rO3zk8QK4aNmCELlGjw.png" /><figcaption>Initial Centers for Each Cluster</figcaption></figure><p>The initial center of cluster 1 is 1,076 (case 3 or the Amur region); 1,231 (case 9 or Buryat region) was chosen as the initial center of cluster 2; 1.04 (case 31 or the Kirov region) the initial center of cluster 3 is selected; 1,2 (case 48 or North Ossetia region) selected as the initial center of cluster 4; 1,335 (case 70 or Tula region) was chosen as the initial center of cluster 5; and 0.947 (case 80 or Yamal-Nenets region) were chosen as the initial center of cluster 6. After the initial center for 6 clusters was determined, the distance between each data and cluster center was calculated using the Euclidean formula to get the initial cluster in the first iteration. Microsoft Excel is used as a tool starting at this stage. Euclidean formulas are converted to ABS (Absolute) calculation formulas in Excel. Then look for the average of each cluster and the average is used as a new center in the second iteration, replacing the initial center in figure 3. In this case study, iteration is repeated 5 times until the final result is obtained precisely in the sixth iteration cluster that shows similarity with the fifth iteration cluster. Because the same clustering has been obtained for each region, iteration can be stopped.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/424/1*Ey35de3j56uKUwfnHxSY0g.png" /><figcaption>Final Clusters</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/422/1*kFXhBTVFQrOdP-vGevcdXQ.png" /><figcaption>Final Clusters</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/423/1*G_a3zV-ahVI7JIpHpgD7FA.png" /><figcaption>Final Clusters</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/424/1*Zc9Aiihw68xwdGpNzG51MQ.png" /><figcaption>Final Clusters</figcaption></figure><p>Based on the results obtained in Table 2, there are 17 regions in Russia that are included in the grouping in the first cluster (1). The following regions are :</p><p>1. Amur</p><p>2. City of St. Petersburg</p><p>3. Gorno-Altay</p><p>4. Irkutsk</p><p>5. Ivanovo</p><p>6. Kaluga</p><p>7. Khakass</p><p>8. Leningrad</p><p>9. Moscow City</p><p>10. Moskva</p><p>11. Nizhegorod</p><p>12. Primor’ye</p><p>13. Rostov</p><p>14. Ryazan’</p><p>15. Sakha</p><p>16. Tambov</p><p>17. Yevrey</p><p>From cluster 1 above, City of St. Petersburg is the region with the largest Industrial Production Index, which is 1.117 and Ivonovo is the region with the smallest Industrial Production Index, which is 1.059. The average Industrial Production Index for cluster 1 is 1.083.</p><p>Furthermore, namely, there are 5 regions in Russia included in the grouping in the second cluster (2). The following regions are :</p><p>1. Buryat</p><p>2. Chukot</p><p>3. North Ossetia</p><p>4. Ul’yanovsk</p><p>5. Yaroslavl’</p><p>From cluster 2 above, Buryat is the region with the largest Industrial Production Index, which is 1.231 and Yaroslavl ‘is the region with the smallest Industrial Production Index, which is 1.185. The average of Industrial Production Index for cluster 2 is 1.205.</p><p>Then there are 33 regions in Russia included in the grouping in the third cluster (3). The following regions are :</p><p>1. Altay</p><p>2. Bashkortostan</p><p>3. Bryansk</p><p>4. Checnya</p><p>5. Chelyabinsk</p><p>6. Dagestan</p><p>7. Kaliningrad</p><p>8. Kamchatka</p><p>9. Kamerovo</p><p>10. Khabarovsk</p><p>11. Kirov</p><p>12. Komi</p><p>13. Kostroma</p><p>14. Kurgan</p><p>15. Mariy-El</p><p>16. Mordovia</p><p>17. Murmansk</p><p>18. Nenets</p><p>19. Novgorod</p><p>20. Novosibirsk</p><p>21. Omsk</p><p>22. Orel</p><p>23. Penza</p><p>24. Perm’</p><p>25. Sakhalin</p><p>26. Samara</p><p>27. Smolensk</p><p>28. Stavropol’</p><p>29. Tatarstan</p><p>30. Tomsk</p><p>31. Udmurt</p><p>32. Vologda</p><p>33. Zabavkal’y</p><p>From cluster 3 above, Tomsk is the region with the largest Industrial Production Index, which is 1.051 and Komi is the region with the smallest Industrial Production Index, which is 0.977. The average of Industrial Production Index for cluster 3 is 1.019.</p><p>There are 8 regions in Russia that are included in the grouping in the fourth cluster (4). The following regions are :</p><p>1. Chuvash</p><p>2. Kabardin-Balkar</p><p>3. Kalmyk</p><p>4. Pskov</p><p>5. Sverdlovsk</p><p>6. Tver’</p><p>7. Vladimir</p><p>8. Voronezh</p><p>From cluster 4 above, Vladimir is the region with the largest Industrial Production Index, namely 1.177 and Voronezh is the region with the smallest Industrial Production Index, namely 1.127. The average of Industrial Production Index for cluster 4 is 1.155.</p><p>There are 2 regions in Russia included in the grouping in the fifth cluster (5). The following regions are :</p><p>1. Adygey</p><p>2. Tula</p><p>From cluster 5 above, the average of Industrial Production Index is 1.319.</p><p>And finally, there are 18 regions in Russia included in the sixth cluster (6). The following regions are:</p><p>1. Arkangel’sk</p><p>2. Astrakhan’</p><p>3. Belgorod</p><p>4. Ingush</p><p>5. Karachay-Cherkess</p><p>6. Karelia</p><p>7. Khanty-Mansiy</p><p>8. Krasnodar</p><p>9. Krasnoyarsk</p><p>10. Kursk</p><p>11. Lipetsk</p><p>12. Maga Buryatdan</p><p>13. Orenburg</p><p>14. Saratov</p><p>15. Tuva</p><p>16. Tyumen’</p><p>17. Volgograd</p><p>18. Yamal-Nenets</p><p>From cluster 6 above, Maga Buryatdan is the region with the largest Industrial Production Index, 0.973 and Tuva is the region with the smallest Industrial Production Index, 0.566. The average of Industrial Production Index for cluster 6 is 0.929.</p><p>Overall, covering cluster 1 to cluster 6, the region with the largest Industrial Production Index of 1.335 is Tula and the region with the smallest Production Index of 0.566 is Tuva. Cluster 5 has the largest average Industrial Production Index, while Cluster 6 has the smallest average Industrial Production Index. This means that companies in cluster 6 need to improve their corporate governance. It would be nice if the companies in cluster 5 maintain and improve their corporate governance as well. These efforts need to be made to help the economy in Russia.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/564/1*q1xsJm_Ku_H7FncuaSjSZA.png" /><figcaption>Visualization of Regions in Russia Based on Final Clusters</figcaption></figure><p>Visualization of regions in Russia based on their cluster is made using the GeoDa. The figure in Figure 5 illustrates the visualization of the regions included in each cluster. Areas of light green on the map are cluster 1 areas, pink represents areas on the map included in cluster 2. Next, there are areas on the map that are light blue are cluster 3. On the map, areas belonging to the cluster 4 is represented by dark green, areas with cluster 5 are represented by red, and areas belonging to cluster 6 are represented by dark blue. It can be seen that the 2 regions with the largest area, Chukot and Shaka, are respectively included in cluster 6 and cluster 1. Chukot has an Industrial Production Index of 1.206 while Shaka has an Industrial Production Index of 1.025.</p><p>Based on the discussion session, it can be concluded as follows:</p><p>1. In the first cluster (1), the largest Industrial Production Index is owned by the City of St. Petersburg.</p><p>2. In the second cluster (2), the largest Industrial Production Index is owned by the Yaroslavl’ region.</p><p>3. In the second cluster (3), the largest Industrial Production Index is owned by the Tomsk region.</p><p>4. In the fourth cluster (4), the largest Industrial Production Index is owned by the Vladimir region.</p><p>5. In the fifth cluster (5), the largest Industrial Production Index is owned by the Tula region.</p><p>6. In the sixth cluster (6), the largest Industrial Production Index is owned by the Maga Buryatdan region.</p><h3><strong>Bibliography</strong></h3><p>2020. [online] Available at: &lt;https://www.washingtonpost.com/wp-srv/world/countries/russia.html&gt; [Accessed 24 April 2020].</p><p>Amplitude. 2020. <em>3 Mistakes You’re Making With Month-Over-Month Growth Rates</em>. [online] Available at: &lt;https://amplitude.com/blog/2016/10/25/month-over-month-growth-rates&gt; [Accessed 17 April 2020].</p><p>Datanovia. 2020. <em>Determining The Optimal Number Of Clusters: 3 Must Know Methods — Datanovia</em>. [online] Available at: &lt;https://www.datanovia.com/en/lessons/determining-the-optimal-number-of-clusters-3-must-know-methods/&gt; [Accessed 19 April 2020].</p><p>Diva-gis.org. 2020. <em>Spatial Data Download | DIVA-GIS</em>. [online] Available at: &lt;https://www.diva-gis.org/datadown&gt; [Accessed 10 April 2020].</p><p>eFinanceManagement.com. 2020. <em>Month-Over-Month | Formula | Examples | Efinancemanagement.Com</em>. [online] Available at: &lt;https://efinancemanagement.com/financial-analysis/month-over-month&gt; [Accessed 17 April 2020].</p><p>En.wikipedia.org. 2020. <em>Federal Subjects Of Russia</em>. [online] Available at: &lt;https://en.wikipedia.org/wiki/Federal_subjects_of_Russia&gt; [Accessed 17 April 2020].</p><p>Insights.ceicdata.com. 2020. <em>Cdmnext</em>. [online] Available at:&lt;https://insights.ceicdata.com/Untitled-insight/views&gt; [Accessed 19 April 2020].</p><p>McCarthy, D. and Puffer, S., 2003. Corporate governance in Russia: a framework for analysis. <em>Journal of World Business</em>, 38(4), pp.397–415.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5ccbf3535ccb" width="1" height="1" alt=""><hr><p><a href="https://medium.com/statistics-uii/application-of-k-means-clustering-to-area-grouping-in-russia-based-on-industrial-production-index-5ccbf3535ccb">Application of K-Means Clustering to Area Grouping in Russia Based on Industrial Production Index</a> was originally published in <a href="https://medium.com/statistics-uii">Jurusan Statistika UII</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Visualization of COVID-19 Spread in China as of March 20, 2020 Using DIVA-GIS and GeoDa]]></title>
            <link>https://ahsanarizkym.medium.com/visualization-of-covid-19-distribution-data-in-china-as-of-march-20-2020-using-diva-gis-and-geoda-a6519250775a?source=rss-b41a392ecd84------2</link>
            <guid isPermaLink="false">https://medium.com/p/a6519250775a</guid>
            <category><![CDATA[china]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[world-health-organization]]></category>
            <category><![CDATA[corona]]></category>
            <category><![CDATA[geodata]]></category>
            <dc:creator><![CDATA[Ahsana Rizky Mashura]]></dc:creator>
            <pubDate>Thu, 26 Mar 2020 07:40:59 GMT</pubDate>
            <atom:updated>2020-03-26T08:09:31.709Z</atom:updated>
            <content:encoded><![CDATA[<p>Coronavirus (COVID-19) is an infectious disease caused by a newly discovered coronavirus. Most people infected with the COVID-19 virus will experience mild to moderate respiratory disease and recover without the need for special treatment. Older people, and those who have basic medical problems such as cardiovascular disease, diabetes, chronic respiratory diseases, and cancer are more likely to enter critical times. (Coronavirus, n.d.)</p><p>On December 31, 2019, the World Health Organization (WHO) heard the first report about a previously unknown virus behind a number of pneumonia cases in Wuhan, a city in East China with a population of more than 11 million. This case began as an epidemic. The Chinese government responded to this incident by imposing a quarantine on Wuhan and a number of surrounding cities in Hubei province.</p><p>As of March 11, 2020, Chinese health authorities reported that more than 1,250 people were positive for COVID-19 and 3,253 of them died, most of which occurred within the scope of Hubei province. On March 17, 2020, there were 39 new cases related to COVID-19 in the documentation.</p><p>So, how is the latest distribution of COVID-19 in the provinces in China? This data is what the author will try to visualize using the Free Spatial Data-Country Level available on the official website of DIVA-GIS (www.diva-gis.org/) and confirmed case data consisting of 3 categories, namely Confirmed/Positive, Death, and Recovered every province in China per March 20th 2020. The author will try to visualize the data above using the Merge Table, Quantile Map, Scatter Plot, Scatter Plot Matrix, and Parallel Coodinate Plot functions on GeoDa.</p><p><strong>Output Merge Table covid_19_data.csv to CHN_adm1.shp table in GeoDa</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GL-ZYWAenvfCT7iX4MCAxw.png" /></figure><p>Keep in mind that before conducting Table Merging, the name of each province in China in the covid_19_data.csv file has to match the name of the province in the “NAME_1” column in the CHN_adm1.shp table.</p><p><strong>Visualization of the Spread of Contaminated / Positive COVID-19</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qBnQ_k0o0-k5wdUtu4HRCA.png" /></figure><p>In the Quantile Map above, I categorized provinces in China into 3 clusters. The interpretation of the Quantile Map above is as follows :</p><p>Areas on the map that are included in cluster 1 are marked in beige. Cluster 1 includes provinces with confirmed / positive COVID-19 cases between 1–137 people or classified as less than cluster 2 and 3. There are 10 provinces included in cluster 1.</p><p>The area on the map that belongs to cluster 2 is marked in pumpkin. Cluster 2 includes provinces with confirmed / positive COVID-19 cases between 146–541 people or classified as moderate compared to Clusters 1 and 3. There are 11 provinces included in Cluster 2.</p><p>The area on the map that belongs to cluster 3 is marked in brown. Cluster 3 includes provinces with confirmed cases / COVID-19 positive among 576–67800 people or classified as many compared to Clusters 1 and 2. There are 10 provinces included in cluster 3.</p><p>The following details the number of people confirmed / positive COVID-19 in each province :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/510/1*6m1-0nP9rUea0Kx5_k2cMQ.png" /></figure><p>In cluster 1, the province with the largest number of COVID-19 confirmed/positive cases was Tianjin with 137 cases and the province with the smallest number of COVID-19 confirmed/positive people was Xizang with 1 case.</p><p>In cluster 2, the province with the largest number of COVID-19 positive / confirmed cases was Sichuan with 541 cases and the province with the smallest number of COVID-19 confirmed/positive people was Guizhou with 146 cases.</p><p>In cluster 3, the province with the largest number of COVID-19 positive/confirmed cases was Hubei province with 67800 cases and the province with the smallest number of COVID-19 confirmed / positive cases was Chongqing province with 576 cases.</p><p><strong>Visualization of the Spread of People Who Died After Contracting COVID-19</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X7-940Y622-CVMoPpasICQ.png" /></figure><p>In the Quantile Map above, I categorize provinces in China into 3 clusters. The interpretation of the Quantile Map above is as follows:</p><p>Areas on the map that are included in cluster 1 are marked in beige. Cluster 1 contains provinces with cases of people who died after contracting COVID-19 between 0–1 people or classified as less compared to Clusters 2 and 3. There are 10 provinces included in Cluster 1.</p><p>The area on the map that belongs to cluster 2 is marked in pumpkin. Cluster 2 includes provinces with cases of people who died after contracting COVID-19 between 2–4 people or are classified as moderate compared to clusters 1 and 3. There are 11 provinces included in cluster 2.</p><p>Areas on the map that belong to cluster 3 are marked in brown. Cluster 3 includes provinces with cases of people who died after contracting COVID-19 between 6–3133 people or classified as many compared to Clusters 1 and 2. There are 10 provinces included in cluster 3.</p><p>The following details the number of people died after contracting COVID-19 in each province :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/509/1*FmsIXymNK7DK_6VhOuThaw.png" /></figure><p>In cluster 1, the provinces of Fujian, Jingxi, Jilin, Nei Mongol and Zhejiang had 1 case of people died after contracting COVID-19 and the rest of the provinces had 0 cases.</p><p>In cluster 2, the province with the largest number of cases of people died after contracting COVID-19 was Hunan province with 4 cases.</p><p>In cluster 3, the province with the largest number of cases of people died after contracting COVID-19 was Hubei province with 3133 cases.</p><p><strong>Visualization of Spread of People Who Recovered After Contracting COVID-19</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KBs8nGPWjw6hUAY5tvv_bw.png" /></figure><p>In the Quantile Map above, I categorize provinces in China into 3 clusters. The interpretation of the Quantile Map above is as follows:</p><p>Areas on the map that are included in cluster 1 are marked with beige. Cluster 1 includes provinces with cases of people who recovered after contracting COVID-19 between 1–133 people or is classified as less compared to Clusters 2 and 3. There are 10 provinces included in Cluster 1.</p><p>The area on the map that belongs to cluster 2 is marked in yellow pumpkin. Cluster 2 includes provinces with cases of people who recovered after contracting COVID-19 between 144–536 people or are classified as moderate compared to clusters 1 and 3. There are 11 provinces included in cluster 2.</p><p>Areas on the map that belong to cluster 3 are highlighted in brown. Cluster 3 contains provinces with cases of people who recovered after contracting COVID-19 between 570–58382 people or classified as more than cluster 1 and 2. There are 10 provinces included in cluster 3.</p><p>The following details the number of people recovered after contracting COVID-19 in each province :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/510/1*Ll-ddgPxTqLQ-YyL-oKUTw.png" /></figure><p>In cluster 1, the province with the largest number of cases of people recovering after contracting COVID-19 was Shanxi and Tianjin provinces with 137 cases each and the province with the smallest number of cases recovering after COVID-19 was Xizang with 1 case.</p><p>In cluster 2, the province with the highest number of cases of people recovering after contracting COVID-19 was Sichuan province with 536 cases and the province with the smallest number of cases recovering after contracting COVID-19 was Guizhou province with 144 cases.</p><p>In cluster 3, the province with the largest number of cases of people recovering after contracting COVID-19 was Hubei province with 58382 cases and the province with the smallest number of cases recovering after contracting COVID-19 was Chongqing province with 570 cases.</p><p><strong>Parallel Coordinate Plot</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bxxTMwQX2565-3Pr1mJ7dg.png" /></figure><p>The Parallel Coordinate Plot above compares variable Confi_tive, variable Death, and the variable Recovered. The interpretation of the plot above is that the data displayed is quite parallel.<em> </em>The first bar represents variable Confi_tive, the second bar represents variable Death, and the third bar represents variable Recovered.</p><p>As it turns out, in most provinces in China, the number of confirmed/positive COVID-19 people is almost the same as the number of people recovered after contracting COVID-19, with several cases of death.</p><p>The exception is for one province whose lines are parallel and are located on the far right side of the plot. The line for the province is very far from the line of other provinces. The line represents Hubei province, in which there were 67800 confirmed/positive COVID-19 cases, 3133 cases of people died after contracting COVID-19, and 58382 cases of people recovering after contracting COVID-19.</p><h3>Bibliography</h3><p><em>Coronavirus</em>. (n.d.). Retrieved from World Health Organization: <a href="https://www.who.int/health-topics/coronavirus#tab=tab_1">https://www.who.int/health-topics/coronavirus#tab=tab_1</a></p><p>Kumar, Sudalai R.2020.Novel Corona Virus 2019 Dataset. <a href="https://www.kaggle.com/sudalairajkumar/novel-corona-virus-2019-dataset#covid_19_data.csv">https://www.kaggle.com/sudalairajkumar/novel-corona-virus-2019-dataset#covid_19_data.csv</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a6519250775a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>