Use r language to dig data "five"

Source: Internet
Author: User

Introduction One, the experiment explanation 1. Environment Login

No password automatic login, system user name Shiyanlou, password Shiyanlou

2. Introduction to the Environment

This experiment environment uses the Ubuntu Linux environment with the desktop, the experiment will use the program:

1. LX Terminal (lxterminal): Linux command line terminal, Open will enter the bash environment, you can use the Linux command
2. GVim: Very useful editor, the simplest usage can refer to the course [Vim Editor] (HTTP://WWW.SHIYANLOU.COM/COURSES/2)
3. R: Enter ' R ' into the interactive environment at the command line, the code below is running in the interactive environment.

3. Use of the environment

Use the R language Interactive environment to enter the code and files required for the experiment, and use the LX Terminal (lxterminal) to run the required commands.

After completing the experiment, you can click "Experiment" above the desktop to save and share the results to Weibo to show your friends the progress of your study. The lab building provides a back-end system that can prove to be true that you have completed the experiment.

The Experiment records page can be viewed in the My Home page, which contains each experiment and notes, as well as the effective learning time of each experiment (refers to the time of the experiment desktop operation, if there is no action, the system will be recorded as Daze time). These are the proof of authenticity of your studies.

Ii. introduction of the course

This lesson mainly introduces some clustering methods, including K-means clustering, K-Center point clustering, hierarchical clustering, and density clustering. The first two sections are the introduction of the K-means algorithm and K-center point algorithm to the iris data clustering; The third section is about using the same data to take a hierarchical clustering algorithm example; the last section introduces the idea of density clustering and dbscan clustering, and shows how to use the Dbscan algorithm to cluster, and use this clustering model to classify new data.

Iii. Course content 1, K-means clustering

This section describes K-means clustering using iris data.

Data preprocessing is performed first:

> Library (Cluster) # set up a new iris DataSet > Iris2 <-iris# Remove a dataset about categories > Iris2$species <-null# divide data by K-means clustering into 3 categories > (Kmeans.result <-Kmeans (Iris2, 3) # Compare the results of K-means clustering with the actual values > table (iris$species, Kmeans.result$cluster)

Comparison results show:

It is shown that setosa (IRIS) can easily be separated from other flowers, but versicolor (Iris) and Virginica (Virginia Iris) are more difficult to distinguish.

Next, plot the data distribution and their respective center points. Note that Iris has a total of four properties, the following code is based on the preceding two properties: the length of the sepals and the width of the sepals to draw a cluster diagram. It is also important to note that because the selection of the initial center point is random, the result of clustering varies with the initial value.

> Plot (iris2[c ("Sepal.length", "Sepal.width")], col = kmeans.result$cluster) # Painting Cluster Center (cluster center) > points (kmeans.result$ Centers[,c ("Sepal.length", "Sepal.width")], col = 1:3,+ pch = 8, cex=2)

The cluster diagram is as follows:

# # #2, K Center point Clustering

This section describes using the function Pam () and PAMK () to implement the K-centric point clustering algorithm. K-Center point clustering and K-means clustering algorithms are very close, the main difference between them is: in the K-means algorithm, its center represents a class, and in the K-Center point algorithm, the closest point to the class center object as a class.

PAM (Partitioning Around medoids) is a classical algorithm in K-Center point clustering, and its idea is based on distance clustering, which has good anti-noise and anti-deviation ability. Its weakness is that it cannot handle large amounts of data, but the improved algorithm Clara algorithm selects multiple samples of the data, uses the PAM algorithm on each sample, and chooses the best clustering results. Both the PAM and Clara algorithms can be implemented in R through the function Pam () and Clara () in package ' cluster ', both of which require the number of clusters to be specified in K. However, the function Pamk () in the package ' FPC ' can select the optimal number of clusters by calling Pam () or Clara ().

Use the following code to observe the clustering situation:

The output results are as follows:

In the above example, PAMK () divides the dataset into two categories: one is ' setosa ' and the other is the mixed data of ' versicolor ' and ' virginica '. , the left half of the graph is a two-dimensional cluster diagram, where the Purple Line shows the distance between the two categories. The right half of the figure is the projection of these two classes, the closer the contour Si to 1 indicates that the observed clustering is very good; the closer to 0 of the SI means that the observed value is not easily distinguishable and is in the two categories. A negative SI indicates that the data has been incorrectly categorized. Si (i=1,2) represents the average projection of the first and second classes, respectively, 0.81 and 0.62, which indicate a good clustering situation.

Next, the number of clusters is k=3 using Pam () clustering.

The results appear as follows:

The left half shows: the first kind of flower ' setosa ' can be very good with the other two kinds of flowers, the second and the third kind of flowers have some similarities, that is to say, some of the two kinds of iris data can not be correctly judged.

According to the two clustering examples using PAMK () and Pam () above, it is difficult to determine which clustering method is better, depending on the target problem and the respective field of experience and knowledge. In this case, the PAM () function seems to be a little bit better at clustering the iris into 3 classes. So Pamk () does not necessarily give the best number of clusters. What we need to know is that when the PAM () function is used, the k=3 is set artificially, and the cluster effect is different if you don't know the iris data classification.

# # #3, hierarchical clustering

This section learns hierarchical clustering of iris data sets using function Hclust ().

First, extract 40 samples from the iris data set to avoid point crowding or even overlap on the cluster diagram, removing the kind of data that is in the DataSet as before, and then layering the data:

> IDX <-sample (1:dim (IRIS) [1], +) > irissample <-iris[idx,]> irissample$species <-null# method= "Ave" Refers to the average distance between the objects is the inter-group distance > HC <-hclust (Dist (irissample), method= "Ave") > Plot (hc, hang =-1, Labels=iris$species[idx] # Cluster tree divided into 3 classes > Rect.hclust (HC, k=3) # Return to classification results > Groups <-cutree (HC, k=3)

The cluster tree graph is drawn as follows:

Like the K-mean clustering results, flowers such as "setosa" can be easily identified, and the second and third types of flowers are still not well differentiated.

# # #4, density-based clustering

Using the package ' FPC ' can implement the Dbscan algorithm to cluster numerical data. The goal of the density-based clustering algorithm is to classify a high-density distributed data region into a class, and so on, so as to achieve the effect of dividing the data into several classes. The following two important parameters are available in the Dbscan algorithm:

1. EPS: Up to distance, define neighborhood size
2. Minpts: All fields within EPS satisfy the minimum requirement for a number of points.

A is a core object if the number of sample points within the given point a neighborhood does not exceed minpts. All points near point A are density-accessible, meaning that the distance to a is less than or equal to the distance EPs, then these points are divided into a category.

The advantage of density clustering is that it can find classes of various shapes and sizes and is insensitive to noise. The K-mean algorithm tends to find the data group with the same size spherical distribution.

The following is a density-based clustering algorithm implementation of the IRIS data set:

> Library (FPC) > Iris2 <-iris[-5] # Remove category labels > ds <-dbscan (Iris2, eps=0.42, minpts=5) # Compare cluster results with original class labels > ta BLE (Ds$cluster, iris$species)

The comparison results are as follows:

In the table above, 1-3 of the first column is the 3 class that has been divided, and 0 represents the noise and outliers, that is, objects that are not divided into any class.

> Plot (ds, IRIS2)

The black Circle is the noise (outliers).

Another way to show clustering results is to use the function Plotcluster () in the package FPC, and we can observe that different classes of data have been identified by tags.

> Plotcluster (IRIS2, Ds$cluster)

Based on the analysis of the similarity between the new data and the class, the clustering model can classify the new data. The following example extracts 10 samples from an iris data set and combines some noise to form a new data set for classification. The function runif () can generate uniformly distributed noise data.

# set random seed, randomly generate 10 iris pattern ben > Set.seed (435) > IDX <-sample (1:nrow (Iris), 10) # Remove categorical attribute columns > NewData <-iris[idx,-5]> newdata <-newdata + matrix (runif (10*4, min=0, max=0.2), nrow=10, ncol=4) # give New data classification > Mypred <-predict (ds, Iris2, NewData) # The clustering results are displayed > plot (iris2[c (1,4)], col=1+ds$cluster) > points ( Newdata[c (1,4)], pch= "*", col=1+mypred, cex=3) # Test Clustering Effects > table (mypred, Iris$species[idx]) 


Figure 4.1

Figure 4.1

Use r language to dig data "five"

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.