• R-9 2020.09.05
반응형
library(ggplot2)
library(dplyr)
library(RColorBrewer)
library(ggthemes)
install.packages("ggrepel")
library(ggrepel)
install.packages("chron")
library(chron)
library(lubridate)
install.packages("xts")
library(xts)
install.packages("highcharter")
library(highcharter)

data <- read.csv("ctrucks_clean.csv",stringsAsFactors = F)
head(data)
str(data)
summary(data)

data$origin = as.factor(data$origin)#출발지 
data$supplier = as.factor(data$supplier)
data$Date = ymd(data$Date)#ymd형태로"2017-04-10"
data$month = month(data$month, label = T)
data$week_day = weekdays(data$Date, abbreviate = T)#요일 표현한다.
#열이 있으면 보여주고 없으면 만들어준다.
#MUTATE

#지난 3년간 가장 많은 수소을 담당한
str(data)
#트력 아이디 별로 빈도소 찾아서 내림차순별로
#1.
truck <- data %>% group_by(truckid) %>% summarise(freq= n()) %>% top_n(20)

library(ggplot2)
library(dplyr)
library(RColorBrewer)
library(ggthemes)
install.packages("ggrepel")
library(ggrepel)
install.packages("chron")
library(chron)
library(lubridate)
install.packages("xts")
library(xts)
install.packages("highcharter")
library(highcharter)

data <- read.csv("ctrucks_clean.csv",stringsAsFactors = F)
head(data)
str(data)
summary(data)

data$origin = as.factor(data$origin)#출발지 
data$supplier = as.factor(data$supplier)
data$Date = ymd(data$Date)#ymd형태로"2017-04-10"
data$month = month(data$month, label = T)
data$week_day = weekdays(data$Date, abbreviate = T)#요일 표현한다.
#열이 있으면 보여주고 없으면 만들어준다.
#MUTATE

#지난 3년간 가장 많은 수소을 담당한
str(data)
#트력 아이디 별로 빈도소 찾아서 내림차순별로
#1.
truck <- data %>% group_by(truckid) %>% summarise(freq= n()) %>% top_n(20)
truck
data %>% filter(truckid =='1073FL01')
data %>% filter(truckid =='7922GR01')
#2.
truck1 <- data %>% group_by(truckid) %>% summarise(freq = n()) %>% arrange(desc(freq)) %>% head(20)
truck1

 

truck3 <- data %>%
  group_by(truckid) %>%
  summarize(freq = n()) %>%   
  arrange(desc(freq)) %>%  head(20) %>% as.data.frame()
truck3

#reorder 재정렬 하는 것이다.
ggplot(data = truck, aes(reorder(truckid, freq), y= freq, fill= freq))+
  geom_bar(stat ="identity",position="dodge")+xlab("Truck")+ylab("Frequency")+coord_flip()

#15를 25로 바꿀 수 있다.
par(mfrow= c(1,2))
ggplot(data = truck, aes(reorder(truckid, freq), y= freq, fill= freq))+
  geom_bar(stat ="identity",position="dodge")+xlab("Truck")+ylab("Frequency")+
 scale_fill_gradientn(name ="",
                    colours =rev(brewer.pal(10, 'Spectral')))+
  geom_text(aes(label = freq ), hjust= 0.5, size = 5.5)+
  ggtitle("The top 20 Trucks with the most deliveries")+
  theme( legend.position = 'none',
         axis.title.y = element_text(size = 15),
         axis.text.y = element_text(size = 15),
         axis.title.x = element_text(size = 15),
         axis.text.x= element_text(size = 15),
         plot.title = element_text(size = 15, hjust = 0.2))+coord_flip()
#scale_fill_gradientn
#coord_flip
#brewer.pal

 

ggplot(data = truck, aes(reorder(truckid, freq), y= freq, fill= freq))+
  geom_bar(stat ="identity",position="dodge")+xlab("Truck")+ylab("Frequency")+
  scale_fill_gradientn(name ="",
                       colours =rev(brewer.pal(10, 'Set3')))+
  geom_text(aes(label = freq ), hjust= 0.5, size = 5.5)+#옆에 있는 빈도수 바꾸기 
  ggtitle("The top 20 Trucks with the most deliveries")+
  theme( legend.position = 'none',
         axis.title.y = element_text(size = 25),
         axis.text.y = element_text(size = 25),
         axis.title.x = element_text(size = 25),
         axis.text.x= element_text(size = 25),
         plot.title = element_text(size = 25, hjust = 0.2))+coord_flip()
#legend.position d없을 경우 legend 없다.
display.brewer.all()
#ggplot도 함수이다.

data %>%
  group_by(truckid) %>%
  summarize(freq = n()) %>%   
  arrange(desc(freq)) %>%  head(20) %>% as.data.frame()+
ggplot(data,aes(reorder(truckid, freq), y= freq, fill= freq))+
  geom_bar(stat ="identity",position="dodge")+xlab("Truck")+ylab("Frequency")+
  scale_fill_gradientn(name ="",
                       colours =rev(brewer.pal(10, 'Set3')))+
  geom_text(aes(label = freq ), hjust= 0.5, size = 5.5)+#옆에 있는 빈도수 바꾸기 
  ggtitle("The top 20 Trucks with the most deliveries")+
  theme( legend.position = 'none',
         axis.title.y = element_text(size = 25),
         axis.text.y = element_text(size = 25),
         axis.title.x = element_text(size = 25),
         axis.text.x= element_text(size = 25),
         plot.title = element_text(size = 25, hjust = 0.2))+coord_flip()  
data %>%
  group_by(truckid) %>%
  summarize(freq = n()) %>%   
  arrange(desc(freq)) %>%  head(20) %>% as.data.frame() %>% 
  ggplot(aes(reorder(truckid, freq), y= freq, fill= freq))+
  geom_bar(stat ="identity",position="dodge")+xlab("Truck")+ylab("Frequency")+
  scale_fill_gradientn(name ="",
                       colours =rev(brewer.pal(10, 'Set3')))+
  geom_text(aes(label = freq ), hjust= 0.5, size = 5.5)+#옆에 있는 빈도수 바꾸기 
  ggtitle("The top 20 Trucks with the most deliveries")+
  theme( legend.position = 'none',
         axis.title.y = element_text(size = 25),
         axis.text.y = element_text(size = 25),
         axis.title.x = element_text(size = 25),
         axis.text.x= element_text(size = 25),
         plot.title = element_text(size = 25, hjust = 0.2))+coord_flip() 



data %>% group_by(week_day,month) %>% count()
data %>% group_by(week_day,month) %>% count() %>% 
  ggplot(aes(reorder(week_day, n ), y = n , fill = n ))+
  geom_bar(stat ="identity",position ="dodge")+
  xlab("Day")+
  ylab("Delivery Count")+
  scale_fill_gradientn(name ="",
                       colours =rev(brewer.pal(10, 'Spectral')))+
  geom_text(aes(label = n ), hjust=- 0.3, size = 3.5)+#옆에 있는 빈도수 바꾸기 
  ggtitle("Delivery Counts through the Days by Month")+
  facet_wrap( ~ month)+
  theme( legend.position = 'none',
         axis.title.y = element_text(size = 15),
         axis.text.y = element_text(size = 10),
         axis.title.x = element_text(size = 15),
         axis.text.x= element_text(size = 10),
         plot.title = element_text(size = 25, hjust = 0.2),
         strip.text = element_text(size = 8, face ="bold"),
         strip.background = element_rect(colour = "red",fill="#CCCCFF")) 


data %>% group_by(week_day,month) %>% count() %>% 
  ggplot(aes(reorder(week_day, n ), y = n , fill = n ))+
  geom_bar(stat ="identity",position ="dodge")+
  xlab("Day")+
  ylab("Delivery Count")+
  scale_fill_gradientn(name ="",
                       colours =rev(brewer.pal(10, 'Spectral')))+
  geom_text(aes(label = n ), hjust=- 0.3, size = 3.5)+#옆에 있는 빈도수 바꾸기 
  ggtitle("Delivery Counts through the Days by Month")+
  facet_wrap( ~ month)+
  theme( legend.position = 'none',
         axis.title.y = element_text(size = 15),
         axis.text.y = element_text(size = 10),
         axis.title.x = element_text(size = 15),
         axis.text.x= element_text(size = 10),
         plot.title = element_text(size = 25, hjust = 0.2),
         strip.text = element_text(size = 15, face ="bold"),
         strip.background = element_rect(colour = "red",fill="#CCCCFF")) +coord_flip() 
#coord_flip() 옆으로 펼쳐진다.

data$month
data %>%filter(month != 2 & month != 6 & month != 7)%>% group_by(week_day,month)%>% count() %>% 
  ggplot(aes(reorder(week_day, n ), y = n , fill = n ))+
  geom_bar(stat ="identity",position ="dodge")+
  xlab("Day")+
  ylab("Delivery Count")+
  scale_fill_gradientn(name ="",
                       colours =rev(brewer.pal(10, 'Spectral')))+
  geom_text(aes(label = n ), hjust=- 0.3, size = 3.5)+#옆에 있는 빈도수 바꾸기 
  ggtitle("Delivery Counts through the Days by Month")+
  facet_wrap( ~ month)+
  theme( legend.position = 'none',
         axis.title.y = element_text(size = 15),
         axis.text.y = element_text(size = 10),
         axis.title.x = element_text(size = 15),
         axis.text.x= element_text(size = 10),
         plot.title = element_text(size = 25, hjust = 0.2),
         strip.text = element_text(size = 8, face ="bold"),
         strip.background = element_rect(colour = "red",fill="#CCCCFF")) 
# facet_wrap( ~ month)옆으로 펼치기
#month ==3 | month == 4 | month == 5
data %>%filter(! month %in% c(2,6,7))%>% group_by(week_day,month)%>% count() %>% 
  ggplot(aes(reorder(week_day, n ), y = n , fill = n ))+
  geom_bar(stat ="identity",position ="dodge")+
  xlab("Day")+
  ylab("Delivery Count")+
  scale_fill_gradientn(name ="",
                       colours =rev(brewer.pal(10, 'Spectral')))+
  geom_text(aes(label = n ), hjust=- 0.3, size = 3.5)+#옆에 있는 빈도수 바꾸기 
  ggtitle("Delivery Counts through the Days by Month")+
  facet_wrap( ~ month)+
  theme( legend.position = 'none',
         axis.title.y = element_text(size = 15),
         axis.text.y = element_text(size = 10),
         axis.title.x = element_text(size = 15),
         axis.text.x= element_text(size = 10),
         plot.title = element_text(size = 25, hjust = 0.2),
         strip.text = element_text(size = 8, face ="bold"),
         strip.background = element_rect(colour = "red",fill="#CCCCFF")) 
#색상을 fill로 채워야 한다.
data$Date

by_date_2015 <- data %>% filter(Date <= ('2016-01-01')) %>% 
  group_by(Date) %>% summarise(Total = n())
by_date_2015

time_series = xts(by_date_2015$Total, order.by = by_date_2015$Date)
hchart(time_series, name ="Number of Deliberies") %>% 
  hc_title(text = "Total Deliveries for 2015") %>% 
  hc_legend(enabled = T)

by_date_2016 = na.omit(data) %>% filter(Date >= ('2016-01-01') & Date <('2017-01-01')) %>% 
  group_by(Date) %>% 
  summarise(Total = n())

time_series = xts(by_date_2016$Total, order.by = by_date_2016$Date)

hchart(time_series, name ="Number of Deliveries") %>% 
  hc_add_theme(hc_theme_darkunica()) %>% 
  hc_title(text ="Total Deliveries for 2016") %>% 
  hc_legend(enaled = T)

churn데이터 고객이탈 데이터
어떤 분이 해지 하는지 알고 싶을때 
#상관관계 확인 126페이지 
#상관관계가 1이 나오면 낮동안 통화한 데이터 ,낮시간 금액
#예시: ‚cars‛ 데이터(내장 데이터) 
#• 상관관계 확인: 회귀분석은 기본적으로 상관관계에 대핚 통계적 분석 
#• 인과관계를 주장하려면 추가적으로 통계 외적인 귺거가 필요 (예: 해당 분야의 이롞적 귺거, 실험의 경우 변인통제, …) 

 Coefficient 관계
기무가설이 기각이 되면 상관관계가 없지 않아요 
speed 변수는 값이 매우 작으므로 유의하다. 

 

cars
data1 <- cars#151
plot(data1)
library(ggplot2)
ggplot(data = data1, aes(x= speed, y= dist ))+geom_point()#153

cor(data1)#상관행렬 
cor.test(data1$speed,data1$dist)

install.packages("corrplot")
library(corrplot)
#dataframe의 cor값이 들어간다.cor(data1)
corrplot::corrplot.mixed(cor(data1))

data2 <- airquality
corrplot::corrplot.mixed(cor(data2))

data3 <- mpg
corrplot::corrplot.mixed(cor(data3))#Error in cor(data3) : 'x' must be numeric
corrplot::corrplot.mixed(cor(mtcars))

fit.cars <- lm(dist ~ speed , data = cars)
fit.cars

summary(fit.cars)
#별표가 붙어 있다. signif 무의미한 
#0에 가까운 것을 잘 띄울수록 별표 표시해주고 
#별새계가 중요하다

잔차분석 
상관관계 1이면 선에 붙어있다.
잔차 원래 데이터 문제를 잔차가지고 정규분포한다.
잔차들이 일정한 모습을 가져야 하면 안된다.
잔차는 아무것이나  random하게 해야 한다.

 

new <- data.frame(speed = c(122))
predict(fit.cars, newdata = new ,interval = "confidence")
predict(fit.cars, newdata = new ,interval = "confidence",level= 0.9)
predict(fit.cars, newdata = new ,interval = "prediction")
#이선자체가 맞다는 보장성이 없어서 prediction 
# confidence 범위보다 넓다.

fit <- lm( dist ~ speed, data = cars)
fit
plot(fit)

par(mfrow= c(2,2))#multi figure
plot(fit)
#fitted 잔차는 0이다. random하게 영향성이 없이 잘 분포되여있다. 빨간선
#빨간선이 포물선처럼 되면 별로 좋지 않다.
#q-q plot qiantiles 45도 회귀의 기울기로 점들이 아래위로 하면서 따라간다.숫자는 이상치가 있다 윗부분이 잘 안 딸아간다.
#scale-Location scale표준화 random하게 있어줘야 한다.
#Residuals vs Leverage 잔차 0.5 안쪽으로 벗어나지 말아야 한다. 빨간색 안쪽으로 그 사이에 있으면 된다.


#Fitted values
#1번 그림 가지고 하면 된다.
plot(fit.cars, 1)
#잒차도를 확인해보니 적합값 (Fitted values)이 커질수록 잒차가 넓게 퍼지는 경향이 보인다. 
install.packages("lmtest")
library(lmtest)
install.packages("car")
library(car)
#잔차분석 – 등분산성 검정 
#규칙없이 흩어져야 한다.
bptest(fit.cars)
#잔차분석을 할 때 잔차도를 보고 판단하는 것 뿐만 아니라 잒차에 대핚 검정 또핚 가능하다.  
#유의확률(p-value)이 작으면 등분산성 가정에 문제가 있을 수 있다 (등분산성 가정을 의심해봐야 핚다). 
ncvTest(fit.cars)#car library
#p-value = 0.07297->기무가설을 체택하는 쪽으로 선택한다.
#p = 0.031049
#p값이 작으면 문제 있따.기무가설은 등분산성 가정에 문제가 있을 수 있다.
# 0.03 <0.05보다 작으니깐 조심해야 한다.

잔차분석을 통해 회귀분석의 가정에 문제가 있는 것을 확인했다면 , 그다음에는 어떻게 해야 하는가 ?-->회귀분석 다시 해야 한다.
데이터 변환을 해야 한다.->171페이제
2차곡선이 그려지게 점들이 있다. 2차의 곡선을 찾아줘야 한다.
y는 dist의 제곱하고 root를 씌워져서 값이 줄어든다. root로 해서 새로운 열을 만들어준다.

#잔차분석 -정규성 검정 
#데이터로 보여주는  정규성
plot(cars,2)
shapiro.test(fit.cars$res)#169
#0.02152 
#유의확률(p-value)이 작으면 정규성 가정에 문제가 있을 수 있다 
#(정규성 가정을 의심해봐야 핚다). 
#잔차를 확인 해야 한다. 잔차는 자주 사용해야한다.
#작은 것이 아니락 크야 한다.

data2 <- cars
#덮어씌우는 것
#data2$dist <- sqrt(data2$dist)
#colnames(data2)[2] <- "sqrt.dist"
#새로운 열을 만드는 것
data2$sqrt.dist <- sqrt(data2$dist)
head(data2, 5)
fit.cars2 <- lm(sqrt.dist ~speed, data = data2)
fit.cars2
bptest(fit.cars2)
#0.9157
ncvTest(fit.cars2)
#0.91258
#등분산성 만족 
plot(fit.cars2)#처음 보다 덜 위험하다.
shapiro.test(fit.cars2$residuals)
#p-value = 0.3143
summary(fit.cars2)


ggplot(data = data2, aes(x= speed, y = sqrt.dist))+
  geom_point()+
  geom_abline(data = date2, intercept = 1.27705, slope = 0.32241, col= "red")

다중선형회귀분석
변수가 2개 이상일 경우 
종속 변수 
성적 
영향을 주는 것 을 모른다. 

변수를 조작한다.
변수가 여러개있다.
최소제곱법-
각각의 개수들을 찾아보는 것 
예: 부동산 예측

#다중
library(readxl)
BostomHousing <- read_excel("BostonHousing.xls")
str(BostomHousing)
data <- tbl_df(BostomHousing)#데이터의 형태를 바꾼다. 이렇게 바꾸면 큰 데이터 프레임을 보기 쉽도록 해 준다.
#tbl_df -> as_tibble를 불러온다.
str(data)

View(data)
glimpse(data)

data(package ="MASS")
names(data)

library(psych)
pairs.panels(data[names(data)])#데이터 있는 것들을 이름을 가져와서 
#상관간계 보여 주는 것 
#0.70 과 -0.74
#rm lstat와 관계있다.
pairs.panels(data)
#plot에서 상관관계 
data <- data[ , -15]#오류난다.
data

names(data)
names(data) <- tolower(names(data))#소문자로 바꿔준다.
data_lm_full <- lm(medv ~ ., data = data)
#medv가격을 나타내는 주기 
data_lm_full
#이것은 작을 수록 좋다.

summary(data_lm_full)
#signif 별표시 되여있다. 별 3개 위주로 값이 작으면 좋다 . 별이 없으면 무의미한 것이여서
#R-squard는  r제곱값인데ㅔ 크면 좋다. 0.74이면 74%정도 말하면 된다.
#Adjusted R-squard 변수가 많으면 모형을 잘 설명해줄것이라고 생각한 것처럼 변수가 늘어나면 아무 의미가 없어도 변수가 널아나서 변수가 조금 변한다. 변수가 저절로 높으지지 않도록 마이나서ㅓ(penalty)를 줘서 값이 작아진다.
#Adjusted R-squard 이것 확인하면 된다.
#전체 적인  pvalue는 2e-16이다 믿을만 하다.

 

-----------------------------------------------------
의사결정나무 정리
redpineK 머신러닝 시리즈
의사결정 순도를 높이는 방향으로 하는 것이다.
넘 잘도면 overfitting발생 가능하다. 
entropy낮추는 방향으로 -<순도를 높이는 방향으로 한다.
의사결정 시리즈로 
분류하고 예측한다.
random forest 
boosting

신경망에서 overfitting의 해결방법은  빼는 것이다.droupout
적당한 선에서 멈춘다.

complexity parameter
hypper parameter

의사결정나무의 장점
회이트 박스모형이며 ,결과를 해석하고 이해하기 쉽다.
자료를 가공할 필요가 거의 없다.
수치 자료와 범주 자료 모두에 적용할 수 있다.


#의사결정 나무 
#ADSP
library(rpart)

apple_df <- read.csv(file= "apple.csv")
apple_df
summary(apple_df)

str(apple_df)

#품종별 무게 
boxplot(weight ~ model , data = apple_df, ylab="무게" )

#품종별 당도
boxplot(sugar ~ model, data = apple_df, ylab ='당도')

#품종별 산도
boxplot(acid ~ model, data = apple_df, ylab ='산도')
ggplot(apple_df, aes(x = model, y = acid)) +geom_boxplot()

#최초 실행시 패키
library("ggplot2")

k <- ggplot(apple_df, aes(factor(color), fill= factor(model)))
k + geom_bar()
#geom_bar  geom_col차이점 
k1 <- ggplot(apple_df, aes(factor(color), fill= factor(model)))
k1 +  geom_col()#geom_col requires the following missing aesthetics: y

#옆으로 하는 것 position="dodge"

#iris데이터 구조
# 꽃 종류 
#꽃받침 S
#꽃잎 P
str(iris)
colnames(iris)
nrow(iris)
table(iris$Species)

library(caret)

iris_row_idx <- createDataPartition(iris$Species, p = 0.8 , list = F)#list형이 아닌 vector형으로 
#iris$Species 를 1-100 중에  80개 random하게 꺼내기 
str(iris_row_idx)
View(iris_row_idx)

iris_train_data <- iris[iris_row_idx,]
str(iris_train_data)
table(iris_train_data$Species)
iris_test_Data <- iris[-iris_row_idx,]
str(iris_test_Data)
table(iris_test_Data$Species)#3개씩 층 30건

#traing 와 테스트 각각의 종류별로도 나누었다.

summary(iris_train_data)
summary(iris_test_Data)

library(rpart)

iris_rpart_result <- rpart(Species ~ . , data = iris_train_data, control = rpart.control(minsplit =2 ))
#Species ~ . species 와 나머지 
#data = iris_train_Data 120개 traing까지 
#rpart.control(minsplit =2 )나머지 2개가 있을 때 까지

#분류분석 결과값 출력 
iris_rpart_result
#질문이 

library(rpart.plot)
rpart.plot(iris_rpart_result)

#cp값 조회
iris_rpart_result$cptable
#단계로 나눈다.

#가지치기 
iris_prune_tree <- prune(iris_rpart_result, cp= 0.0125)
#iris_rpart_result$cptable cp값으로 수정 
#cp 잴 아래것 빼고 빼는 것이 좋다.
rpart.plot(iris_prune_tree)
#마지막을 치운다. 적당하게 일반화 해줘야 한다.

#rm(list = ls())

str(iris_test_Data)
#테스트 데이터 확인 - 훈련 데이터와 컬럼명이 같아야 함 (단 종속 변수 걸럼은 없어)
predict(iris_rpart_result ,iris_test_Data, type = "class")

actual <- iris_test_Data$Species
expect <- predict(iris_rpart_result ,iris_test_Data, type = "class")
expect_prune <- predict(iris_prune_tree ,iris_test_Data, type = "class")#가지치기 하는 것도 예측해야 한다.

iris_predict_df <- data.frame(actual, expect, expect_prune)
iris_predict_df#결과값 확인 

#혼동행렬 만들기 
table(iris_predict_df)

library(caret)
confusionMatrix(expect,actual, mode ="everything" )

#------------------------

library(ggplot2movies)
movies <- ggplot2movies::movies
str(movies)

apple_train_idx <- createDataPartition(apple_df$model , p = 0.8, list = F)
nrow(apple_train_idx)
nrow(apple_df)

str(apple_df)

apple_train_df <- apple_df[apple_train_idx,]
apple_test_df <- apple_df[-apple_train_idx,]

str(apple_train_df)
str(apple_test_df)
apple_train_df
apple_test_df
table(apple_train_df$model)
table(apple_test_df$model)

apple_rpart_result <- rpart(model ~ . , data = apple_train_df, control = rpart.control(minsplit = 2))
apple_rpart_result

rpart.plot(apple_rpart_result)
str(apple_rpart_result)

apple_rpart_result$cptable
apple_pune_tree <- prune(apple_rpart_result , cp = 0.0000)
rpart.plot(apple_pune_tree)
str(apple_test_df)

app_actual <- apple_test_df$model
app_expect <- predict(apple_rpart_result, apple_test_df, type ="class")

app_predict_df <- data.frame(app_actual, app_expect)

table(app_predict_df)

#randomForest
install.packages("randomForest")
require(randomForest)
ind <- sample(2, nrow(iris), replace = T, prob = c(0.7 , 0.3))
trainData <- iris[ind == 1,]
testData <- iris[ind == 2,]

rf <- randomForest(as.factor(Species)~ . , data = trainData, ntree = 100, proximity = T, importance = T)
print(rf)

predict(rf)
table(predict(rf), trainData$Species)
irisPred <- predict(rf, newdata = testData)
irisPred
table(irisPred, testData$Species)

랜덤 포레스트(영어: random forest)는 분류, 회귀 분석 등에 사용되는 앙상블 학습 방법의 일종으로, 훈련 과정에서 
구성한 다수의 결정 트리로부터 부류(분류) 또는 평균 예측치(회귀 분석)를 출력함으로써 동작한다.
Bagging은 샘플을 여러 번 뽑아 각 모델을 학습시켜 결과를 집계(Aggregating) 하는 방법입니다. 
랜덤 프레스트는  배깅이 발전한 것이다.
부스팅
배깅이 일반적인 모형을 만드는데 집중되어 있다면 ,부스팅은 맞추기 어려운 문제를 맞추는 것이 목적이다.

#boosting
#파산 분류
credit <- read.csv("credit.csv")
View(credit)
install.packages("C50")
library(C50)
m_c50_bst <- C5.0(default~. , data = credit, trials = 100)
install.packages("adabag")
library(adabag)

set.seed(300)
m_adaboost <- boosting(default ~. , data = credit)#파산 하는지 의사결정 tree를 boosting해서 만든다.
p_adaboost <- predict(m_adaboost, credit)#모델가지고 예측 
head(p_adaboost$class)
p_adaboost$confusion

#set.seed(300)
#adaboost_cv <- boosting.cv(default ~ . , data = credit)
#adaboost_cv$confusion

#bagging
library(ipred)
set.seed(300)
mybag <- bagging(default ~. , data= credit, nbagg = 25) #radong data 25개 마추어서 모여봐 
predict_pred <- predict(mybag, credit)
table(predict_pred, credit$default)
반응형

'Study > R' 카테고리의 다른 글

R-10  (0) 2020.09.05
R-8  (0) 2020.09.05
R-7  (0) 2020.09.05
R-6  (0) 2020.09.05
R-5  (0) 2020.09.05

+ Recent posts