# 10개 난수 생성
rnorm(10)
# 100개 난수 생성 후 절대값, 평균
mean(abs(rnorm(100))
# 100개 난수 생성 후 히스토그램
hist(rnorm(100))
2015년 9월 11일 금요일
[R] Text mining
# 라이브러리 설치
install.packages("xlsx", dependencies = TRUE)
library(tm)
library(wordcloud)
library(KoNLP)
library(arules)
library(arulesViz)
library(plyr)
library(igraph)
library(xlsx)
library(lsa)
# Keyword 도출
tmpString <- readLines("C:/Users/Hunhwa.Song/Desktop/Negative_h.txt")
tmpString
singleString <- paste(readLines("C:/Users/Hunhwa.Song/Desktop/Negative_h.txt"), collapse=" ")
singleString
singleString <- gsub("[[:space:]]", " ", singleString)
singleString
useSejongDic()
nouns <- extractNoun(singleString)
nouns <- nouns[nchar(nouns)>=2]
cnouns <- count(nouns)
pal <- brewer.pal(12,"Paired")
pal <- pal[-(1)]
wordcloud(words=cnouns$x, freq=cnouns$freq, scale = c(5, 0.5), rot.per = 0.1, colors=pal, min.freq=2, random.order=F)
install.packages("xlsx", dependencies = TRUE)
library(tm)
library(wordcloud)
library(KoNLP)
library(arules)
library(arulesViz)
library(plyr)
library(igraph)
library(xlsx)
library(lsa)
# Keyword 도출
tmpString <- readLines("C:/Users/Hunhwa.Song/Desktop/Negative_h.txt")
tmpString
singleString <- paste(readLines("C:/Users/Hunhwa.Song/Desktop/Negative_h.txt"), collapse=" ")
singleString
singleString <- gsub("[[:space:]]", " ", singleString)
singleString
useSejongDic()
nouns <- extractNoun(singleString)
nouns <- nouns[nchar(nouns)>=2]
cnouns <- count(nouns)
pal <- brewer.pal(12,"Paired")
pal <- pal[-(1)]
wordcloud(words=cnouns$x, freq=cnouns$freq, scale = c(5, 0.5), rot.per = 0.1, colors=pal, min.freq=2, random.order=F)
[R] SOM
# som package install
install.packages("som", dependencies = TRUE)
detach("package:kohonen", unload=TRUE)
library(som)
# Load the yeast dataset
data(yeast)
yeast <- yeast[, -c(1, 11)]
yeast <- normalize(yeast, byrow=FALSE)
# Train SOM with two different settings
som1 <- som(yeast, xdim=5, ydim=5, topol="rect", neigh="gaussian")
som2 <- som(yeast, xdim=5, ydim=5, topol="hexa", neigh="bubble")
# See the results
summary(som1)
plot(som1)
som1$visual[1:10,]
summary(som2)
plot(som2)
som2$visual[1:10,]
# kohonen package install
install.packages("kohonen", dependencies = TRUE)
detach("package:som", unload=TRUE)
library(kohonen)
data(wines)
trn = sample(nrow(wines), 120)
wines_trn <- scale(wines[trn,])
wines_tst <- scale(wines[-trn,], center = attr(wines_trn, "scaled:center"), scale = attr(wines_trn,"scaled:scale"))
som.wines <- som(wines_trn, grid = somgrid(5,5,"hexagonal"))
map(som.wines, wines_tst)
graphics.off()
par(mfrow = c(2, 2))
plot(som.wines, type = "property", property = som.wines$codes[,1], main = colnames(som.wines$codes)[1])
plot(som.wines, type = "property", property = som.wines$codes[,2], main = colnames(som.wines$codes)[2])
plot(som.wines, type = "property", property = som.wines$codes[,3], main = colnames(som.wines$codes)[3])
plot(som.wines, type = "property", property = som.wines$codes[,4], main = colnames(som.wines$codes)[4])
graphics.off()
par(mfrow = c(2, 2))
plot(som.wines, type = "quality")
plot(som.wines, type = "codes")
plot(som.wines, type = "changes")
install.packages("som", dependencies = TRUE)
detach("package:kohonen", unload=TRUE)
library(som)
# Load the yeast dataset
data(yeast)
yeast <- yeast[, -c(1, 11)]
yeast <- normalize(yeast, byrow=FALSE)
# Train SOM with two different settings
som1 <- som(yeast, xdim=5, ydim=5, topol="rect", neigh="gaussian")
som2 <- som(yeast, xdim=5, ydim=5, topol="hexa", neigh="bubble")
# See the results
summary(som1)
plot(som1)
som1$visual[1:10,]
summary(som2)
plot(som2)
som2$visual[1:10,]
# kohonen package install
install.packages("kohonen", dependencies = TRUE)
detach("package:som", unload=TRUE)
library(kohonen)
data(wines)
trn = sample(nrow(wines), 120)
wines_trn <- scale(wines[trn,])
wines_tst <- scale(wines[-trn,], center = attr(wines_trn, "scaled:center"), scale = attr(wines_trn,"scaled:scale"))
som.wines <- som(wines_trn, grid = somgrid(5,5,"hexagonal"))
map(som.wines, wines_tst)
graphics.off()
par(mfrow = c(2, 2))
plot(som.wines, type = "property", property = som.wines$codes[,1], main = colnames(som.wines$codes)[1])
plot(som.wines, type = "property", property = som.wines$codes[,2], main = colnames(som.wines$codes)[2])
plot(som.wines, type = "property", property = som.wines$codes[,3], main = colnames(som.wines$codes)[3])
plot(som.wines, type = "property", property = som.wines$codes[,4], main = colnames(som.wines$codes)[4])
graphics.off()
par(mfrow = c(2, 2))
plot(som.wines, type = "quality")
plot(som.wines, type = "codes")
plot(som.wines, type = "changes")
[R] K-means & Hierarchical Clustering
# Load the Iris dataset
data(iris)
# Remove the class label
newiris <- iris
newiris$Species <- NULL
# Perform K-Means Clustering with K=3
kc <- kmeans(newiris,3)
str(kc)
kc$centers
kc$size
kc$cluster
# Compare the assigned clusters and the Species
table(iris$Species, kc$cluster)
plot(newiris[,c("Sepal.Length", "Sepal.Width")], col = kc$cluster)
points(kc$centers[,c("Sepal.Length", "Sepal.Width")], col = 1:3, pch = 8, cex=2)
# Perform K-Means Clustering with K=5
kc <- kmeans(newiris,5)
# Compare the assigned clusters and the Species
table(iris$Species, kc$cluster)
plot(newiris[,c("Sepal.Length", "Sepal.Width")], col = kc$cluster)
points(kc$centers[,c("Sepal.Length", "Sepal.Width")], col = 1:5, pch = 8, cex=2)
# Creates a sample dataset
y <- matrix(rnorm(50), 10, 5, dimnames=list(paste("g", 1:10, sep=""), paste("t", 1:5, sep="")))
# Compute the similarity using the spearman coefficient
c <- cor(t(y), method="spearman")
d <- as.dist(1-c)
# Perform hierarchical clustering
hr <- hclust(d, method = "complete", members=NULL)
# plot the results
par(mfrow = c(2, 2))
plot(hr, hang = 0.1)
plot(hr, hang = -1)
plot(as.dendrogram(hr), edgePar=list(col=3, lwd=4), horiz=T)
# Prints the full content of the hclust object
unclass(hr)
# Prints dendrogram structure as text
str(as.dendrogram(hr))
# Prints the row labels in the order they appear in the tree
hr$labels[hr$order]
# Find the clusters
mycl <- cutree(hr, h=max(hr$height)/2)
mycl
plot(hr)
rect.hclust(hr, k=5, border="red")
# Imports color function to obtain heat maps in red and green.
# Use this color function in heatmap color argument like this: 'col=my.colorFct()'
source("http://faculty.ucr.edu/~tgirke/Documents/R_BioCond/My_R_Scripts/my.colorFct.R")
# Clusters rows by Pearson correlation as distance method.
hr <- hclust(as.dist(1-cor(t(y), method="pearson")), method="complete")
# Clusters columns by Spearman correlation as distance method.
hc <- hclust(as.dist(1-cor(y, method="spearman")), method="complete")
# The previous two hclust objects are used to obtain a heatmap
# where the rows are clusterd by Pearson and the columns by Spearman correlation distances.
# The 'scale' argument allows to scale the input matrix by rows or columns.
# The default is by rows and "none" turns the scaling off.
heatmap(y, Rowv=as.dendrogram(hr), Colv=as.dendrogram(hc), col=my.colorFct(), scale="row")
mycl <- cutree(hr, h=max(hr$height)/1.5)
mycol <- sample(rainbow(256))
mycol <- mycol[as.vector(mycl)]
heatmap(y, Rowv=as.dendrogram(hr), Colv=as.dendrogram(hc), col=my.colorFct(),
scale="row", ColSideColors=heat.colors(length(hc$labels)), RowSideColors=mycol)
data(iris)
# Remove the class label
newiris <- iris
newiris$Species <- NULL
# Perform K-Means Clustering with K=3
kc <- kmeans(newiris,3)
str(kc)
kc$centers
kc$size
kc$cluster
# Compare the assigned clusters and the Species
table(iris$Species, kc$cluster)
plot(newiris[,c("Sepal.Length", "Sepal.Width")], col = kc$cluster)
points(kc$centers[,c("Sepal.Length", "Sepal.Width")], col = 1:3, pch = 8, cex=2)
# Perform K-Means Clustering with K=5
kc <- kmeans(newiris,5)
# Compare the assigned clusters and the Species
table(iris$Species, kc$cluster)
plot(newiris[,c("Sepal.Length", "Sepal.Width")], col = kc$cluster)
points(kc$centers[,c("Sepal.Length", "Sepal.Width")], col = 1:5, pch = 8, cex=2)
# Creates a sample dataset
y <- matrix(rnorm(50), 10, 5, dimnames=list(paste("g", 1:10, sep=""), paste("t", 1:5, sep="")))
# Compute the similarity using the spearman coefficient
c <- cor(t(y), method="spearman")
d <- as.dist(1-c)
# Perform hierarchical clustering
hr <- hclust(d, method = "complete", members=NULL)
# plot the results
par(mfrow = c(2, 2))
plot(hr, hang = 0.1)
plot(hr, hang = -1)
plot(as.dendrogram(hr), edgePar=list(col=3, lwd=4), horiz=T)
# Prints the full content of the hclust object
unclass(hr)
# Prints dendrogram structure as text
str(as.dendrogram(hr))
# Prints the row labels in the order they appear in the tree
hr$labels[hr$order]
# Find the clusters
mycl <- cutree(hr, h=max(hr$height)/2)
mycl
plot(hr)
rect.hclust(hr, k=5, border="red")
# Imports color function to obtain heat maps in red and green.
# Use this color function in heatmap color argument like this: 'col=my.colorFct()'
source("http://faculty.ucr.edu/~tgirke/Documents/R_BioCond/My_R_Scripts/my.colorFct.R")
# Clusters rows by Pearson correlation as distance method.
hr <- hclust(as.dist(1-cor(t(y), method="pearson")), method="complete")
# Clusters columns by Spearman correlation as distance method.
hc <- hclust(as.dist(1-cor(y, method="spearman")), method="complete")
# The previous two hclust objects are used to obtain a heatmap
# where the rows are clusterd by Pearson and the columns by Spearman correlation distances.
# The 'scale' argument allows to scale the input matrix by rows or columns.
# The default is by rows and "none" turns the scaling off.
heatmap(y, Rowv=as.dendrogram(hr), Colv=as.dendrogram(hc), col=my.colorFct(), scale="row")
mycl <- cutree(hr, h=max(hr$height)/1.5)
mycol <- sample(rainbow(256))
mycol <- mycol[as.vector(mycl)]
heatmap(y, Rowv=as.dendrogram(hr), Colv=as.dendrogram(hc), col=my.colorFct(),
scale="row", ColSideColors=heat.colors(length(hc$labels)), RowSideColors=mycol)
[R] Association Rules
# Association Rules -------------------------------------------------------
# arules and arulesViz packages install
install.packages("arules", dependencies = TRUE)
install.packages("arulesViz", dependencies = TRUE)
install.packages("wordcloud", dependencies = TRUE)
library(arules)
library(arulesViz)
library(wordcloud)
# Load titanic data set
titanic <- read.delim("titanic.txt", dec=",")
str(titanic)
head(titanic)
# Remove "Name" column and group "Age" column
titanic_ar <- titanic[,2:5]
titanic_ar$Age = as.character(titanic_ar$Age)
c_idx <- which(as.numeric(titanic_ar$Age) < 20)
a_idx <- which(as.numeric(titanic_ar$Age) >= 20)
na_idx <- which(is.na(titanic_ar$Age))
titanic_ar$Age[c_idx] <- "Child"
titanic_ar$Age[a_idx] <- "Adult"
titanic_ar$Age[na_idx] <- "Unknown"
# Convert the attribues to factor
titanic_ar$Age <- as.factor(titanic_ar$Age)
titanic_ar$Survived <- as.factor(titanic_ar$Survived)
# Rule generation by Apriori algorithm with default settings
rules <- apriori(titanic_ar)
inspect(rules)
# Rule generation by Apriori algorithm with custom settings
rules <- apriori(titanic_ar, parameter = list(minlen = 3, support = 0.1, conf = 0.8),
appearance = list(rhs = c("Survived=0", "Survived=1"), default="lhs"))
inspect(rules)
# Plot the rules
plot(rules, method="scatterplot")
plot(rules, method="graph", control=list(type = "items", alpha = 1))
plot(rules, method="paracoord", control=list(reorder=TRUE))
# Load transaction data "Groceries"
data("Groceries")
summary(Groceries)
str(Groceries)
inspect(Groceries)
# Item inspection
itemName <- itemLabels(Groceries)
itemCount <- itemFrequency(Groceries)*9835
col <- brewer.pal(8, "Dark2")
wordcloud(words = itemName, freq = itemCount, min.freq = 1, scale = c(4, 0.2), col = col , random.order = FALSE)
itemFrequencyPlot(Groceries, support = 0.05, cex.names=0.8)
# Rule generation by Apriori
rules <- apriori(Groceries, parameter=list(support=0.005, confidence=0.5))
rules
# List the first three rules with the highest lift values
inspect(head(sort(rules, by="lift"),3))
# Save the rules in a text file
write.csv(as(rules, "data.frame"), "Groceries_rules.csv", row.names = FALSE)
# Plot the rules
plot(rules)
plot(rules, method="grouped")
# arules and arulesViz packages install
install.packages("arules", dependencies = TRUE)
install.packages("arulesViz", dependencies = TRUE)
install.packages("wordcloud", dependencies = TRUE)
library(arules)
library(arulesViz)
library(wordcloud)
# Load titanic data set
titanic <- read.delim("titanic.txt", dec=",")
str(titanic)
head(titanic)
# Remove "Name" column and group "Age" column
titanic_ar <- titanic[,2:5]
titanic_ar$Age = as.character(titanic_ar$Age)
c_idx <- which(as.numeric(titanic_ar$Age) < 20)
a_idx <- which(as.numeric(titanic_ar$Age) >= 20)
na_idx <- which(is.na(titanic_ar$Age))
titanic_ar$Age[c_idx] <- "Child"
titanic_ar$Age[a_idx] <- "Adult"
titanic_ar$Age[na_idx] <- "Unknown"
# Convert the attribues to factor
titanic_ar$Age <- as.factor(titanic_ar$Age)
titanic_ar$Survived <- as.factor(titanic_ar$Survived)
# Rule generation by Apriori algorithm with default settings
rules <- apriori(titanic_ar)
inspect(rules)
# Rule generation by Apriori algorithm with custom settings
rules <- apriori(titanic_ar, parameter = list(minlen = 3, support = 0.1, conf = 0.8),
appearance = list(rhs = c("Survived=0", "Survived=1"), default="lhs"))
inspect(rules)
# Plot the rules
plot(rules, method="scatterplot")
plot(rules, method="graph", control=list(type = "items", alpha = 1))
plot(rules, method="paracoord", control=list(reorder=TRUE))
# Load transaction data "Groceries"
data("Groceries")
summary(Groceries)
str(Groceries)
inspect(Groceries)
# Item inspection
itemName <- itemLabels(Groceries)
itemCount <- itemFrequency(Groceries)*9835
col <- brewer.pal(8, "Dark2")
wordcloud(words = itemName, freq = itemCount, min.freq = 1, scale = c(4, 0.2), col = col , random.order = FALSE)
itemFrequencyPlot(Groceries, support = 0.05, cex.names=0.8)
# Rule generation by Apriori
rules <- apriori(Groceries, parameter=list(support=0.005, confidence=0.5))
rules
# List the first three rules with the highest lift values
inspect(head(sort(rules, by="lift"),3))
# Save the rules in a text file
write.csv(as(rules, "data.frame"), "Groceries_rules.csv", row.names = FALSE)
# Plot the rules
plot(rules)
plot(rules, method="grouped")
[R] Linear Discriminant Analysis
# Classifier 3: Linear Discriminant Analysis ------------------------------
install.packages("MASS", dependencies = TRUE)
# Call the MASS package
library(MASS)
# Conduct LDA
lda_model <- lda(ploan_target ~ ., data = ploan_trn)
# Training result of LDA
plot(lda_model)
# Predict the unknown observations based on the LDA
lda_predict <- predict(lda_model, ploan_val)
names(lda_predict)
lda_predict$class
lda_predict$posterior
lda_predict$x
cm_lda <- table(ploan_val$ploan_target, lda_predict$class)
perf_mat[,4] <- perf_eval(cm_lda)
colnames(perf_mat) <- c("Naive Bayes", "LR with all variables", "LR with selected variables", "LDA")
rownames(perf_mat) <- c("TPR", "TNR", "ACC", "BCR")
perf_mat
install.packages("MASS", dependencies = TRUE)
# Call the MASS package
library(MASS)
# Conduct LDA
lda_model <- lda(ploan_target ~ ., data = ploan_trn)
# Training result of LDA
plot(lda_model)
# Predict the unknown observations based on the LDA
lda_predict <- predict(lda_model, ploan_val)
names(lda_predict)
lda_predict$class
lda_predict$posterior
lda_predict$x
cm_lda <- table(ploan_val$ploan_target, lda_predict$class)
perf_mat[,4] <- perf_eval(cm_lda)
colnames(perf_mat) <- c("Naive Bayes", "LR with all variables", "LR with selected variables", "LDA")
rownames(perf_mat) <- c("TPR", "TNR", "ACC", "BCR")
perf_mat
[R] Logistic Regression
# Classifier 2: Logistic Regression ---------------------------------------
# Conduct the normalization
ploan_input <- scale(ploan_input, center = TRUE, scale = TRUE)
ploan_target <- as.numeric(ploan_target)-1
ploan_data <- data.frame(ploan_input, ploan_target)
ploan_trn <- ploan_data[trn_idx,]
ploan_val <- ploan_data[-trn_idx,]
# Train the Logistic Regression Model with all variables
full_lr <- glm(ploan_target ~ ., family=binomial, ploan_trn)
full_lr
summary(full_lr)
# Train the Logistic Regression Model with selected variables
reduced_lr <- step(full_lr, direction = "backward")
summary(reduced_lr)
# Evaluate the logistic regression performance on the validation data
# Case 1: full model
full_response <- predict(full_lr, type = "response", newdata = ploan_val)
full_target <- ploan_val$ploan_target
full_predicted <- rep(0, length(full_target))
full_predicted[which(full_response >= 0.5)] <- 1
cm_full <- table(full_target, full_predicted)
perf_mat[,2] <- perf_eval(cm_full)
perf_mat
# Case 2: reduced model
reduced_response <- predict(reduced_lr, type = "response", newdata = ploan_val)
reduced_target <- ploan_val$ploan_target
reduced_predicted <- rep(0, length(reduced_target))
reduced_predicted[which(reduced_response >= 0.5)] <- 1
cm_reduced <- table(reduced_target, reduced_predicted)
perf_mat[,3] <- perf_eval(cm_reduced)
perf_mat
# Conduct the normalization
ploan_input <- scale(ploan_input, center = TRUE, scale = TRUE)
ploan_target <- as.numeric(ploan_target)-1
ploan_data <- data.frame(ploan_input, ploan_target)
ploan_trn <- ploan_data[trn_idx,]
ploan_val <- ploan_data[-trn_idx,]
# Train the Logistic Regression Model with all variables
full_lr <- glm(ploan_target ~ ., family=binomial, ploan_trn)
full_lr
summary(full_lr)
# Train the Logistic Regression Model with selected variables
reduced_lr <- step(full_lr, direction = "backward")
summary(reduced_lr)
# Evaluate the logistic regression performance on the validation data
# Case 1: full model
full_response <- predict(full_lr, type = "response", newdata = ploan_val)
full_target <- ploan_val$ploan_target
full_predicted <- rep(0, length(full_target))
full_predicted[which(full_response >= 0.5)] <- 1
cm_full <- table(full_target, full_predicted)
perf_mat[,2] <- perf_eval(cm_full)
perf_mat
# Case 2: reduced model
reduced_response <- predict(reduced_lr, type = "response", newdata = ploan_val)
reduced_target <- ploan_val$ploan_target
reduced_predicted <- rep(0, length(reduced_target))
reduced_predicted[which(reduced_response >= 0.5)] <- 1
cm_reduced <- table(reduced_target, reduced_predicted)
perf_mat[,3] <- perf_eval(cm_reduced)
perf_mat
[R] Naive Bayesian Classifier
# Performance Evaluation Function ---------------------------------
perf_eval <- function(cm){
# True positive rate: TPR
TPR = cm[2,2]/sum(cm[2,])
# True negative rate: TNR
TNR = cm[1,1]/sum(cm[1,])
# Simple Accuracy
ACC = (cm[1,1]+cm[2,2])/sum(cm)
# Balanced Correction Rate
BCR = sqrt(TPR*TNR)
return(c(TPR, TNR, ACC, BCR))
}
# Classifier 1: Naive Bayesian Classifier ---------------------------------
# e1071 package install
install.packages("e1071", dependencies = TRUE)
# Call the e1071 package
library(e1071)
ploan <- read.csv("Personal Loan.csv")
input_idx <- c(2,3,4,6,7,8,9,11,12,13,14)
target_idx <- 10
ploan_input <- ploan[,input_idx]
ploan_target <- as.factor(ploan[,target_idx])
ploan_data <- data.frame(ploan_input, ploan_target)
# Split the data into the training/validation sets
trn_idx <- sample(1:dim(ploan_data)[1], round(0.7*dim(ploan_data)[1]))
ploan_trn <- ploan_data[trn_idx,]
ploan_val <- ploan_data[-trn_idx,]
# Training the Naive Bayesian Classifier ~ left is indepen, ~ right is depen x1+X2+x3
nb_model <- naiveBayes(ploan_target ~ ., data = ploan_trn)
nb_model$apriori
nb_model$tables
# Predict the new input data based on Naive Bayesian Classifier
posterior = predict(nb_model, ploan_val, type = "raw")
nb_prey = predict(nb_model, ploan_val, type ="class")
# Generate a confusion matrix
cfmatrix <- table(ploan_val$ploan_target, nb_prey)
# Evaluate the performance
perf_mat <- matrix(0, 4, 4)
perf_mat[,1] <- perf_eval(cfmatrix)
perf_mat
perf_eval <- function(cm){
# True positive rate: TPR
TPR = cm[2,2]/sum(cm[2,])
# True negative rate: TNR
TNR = cm[1,1]/sum(cm[1,])
# Simple Accuracy
ACC = (cm[1,1]+cm[2,2])/sum(cm)
# Balanced Correction Rate
BCR = sqrt(TPR*TNR)
return(c(TPR, TNR, ACC, BCR))
}
# Classifier 1: Naive Bayesian Classifier ---------------------------------
# e1071 package install
install.packages("e1071", dependencies = TRUE)
# Call the e1071 package
library(e1071)
ploan <- read.csv("Personal Loan.csv")
input_idx <- c(2,3,4,6,7,8,9,11,12,13,14)
target_idx <- 10
ploan_input <- ploan[,input_idx]
ploan_target <- as.factor(ploan[,target_idx])
ploan_data <- data.frame(ploan_input, ploan_target)
# Split the data into the training/validation sets
trn_idx <- sample(1:dim(ploan_data)[1], round(0.7*dim(ploan_data)[1]))
ploan_trn <- ploan_data[trn_idx,]
ploan_val <- ploan_data[-trn_idx,]
# Training the Naive Bayesian Classifier ~ left is indepen, ~ right is depen x1+X2+x3
nb_model <- naiveBayes(ploan_target ~ ., data = ploan_trn)
nb_model$apriori
nb_model$tables
# Predict the new input data based on Naive Bayesian Classifier
posterior = predict(nb_model, ploan_val, type = "raw")
nb_prey = predict(nb_model, ploan_val, type ="class")
# Generate a confusion matrix
cfmatrix <- table(ploan_val$ploan_target, nb_prey)
# Evaluate the performance
perf_mat <- matrix(0, 4, 4)
perf_mat[,1] <- perf_eval(cfmatrix)
perf_mat
[R] Forecasting - ARIMA Model
# ACF 및 PACF plot 확인
acf(training_timeseries)
pacf(training_timeseries)
# diff 함수를 활용하여 differencing 수행
training_timeseries_diff = diff(training_timeseries, difference = 2)
# differencing 결과를 통해 Autocorrelation 재확인
acf(training_timeseries_diff)
pacf(training_timeseries_diff)
# arima 함수를 통해 ARIMA (p,d,q) 모델 구축
model = arima(training_timeseries, order = c(1,1,1))
model$aic
model = arima(training_timeseries, order = c(1,1,2))
model$aic
model = arima(training_timeseries, order = c(2,1,1))
model$aic
model = arima(training_timeseries, order = c(2,1,2))
model$aic
model = arima(training_timeseries, order = c(1,2,1))
model$aic
model = arima(training_timeseries, order = c(1,2,2))
model$aic
model = arima(training_timeseries, order = c(2,2,1))
model$aic
model = arima(training_timeseries, order = c(2,2,2))
model$aic
# AIC가 가장 작은 ARIMA (1,2,2) 모델 구축
model = arima(training_timeseries, order = c(1,2,2))
model$aic
# AIC가 가장 작은 ARIMA (1,2,2) 모델 구축
forecast = forecast.Arima(model, h = 10)
summary(forecast)
plot(forecast)
MAE_result = mean(abs(testing - forecast$mean))
MAPE_result = mean(abs(testing - forecast$mean) / testing)*100
acf(training_timeseries)
pacf(training_timeseries)
# diff 함수를 활용하여 differencing 수행
training_timeseries_diff = diff(training_timeseries, difference = 2)
# differencing 결과를 통해 Autocorrelation 재확인
acf(training_timeseries_diff)
pacf(training_timeseries_diff)
# arima 함수를 통해 ARIMA (p,d,q) 모델 구축
model = arima(training_timeseries, order = c(1,1,1))
model$aic
model = arima(training_timeseries, order = c(1,1,2))
model$aic
model = arima(training_timeseries, order = c(2,1,1))
model$aic
model = arima(training_timeseries, order = c(2,1,2))
model$aic
model = arima(training_timeseries, order = c(1,2,1))
model$aic
model = arima(training_timeseries, order = c(1,2,2))
model$aic
model = arima(training_timeseries, order = c(2,2,1))
model$aic
model = arima(training_timeseries, order = c(2,2,2))
model$aic
# AIC가 가장 작은 ARIMA (1,2,2) 모델 구축
model = arima(training_timeseries, order = c(1,2,2))
model$aic
# AIC가 가장 작은 ARIMA (1,2,2) 모델 구축
forecast = forecast.Arima(model, h = 10)
summary(forecast)
plot(forecast)
MAE_result = mean(abs(testing - forecast$mean))
MAPE_result = mean(abs(testing - forecast$mean) / testing)*100
[R] Forecasting - HoltWinters
# forecast 라이브러리 설치 및 불러오기
install.packages("forecast")
library(forecast)
# 분석데이터 불러오기
ex_data = read.csv("C:/Users/user/Desktop/연간 국민 총 생산.csv", header = TRUE)
training = ex_data[1:35,2]
testing = ex_data[36:45,2]
# 시계열 형태의 데이터로 변환
training_timeseries = ts(training, frequency = 1)
testing_timeseries = ts(testing, frequency = 1)
plot.ts(training_timeseries)
# 단일지수 평활 모델 구축
model = HoltWinters(training_timeseries, alpha = 0.1, beta = FALSE, gamma = FALSE)
# 모델에서 얻은 training data에 대한 추정치와 실제 값을 비교하는 plot
plot(model$fitted[,1])
lines(training_timeseries, col = "red")
# 구축된 모델을 활용하여 향후 10시점까지를 예측하고 MAE를 통해 예측 성능 비교
forecast = forecast.HoltWinters(model, h = 10)
plot(forecast)
# 이중지수 평활 모델 구축
model = HoltWinters(training_timeseries, alpha = 0.2, beta = 0.3, gamma = FALSE)
# 모델에서 얻은 training data에 대한 추정치와 실제 값을 비교하는 plot
plot(model$fitted[,1])
lines(training_timeseries, col = "red")
# 구축된 모델을 활용하여 향후 10시점까지를 예측하고 MAE를 통해 예측 성능 비교
forecast = forecast.HoltWinters(model, h = 10) # 예측결과는 forecast에 저장됨
plot(forecast)
# testing data의 실제 값과 예측 값의 차이를 MAE와 MAPE를 통해서 비교
MAE_result = mean(abs(testing - forecast$mean))
MAPE_result = mean(abs(testing - forecast$mean) / testing)*100
install.packages("forecast")
library(forecast)
# 분석데이터 불러오기
ex_data = read.csv("C:/Users/user/Desktop/연간 국민 총 생산.csv", header = TRUE)
training = ex_data[1:35,2]
testing = ex_data[36:45,2]
# 시계열 형태의 데이터로 변환
training_timeseries = ts(training, frequency = 1)
testing_timeseries = ts(testing, frequency = 1)
plot.ts(training_timeseries)
# 단일지수 평활 모델 구축
model = HoltWinters(training_timeseries, alpha = 0.1, beta = FALSE, gamma = FALSE)
# 모델에서 얻은 training data에 대한 추정치와 실제 값을 비교하는 plot
plot(model$fitted[,1])
lines(training_timeseries, col = "red")
# 구축된 모델을 활용하여 향후 10시점까지를 예측하고 MAE를 통해 예측 성능 비교
forecast = forecast.HoltWinters(model, h = 10)
plot(forecast)
# 이중지수 평활 모델 구축
model = HoltWinters(training_timeseries, alpha = 0.2, beta = 0.3, gamma = FALSE)
# 모델에서 얻은 training data에 대한 추정치와 실제 값을 비교하는 plot
plot(model$fitted[,1])
lines(training_timeseries, col = "red")
# 구축된 모델을 활용하여 향후 10시점까지를 예측하고 MAE를 통해 예측 성능 비교
forecast = forecast.HoltWinters(model, h = 10) # 예측결과는 forecast에 저장됨
plot(forecast)
# testing data의 실제 값과 예측 값의 차이를 MAE와 MAPE를 통해서 비교
MAE_result = mean(abs(testing - forecast$mean))
MAPE_result = mean(abs(testing - forecast$mean) / testing)*100
[R] Descriptive statistics
# 기술통계
mean(data$X)
str(data$X)
mean(data$X)
str(data$X)
quantile(iris$Sepal.Length, seq(0,1,by=0.05))
# psych 패키지
install.packages("psych")
# psych 패키지
install.packages("psych")
describe(data)
[R] Decision Tree
# 라이브러리 설치
install.packages("rpart")
library(rpart)
# 데이터 불러오기
ex_data = read.csv("iris.csv", header = TRUE)
# 의사결정나무 모델 구축
model = rpart(Class ~., data=ex_data, method = "class")
# 의사결정나무 모델 시각화
plot(model, uniform = TRUE)
text(model, use.n = TRUE, all = TRUE, cex = 0.8)
# Training data와 Testing data를 분할하여 모델의 성능 검증
train = ex_data[1:120,]
test = ex_data[121:150,]
# Training data를 활용하여 모델 구축
model = rpart(Class ~., data=train, method = "class")
# 모델을 testing 데이터에 적용하여 table 형태로 결과 확인
pred = predict(model, newdata = test, type = "class")
table(pred, test$Class)
install.packages("rpart")
library(rpart)
# 데이터 불러오기
ex_data = read.csv("iris.csv", header = TRUE)
# 의사결정나무 모델 구축
model = rpart(Class ~., data=ex_data, method = "class")
# 의사결정나무 모델 시각화
plot(model, uniform = TRUE)
text(model, use.n = TRUE, all = TRUE, cex = 0.8)
# Training data와 Testing data를 분할하여 모델의 성능 검증
train = ex_data[1:120,]
test = ex_data[121:150,]
# Training data를 활용하여 모델 구축
model = rpart(Class ~., data=train, method = "class")
# 모델을 testing 데이터에 적용하여 table 형태로 결과 확인
pred = predict(model, newdata = test, type = "class")
table(pred, test$Class)
[R] Data Management
# 특정 열만 선택
data1 <- data[,2:5]
input_idx <- c(1,2,3)
target_idx <- 4
# select 1st and 5th thru 10th variables
newdata <- mydata[c(1,5:10)]
# exclude 3rd and 5th variable
newdata <- mydata[c(-3,-5)]
# delete variables v3 and v5
mydata$v3 <- mydata$v5 <- NULL
# 변수명 수정
colnames(data1) <- c("recog", "expense", "prefer", "sales")
colnames(data2) <- c("X1", "X2", "X3", "Y")
# rename the variable names
library(reshape)
test <- rename(test, c(target="newname"))
# 변수 특성 변경
expense <- as.numeric(data1$expense)
sales <- as.numeric(data1$sales)
# 변수 합성으로 새로운 데이터 프레임 생성
data2 <- data.frame(expense, data1$recog, data1$prefer, sales)
# 표준화 후 데이터 프레임 생성
data3 <- data.frame(scale(data2, center = TRUE, scale = TRUE))
# 행열 추가
rbind(data, list("A", 13))
cbind(data, states = c("NA", 23))
# 데이터 프레임 병합
merge(data1, data2)
merge(data1, data2, by.x="sex", by.z="gender"
# 데이터 정렬
order(data) # by asc
order(-data) # by desc
# 중복값 제거 (iduser 중복된 값 제외됨)
newdata <- data[!duplicated(active$iduser), ]
data1 <- data[,2:5]
input_idx <- c(1,2,3)
target_idx <- 4
# select 1st and 5th thru 10th variables
newdata <- mydata[c(1,5:10)]
# exclude 3rd and 5th variable
newdata <- mydata[c(-3,-5)]
# delete variables v3 and v5
mydata$v3 <- mydata$v5 <- NULL
# 변수명 수정
colnames(data1) <- c("recog", "expense", "prefer", "sales")
colnames(data2) <- c("X1", "X2", "X3", "Y")
# rename the variable names
library(reshape)
test <- rename(test, c(target="newname"))
# 변수 특성 변경
expense <- as.numeric(data1$expense)
sales <- as.numeric(data1$sales)
# 변수 합성으로 새로운 데이터 프레임 생성
data2 <- data.frame(expense, data1$recog, data1$prefer, sales)
# 표준화 후 데이터 프레임 생성
data3 <- data.frame(scale(data2, center = TRUE, scale = TRUE))
# 행열 추가
rbind(data, list("A", 13))
cbind(data, states = c("NA", 23))
# 데이터 프레임 병합
merge(data1, data2)
merge(data1, data2, by.x="sex", by.z="gender"
# 데이터 정렬
order(data) # by asc
order(-data) # by desc
# 중복값 제거 (iduser 중복된 값 제외됨)
newdata <- data[!duplicated(active$iduser), ]
[R] Testing model
# 별도 검증용 데이터 준비 후 검증
pred = predict(model1, test)
plot(test$Price, pred)
plot(test$Price, type = "b", col = "blue", lty = 1)
points(pred, col = "red", lty = 3, type = "b")
pred = predict(model1, test)
plot(test$Price, pred)
plot(test$Price, type = "b", col = "blue", lty = 1)
points(pred, col = "red", lty = 3, type = "b")
[R] Regression analysis
# 선형회귀분석
model = lm(Y~., data = data)
model <- lm(Y~X1+X2+X4, data = data)
# 결과 요약
summary(model)
# 두 변수 간 선형관계 확인
x = data$KM
y = data$Price
plot(x,y)
# 전차 확인
plot(model$residual)
abline(h = 0)
qqnorm(model$residual)
qqline(model$residual)
# 잔차 제거
data1 = data[model$residual > -4500 & (model$residual < 4500),]
# 참고
resid(lm(y~x, data=df, na.action=na.omit)) # na값 제외하고 계산
resid(lm(y~x, data=df, na.action=na.exclude)) # na값 제외하고 계산
model = lm(Y~., data = data)
model <- lm(Y~X1+X2+X4, data = data)
# 결과 요약
summary(model)
# 두 변수 간 선형관계 확인
x = data$KM
y = data$Price
plot(x,y)
# 전차 확인
plot(model$residual)
abline(h = 0)
qqnorm(model$residual)
qqline(model$residual)
# 잔차 제거
data1 = data[model$residual > -4500 & (model$residual < 4500),]
# 참고
resid(lm(y~x, data=df, na.action=na.omit)) # na값 제외하고 계산
resid(lm(y~x, data=df, na.action=na.exclude)) # na값 제외하고 계산
[R] Correlation test
# scatter plot을 통해 변수 간 상관분석
pairs(data, data = data)
#상관분석
cor.test(X, Y, alternative = "two.sided", method = "pearson")
pairs(data, data = data)
#상관분석
cor.test(X, Y, alternative = "two.sided", method = "pearson")
[R] EDA
# data에 포함된 관측치의 개수
nrow(data)
# data에 포함된 변수의 개수
ncol(data)
# data에 포함된 변수명
colnames(data)
# 초반에 위치한 대표 데이터
head(data)
# Y변수의 히스토그램
hist(data$Y)
# 박스플롯
boxplot(data$Y)
# 열 개수
length(data)
nrow(data)
# data에 포함된 변수의 개수
ncol(data)
# data에 포함된 변수명
colnames(data)
# 초반에 위치한 대표 데이터
head(data)
# Y변수의 히스토그램
hist(data$Y)
# 박스플롯
boxplot(data$Y)
# 열 개수
length(data)
[R] Read / Write data
# 데이터 불러오기, 첫번째 행에 변수명 포함
data<- read.csv("data.csv", header = T)
data<- read.csv("data.csv", header = T)
data<- read.table("data.txt", header = T, sep=",")
# 엑셀데이터 불러오기
dataM<-read.xlsx(data.xlsx, sheetname = "sheet")
# 데이터 내보내기
write.csv(data, "data.csv", row.names=F)
# 엑셀데이터 불러오기
library(xlsx)
data<- read.xlsx(data.xlsx, 1)dataM<-read.xlsx(data.xlsx, sheetname = "sheet")
# 데이터 내보내기
write.csv(data, "data.csv", row.names=F)
피드 구독하기:
글 (Atom)