Prof. Pier Luca Lanzi
Data Exploration !Data Mining and Text Mining (UIC 583 @ Politecnico di Milano)
Prof. Pier Luca Lanzi
Readings
• “Data Mining and Analysis” – Chapter 2 & 3
• Loading Data and Basic Formatting in R !http://flowingdata.com/2015/02/18/loading-data-and-basic-formatting-in-r/
2
Prof. Pier Luca Lanzi
before trying anything, you should know your data!
Prof. Pier Luca Lanzi
What is Data Exploration?
• It is the preliminary exploration of the data aimed at identifying their most relevant characteristics
• What the key motivations?! Helping to select the right tool for preprocessing and data
mining ! Exploiting humans’ abilities to recognize patterns !
not captured by automatic tools • Related to Exploratory Data Analysis (EDA), created by
statistician John Tukey
4
Prof. Pier Luca Lanzi
Exploratory Data Analysis
• “An approach of analyzing data to summarize their main characteristics without using a statistical model or having formulated a prior hypothesis.”
• “Exploratory data analysis was promoted by John Tukey to encourage statisticians to explore the data, and possibly formulate hypotheses that could lead to new data collection and experiments.”!
• Seminal book is “Exploratory Data Analysis” by Tukey
• Nice online introduction in Chapter 1 of the NIST Engineering Statistics Handbook !http://www.itl.nist.gov/div898/handbook/index.htm
• http://en.wikipedia.org/wiki/Exploratory_data_analysis!
5
Prof. Pier Luca Lanzi
http://vis.stanford.edu/files/2012-EnterpriseAnalysisInterviews-VAST.pdf
Prof. Pier Luca Lanzi
What Data Exploration Techniques?
• Exploratory Data Analysis (as originally defined by Tukey),!was mainly focused on! Visualization! Clustering and anomaly detection !
(viewed as exploratory techniques)! In data mining, clustering and anomaly detection are major
areas of interest, and not thought of as just exploratory• In this section, we focus on data exploration using! Summary statistics! Visualization
• We will come back later to data exploration when discussing clustering
7
Prof. Pier Luca Lanzi
numerical attributes
Prof. Pier Luca Lanzi
Prof. Pier Luca Lanzi
Prof. Pier Luca Lanzi
Prof. Pier Luca Lanzi
Prof. Pier Luca Lanzi
Prof. Pier Luca Lanzi
Prof. Pier Luca Lanzi
Prof. Pier Luca Lanzi
Prof. Pier Luca Lanzi
Prof. Pier Luca Lanzi
Geometric Interpretation of Correlation
• The correlation coefficient is simply the cosine of the angle between the two centered attribute vectors
20
Prof. Pier Luca Lanzi
normalization
Prof. Pier Luca Lanzi
Prof. Pier Luca Lanzi
Prof. Pier Luca Lanzi
Summary Statistics
• They are numbers that summarize properties of the data
• Summarized properties include location, mean, spread, skewness, standard deviation
• Most summary statistics can be calculated in a single pass
37
Prof. Pier Luca Lanzi
Frequency and Mode
• The frequency of an attribute value is the percentage of time the value occurs in the data set
• For example, given the attribute ‘gender’ and a representative population of people, the gender ‘female’ occurs about 50% of the time.
• The mode of an attribute is the most frequent attribute value
• The notions of frequency and mode are typically used with categorical data
38
Prof. Pier Luca Lanzi
Measures of Location:!Mean and Median
• The mean is the most common measure of the location of a set of points
• However, the mean is very sensitive to outliers
• Thus, the median or a trimmed mean is also commonly used
39
Prof. Pier Luca Lanzi
Measures of Spread: !Range and Variance
• Range is the difference between the max and min• The variance or standard deviation is the most common measure
of the spread of a set of points
• However, this is also sensitive to outliers, so that other measures are often used
40
Prof. Pier Luca Lanzi
Percentiles
• For continuous data, the notion of a percentile is veryuseful
• Given an ordinal or continuous attribute x and a number p between 0 and 100, the p-th percentile is a value xp of x such that p% of the observed values of x are less than xp
• For instance, the 50th percentile is the value x50% such that 50% of all values of x are less than x50%
41
Prof. Pier Luca Lanzi
Summary Statistics in R
# stringr is also needed to be installed # required libraries library(foreign) library(rattle) library(plyr) # set working directory setwd("~/Dropbox/Documents/Online/Corsi/DMTM/data") # load data wnum = read.arff("weather.numeric.arff") # check the structure str(wnum) # names of the attributes names(wnum) # rename the attributes to normalize them in lowercase names <- normVarNames(names(wnum))
42
Prof. Pier Luca Lanzi
Summary Statistics in R
# summary statistics summary(wnum) mean(wnum$humidity) sd(wnum$humidity) var(wnum$humidity) median(wnum$humidity) max(wnum$humidity) min(wnum$humidity) # first ten rows head(wnum,10) # first 5 rows columns 1 & 3 head(wnum[c(1,3)],5) # naming the columns head(wnum[c("humidity", "temperature")])
43
Prof. Pier Luca Lanzi
Summary Statistics in R
# sampling ten rows head(wnum[sample(nrow(wnum), 10),c("humidity", "temperature")]) # selecting the rows based an attribute properties wnum[wnum$outlook=="sunny",] # exploring data with sorted attributes wnum[order(wnum$temperature),] ### ### grouping and summarizing data ### ddply(snum,"outlook",summarize, max=max(temperature, na.rm=TRUE))
44
Prof. Pier Luca Lanzi
Visualization
• Visualization is the conversion of data into a visual or tabular format so that the characteristics of the data and the relationships among data items or attributes can be analyzed or reported
• Data visualization is one of the most powerful and appealing techniques for data exploration ! Humans have a well developed ability to analyze large
amounts of information that is presented visually! Can detect general patterns and trends! Can detect outliers and unusual patterns
45
Prof. Pier Luca Lanzi
Barplots
• They use horizontal or vertical bars to compare categories.
• One axis shows the compared categories, the other axis represents a discrete value
• Some bar graphs present bars clustered in groups of more than one (grouped bar graphs), and others show the bars divided into subparts to show cumulate effect (stacked bar graphs)
46
Prof. Pier Luca Lanzi
Barplot using R
# barplot barplot(wnum$outlook) ### ### distribution of outlook values ### splitted according to attribute windy ### counts <- table(wnum$windy,wnum$outlook) barplot(counts,col=c("darkblue","red")) # horizontal barplot(counts,col=c("darkblue","red"), horiz=TRUE) # grouped barplot(counts,col=c("darkblue","red"), horiz=TRUE, beside=TRUE)
47
Prof. Pier Luca Lanzi
Histograms
• They are a graphical representation of the distribution of data !introduced by Karl Pearson in 1895
• They estimate the probability distribution of a continuous variables
• They are representations of tabulated frequencies depicted as adjacent rectangles, erected over discrete intervals (bins). Their areas are proportional to the frequency of the observations in the interval.
48
Prof. Pier Luca Lanzi
Histograms
• The height of each bar indicates the number of objects• Shape of histogram depends on the number of bins
49
Example: Petal Width (10 and 20 bins, respectively)
Prof. Pier Luca Lanzi
Histograms in R
# distribution of temperature values hist(wnum$temperature, xlab="Temperature",
main="Temperature Distribution", col="blue") # fewer bins hist(wnum$temperature, breaks=2, xlab="Temperature",
main="Temperature Distribution", col="blue") # fit the distribution d <- density(wnum$temperature) plot(d, main="Temperature Distribution", xlab="Temperature") polygon(d, col="red", border="blue") # difference in bins the distribution hist(iris$petalwidth, col="blue", breaks=10, xlab="Petal Width", main="") hist(iris$petalwidth, col="blue", breaks=20, xlab="Petal Width", main="") d <- density(iris$petalwidth) plot(d, main="Petal Width Distribution", xlab="Petal Width") polygon(d, col="red", border="blue")
50
Prof. Pier Luca Lanzi
Maps
• Maps are a very effective communications tool that can visualize thousands of data points in just one figure
51
Prof. Pier Luca Lanzi
Mapping Data with R
# http://togaware.com/onepager/MapsO.pdf # required packages install.packages("maps") install.packages("ggmap") install.packages("oz") library(maps) library(ggmap) library(oz) library(ggplot2) library(scales) ds <- map_data("world") p <- ggplot(ds, aes(x=long, y=lat, group=group, fill=region)) p <- p + geom_polygon() p <- p + theme(legend.position = "none”)
52
Prof. Pier Luca Lanzi
Mapping Data with R
# World map p <- ggplot(ds, aes(x=long, y=lat, group=group, fill=region)) p <- p + geom_polygon() p <- p + theme(legend.position = "none") p # Map of Europe map <- get_map(location="Europe", zoom=4) p <- ggmap(map) p # Google Map map <- get_map(location="Sydney", zoom=14, maptype="roadmap", source="google") p <- ggmap(map) p
53
Prof. Pier Luca Lanzi
Mapping Data with R
# Mapping arrests arrests <- USArrests names(arrests) <- tolower(names(arrests)) arrests$region <- tolower(rownames(USArrests)) head(arrests) # maps the attribute state in their long/lat coordinates states <- map_data("state") # join the database of state information with the arrests information using region ds <- merge(states, arrests, sort=FALSE, by="region") # reorder the points for plotting otherwise the borders are plotted incorrectly ds <- ds[order(ds$order), ] g <- ggplot(ds, aes(long, lat, group=group, fill=ds$assault/ds$murder)) g <- g + geom_polygon() print(g)
54
Prof. Pier Luca Lanzi
Mapping Data for Visualization
• Data objects, their attributes, and the relationships among data objects are translated into graphical elements such as points, lines, shapes, and colors
• Objects are often represented as points
• Their attribute values can be represented as the position of the points or the characteristics of the points, e.g., color, size, and shape
• If position is used, then the relationships of points, i.e., whether they form groups or a point is an outlier, is easily perceived.
55
Prof. Pier Luca Lanzi
Data Arrangement
• Is the placement of visual elements within a display
• Influence on how easy it is to understand the data
56
Prof. Pier Luca Lanzi
Selection
• Is the elimination or the de-emphasis of !certain objects and attributes
• Selection may involve choosing a subset of attributes ! Dimensionality reduction is often used to reduce the number
of dimensions to two or three! Alternatively, pairs of attributes can be considered
• Selection may also involve choosing a subset of objects! A region of the screen can only show so many points! Can sample, but want to preserve points in sparse areas
57
Prof. Pier Luca Lanzi
Box Plots
• Box Plots (invented by Tukey)
• Another way of displaying the distribution of data
• Following figure shows !the basic part of a box plot
• IQR is the interquartile range !or Q3-Q1
58
outlier
Min (> Q1 -1.5 IQR)
1st quartile (Q1)
3rd quartile (Q3)
2nd quartile (Q2)
Max ( < Q3 +1.5 IQR)
Prof. Pier Luca Lanzi
Box Plot Example 59
Prof. Pier Luca Lanzi
Boxplots in R
# set working directory setwd("~/Dropbox/Documents/Online/Corsi/DMTM/data") # load data iris = read.arff("iris.arff") boxplot(iris[,1:4], ylab="values (cm)", main="iris dataset") boxplot(iris[,1:4], ylab="values (cm)", main="iris dataset", las=2, names=c("sep len", "sep wid", "pet len", "pet wid"), col=c("lightblue","lightblue","pink","pink"), at=c(1,2,5,6)) boxplot(iris[,1:4], ylab="values (cm)", main="iris dataset", las=2, names=c("sep len", "sep wid", "pet len", "pet wid"), border=c("blue","blue","green","green"), at=c(1,2,5,6)) # more examples # http://www.r-bloggers.com/box-plot-with-r-tutorial/
60
Prof. Pier Luca Lanzi
Scatter Plots
• Attributes values determine the position
• Two-dimensional scatter plots most common, but can have three-dimensional scatter plots
• Often additional attributes can be displayed by using the size, shape, and color of the markers that represent the objects
• It is useful to have arrays of scatter plots can compactly summarize the relationships of several pairs of attributes
• Examples: http://www.statmethods.net/graphs/scatterplot.html
61
Prof. Pier Luca Lanzi
Scatter Plots in R
# set working directory setwd("~/Dropbox/Documents/Online/Corsi/DMTM/data") # load data iris = read.arff("iris.arff") # attach iris to the path attach(iris) # plot scatter plot plot(petallength,sepallength, xlab="Petal Length", ylab="Sepal Length", pch=19) # linear model abline(lm(sepallength~petallength), col="red") # regression line (y~x) # local linear model lines(lowess(petallength, sepallength), col="blue") # lowess line (x,y)
62
Prof. Pier Luca Lanzi
Scatter Plots in R
library(car) scatterplot(sepallength~petallength | class, data=iris, xlab="Petal Length”, ylab="Sepal Length", main="Enhanced Scatter Plot", labels=row.names(iris))
63
Prof. Pier Luca Lanzi
Scatter Plot Array for Iris 64
Prof. Pier Luca Lanzi
Scatter Matrix Plots in R
# paired library(car) scatterplot(sepallength~petallength | class, data=iris, xlab="Petal Length", ylab="Sepal Length", main="Enhanced Scatter Plot", labels=row.names(iris)) png("~/Downloads/scatter1.png") # scatter plot matrix pairs(~petallength+petalwidth+sepallength+sepalwidth,data=iris, main="Simple Scatterplot Matrix") dev.off() library(car) png("~/Downloads/scatter2.png") # scatter plot matrix scatterplotMatrix(~petallength+petalwidth+sepallength+sepalwidth|class, data=iris, main="Scatter Plots vs Class") dev.off()
65
Prof. Pier Luca Lanzi
Scatter Plot Combined with Box Plots 66
Prof. Pier Luca Lanzi
Scatter Plots with Box Plots
# Add boxplots to a scatterplot par(fig=c(0,0.8,0,0.8), new=TRUE) plot(mtcars$wt, mtcars$mpg, xlab="Miles Per Gallon", ylab="Car Weight") par(fig=c(0,0.8,0.55,1), new=TRUE) boxplot(mtcars$wt, horizontal=TRUE, axes=FALSE) par(fig=c(0.65,1,0,0.8),new=TRUE) boxplot(mtcars$mpg, axes=FALSE) mtext("Enhanced Scatterplot", side=3, outer=TRUE, line=-3)
67
Prof. Pier Luca Lanzi
Contour Plots
• Useful for continuous attributes measured on a spatial grid
• They partition the plane into regions of similar values
• The contour lines that form the boundaries of these regions connect points with equal values
• The most common example is contour maps of elevation
• Can also display temperature, rainfall, air pressure, etc.
68
Prof. Pier Luca Lanzi
Celsius
Prof. Pier Luca Lanzi
Matrix Plots
• Can plot the data matrix
• This can be useful when objects are sorted according to class
• Typically, the attributes are normalized to prevent one attribute from dominating the plot
• Plots of similarity or distance matrices can also be useful for visualizing the relationships between objects
70
Prof. Pier Luca Lanzi
Heatmaps 71
dm <- data.matrix(iris[,1:4]) heatmap(dm)
Prof. Pier Luca Lanzi
additional exampleshttp://onepager.togaware.com/PlotsO.pdf
Prof. Pier Luca Lanzi
Other Visualization Techniques
• Star Plots ! Similar approach to parallel coordinates, !
but axes radiate from a central point! The line connecting the values of an object is a polygon
• Chernoff Faces! Approach created by Herman Chernoff! This approach associates each attribute with a characteristic of
a face! The values of each attribute determine the appearance of the
corresponding facial characteristic! Each object becomes a separate face! Relies on human’s ability to distinguish faces
73
Prof. Pier Luca Lanzi
Prof. Pier Luca Lanzi
Prof. Pier Luca Lanzi
Chernoff Faces
• More dimensions are plotted using several features of human faces
76
Prof. Pier Luca Lanzihttp://cartastrophe.files.wordpress.com/2010/06/spinelli.png
Prof. Pier Luca Lanzi
Prof. Pier Luca Lanzi
Chernoff Faces & Star/Radar Plots
# http://cran.r-project.org/web/packages/aplpack/aplpack.pdf library(foreign) library(aplpack) # set working directory setwd("~/Dropbox/Documents/Online/Corsi/DMTM/data") # load data iris = read.arff("iris.arff") # attach iris to the path attach(iris) # Chernoff faces faces(iris[1:16,1:4])
79
Prof. Pier Luca Lanzi
Chernoff Faces & Star/Radar Plots
require(grDevices) stars(mtcars[, 1:7], key.loc = c(14, 2), main = "Motor Trend Cars : stars(*, full = F)", full = FALSE) # full stars stars(mtcars[, 1:7], key.loc = c(14, 1.5), main = "Motor Trend Cars : full stars()", flip.labels = FALSE) # spider radar plot stars(mtcars[, 1:7], locations = c(0, 0), radius = FALSE, key.loc = c(0, 0), main = "Motor Trend Cars", lty = 2) # adding colors palette(rainbow(12, s = 0.6, v = 0.75)) stars(mtcars[, 1:7], len = 0.8, key.loc = c(12, 1.5), main = "Motor Trend Cars", draw.segments = TRUE) # positioning stars(mtcars[, 1:7], len = 0.6, key.loc = c(1.5, 0), main = "Motor Trend Cars", draw.segments = TRUE, nrow = 6, cex = .7) dev.off() faces(mtcars[,1:7])
80
Prof. Pier Luca Lanzi
examples
Prof. Pier Luca Lanzi
do we read the articles we share?
does my banner work?
Prof. Pier Luca Lanzi
“When we combined attention and traffic to find the story that had the largest volume of total engaged time, we found that it had fewer than 100 likes and fewer than 50 tweets. Conversely, the story with the largest number of tweets got about 20% of the total engaged time that the most engaging story received.”
Prof. Pier Luca Lanzi
“Here’s the skinny, 66% of attention on a normal media page is spent below the fold. That leaderboard at the top of the page? People scroll right past that and spend their time where the content not the cruft is. .”
Prof. Pier Luca Lanzi
http://time.com/12933/what-you-think-you-know-about-the-web-is-wrong/?iid=biz-category-mostpop2
Prof. Pier Luca Lanzi
http://apps.startribune.com/news/20140313-beer-me-minnesota/
Prof. Pier Luca Lanzi
Prof. Pier Luca Lanzi
Prof. Pier Luca Lanzi