• R-5 2020.09.05
반응형

이상치가 있으면 인지 하고 
지우는지 범위를 변경하는지 알수 있다.
boxplot
상자기준으로 
극단치
극단치 경계
윗수염: 하위 75 ~ 100%
3사분위(Q3) 하위 75%
2사분위(Q2) 하위 50% 중간값
1사분위(Q1) 하위 25%
아랫수염
극단치 경계

 

몇 %이상 들어가야만 사회가 안정적이다.
아니면 값이 이상치이다.
실제있는 데이터만 정확해서 수염의 길이를 표현하는 것있고 있는 것 값중에서 가장 작은 값을 표시한다.
있는데이터에서만 그려주니깐 

 

library(ggplot2)
boxplot(mpg$hwy)
mpg$hwy <- ifelse(mpg$hwy < 12 | mpg$hwy > 37, NA, mpg$hwy)
table(is.na(mpg$hwy))

library(dplyr)
outlier <- data.frame(sex= c(1,2,1,3,2,1) , score= c(5,4,3,4,2,26))
outlier

table(outlier$sex)
table(outlier$score)

outlier$sex <- ifelse(outlier$sex == 3, NA, outlier$sex)#3은 이상치보다 오류이다.
outlier

outlier$score <- ifelse(outlier$score>5 , NA, outlier$score)#16
outlier

outlier <- data.frame(sex= c(1,2,1,3,2,1) , score= c(5,4,3,4,2,26))
boxplot(outlier$score)

outlier %>% filter(!is.na(sex) & !is.na(score)) %>% 
  group_by(sex) %>% 
  summarise(mean_score = mean(score))

mpg

ggplot(mpg,aes(drv, hwy))+geom_boxplot()
ggplot(mpg,aes(y =hwy))+geom_boxplot()
ggplot(mpg,aes(,hwy))+geom_boxplot()
mpg$drv
boxplot(mpg$drv)#숫자가 아니여서 못 그린다.
ggplot(data = mpg, aes(drv))+ geom_bar()

ggplot(mpg,aes(x = manufacturer, y = displ,colour = manufacturer,fill= "fill")) + geom_boxplot()
ggplot(mpg,aes(x = displ, y = manufacturer,colour = displ,fill= "fill")) + geom_boxplot()
#y는 숫자이여야만 높으를 줄수 있다.

na.rm =  T으로 권장드린다.

tibble -> data.frame 기본적인 것 

 

3일차 분석사례실습 / 텍스트마이닝 
한국복지패널데이터 분석 
성별에 따른 월급 차이 
성별 직업 빈도 
종교 유무에 따른 이혼율 
한국복지패널  데이터 분석 
성별에 따른 월급 차이   
-“성별에 따라 월급이  얼마나  다른가?” 

 

install.packages("foreign")
library(foreign)#기본으로 깔려져있다.
library(dplyr)  
library(ggplot2) 
raw_welfare <- read.spss(file="Koweps_hpc10_2015_beta1.sav")
welfare <- as.data.frame(raw_welfare)#data를 편리하게 사용하려고 as.data.fram으로 나누었다.
str(welfare)#변수의 형태등 
glimpse(welfare)
head(welfare)
tail(welfare)
summary(welfare)

lit는 데이터 형에 아무른 변화가 없다.
파이썬  list는 vector에 가깝다.

 

raw_welfare <- read.spss(file="Koweps_hpc10_2015_beta1.sav")
welfare <- as.data.frame(raw_welfare)#data를 편리하게 사용하려고 as.data.fram으로 나누었다.
str(welfare)#변수의 형태등 
glimpse(welfare)
head(welfare)
tail(welfare)
summary(welfare)
#아래에 2가지 방법으로 가능하다.
#1.
welfare <- welfare %>% 
  rename( gender = h10_g3, birth = h10_g4,marriage = h10_g10, religion = h10_g11,
          income = p1002_8aq1, job = h10_eco9,
          region= h10_reg7) %>% 
  select(gender, birth, marriage, religion, income, job ,region)
welfare

#2.
welfare <- welfare %>% 
  select(gender = h10_g3, birth = h10_g4,marriage = h10_g10, religion = h10_g11,
         income = p1002_8aq1, job = h10_eco9,
         region= h10_reg7)
welfare
str(welfare)#numeric으로 변환한다.
summary(welfare)#gender이 이상하게 나온다.na값이 보여진다. 몇개있는지도 보여준다.
#숫자로
plot(welfare)#밑에와 위에 같은데 아래쪽 본다.
pairs(job ~ income+gender+region, data = welfare)
#줄로 된것은 1아니면 2밖에 없다. numeric이 아니라 범주형이다
#막대리 처럼 해지면 
boxplot(welfare)
#income을 따로 잡을수 있다.
sum(is.na(welfare))#21165
sum(welfare, na.rm = T)#38498929
colSums(is.na(welfare))#컬럼별로 sum을 한다.
summary(welfare$income)
mean(welfare$income)
mean(welfare$income,na.rm = T)#241.619
mean(is.na(welfare$income))#0.7219155

range(welfare$income)
range(welfare$income,na.rm = T)
welfare$income <- ifelse(welfare$income == 0 , NA, welfare$income)
#분석할때 소덕의 범위를 
#0이 아닌데 0으로 대답하는 분이 많다고 생각한다.
summary(welfare$income)
plot(welfare$income)#index가 row개수 

install.packages("psych")
library(psych)
describe(welfare)#descirbe 다른 관점에서 보여준다.
#다른 관점에서의 통계적 정보를 보여준다.

str(welfare)#16664
ggplot(data = welfare, aes(x= income))+geom_density()#밀도
#평균등으로 파악하기 힘든 집단이다.
#Removed 12044 rows containing non-finite values (stat_density). 
ggplot(data = welfare, aes(x = income))+geom_freqpoly()
#Removed 12044 rows containing non-finite values (stat_bin)

summary(welfare$gender)
welfare$gender <- ifelse(welfare$gender == 1, 'M','F')
summary(welfare$gender)#전에는 1,2 등으로 나왔는데 character로 바꿔졌다.
table(welfare$gender)#빈도수 세주는 것
ggplot(data = welfare, aes(x = gender))+geom_bar()
ggplot(data = welfare, aes(x = gender, colour = gender))+geom_bar()#테두리
ggplot(data = welfare, aes(x = gender,fill =gender))+geom_bar()#테두리
ggplot(data = welfare, aes(x = gender))+geom_bar(aes(fill =gender))#테두리
barplot(table(welfare$gender), xlab="gender" , ylab = "count",col=rainbow(3))  #barplot count를 한것으로 해야 한다. 그래서 table한 상태로 들어가야 한다.

welfare %>% select(gender, income) %>% group_by(gender) %>% summarise(평균= mean(income, na.rm = T))
welfare %>% filter( !is.na(income)) %>% group_by(gender) %>% summarise(평균= mean(income))
data_gender <- welfare %>% group_by(gender) %>% summarise(평균=mean(income,na.rm = T))
data_gender 
welfare %>% select(gender, income) %>% group_by(gender) %>% summarise(평균= mean(income, na.rm = T)) %>% 
  ggplot(aes(x= gender, y =평균,fill=gender))+geom_bar(stat = 'identity')
ggplot(data=data_gender, aes(x= gender, y =평균,fill = gender))+geom_bar(stat = 'identity')
#stat = 'identity'  이것 무조건 해줘야 한다. 아니면 오류난다.stat_count() must not be used with a y aesthetic

welfare %>% select(gender, income) %>% ggplot(aes(x= income, color =gender))+geom_density()

나이에 따른 소득 차이   
-“몇 살에 수입이 가장 많은가?” 

 

class(welfare$birth)
summary(welfare$birth)
qplot(welfare$birth)
#qplot을 쓰지 말라
boxplot(welfare$birth)#이상치를 확인하려면 boxplot을 보면 된다.
sum(is.na(welfare$birth))#결측치 확인 한 것
welfare$age <- 2015 - welfare$birth +1
#열이 없으면 새로 만든다.
summary(welfare$age)
plot(welfare$birth)
plot(table(welfare$birth))
barplot(welfare$birth)
welfare
#있던 데이터에서 정리한다. 나이별로 열을 하는 것을 만들었다.
age_income <- welfare %>% filter(!is.na(income)) %>% group_by(age) %>% summarise(mean_income= mean(income))
head(age_income)
ggplot(data=age_income, aes(x= age, y =mean_income))+geom_line()
ggplot(data = age_income ,aes(x= age,y=mean_income))+geom_point()
ggplot(data = age_income ,aes(x= age,y=mean_income))+geom_point(size=2, color= "blue")
ggplot(data = age_income ,aes(x= age,y=mean_income))+geom_point(size=2, color= "blue")+geom_line()
#layer익때문에 겹져진다.

연령대(세대)별  평균소득
#순서가 상관이 있다. 먼저 그리는 것에 겹쳐진다.

#세대별
install.packages("KoNLP")
library(KoNLP)#Checking user defined dictionary!

useSejongDic()

library(wordcloud2)
text1 = readLines("ahn.txt")
text1

#3: None
library(ggplot2)
library(dplyr)
welfare <- welfare %>% mutate(age_gen = ifelse(age <30,"young",ifelse(age<= 40,"g3",ifelse(age<=50 ,"g4",ifelse(age<= 60,"g5","old")))))
head(welfare,10)

table(welfare$age_gen)
qplot(welfare$age_gen)

age_gen_income <- welfare %>% group_by(age_gen) %>% summarise(mean_income = mean(income,na.rm = T))
age_gen_income

ggplot(data = age_gen_income,aes(x = age_gen, y = mean_income))+geom_col()
ggplot(data = age_gen_income, aes(x= age_gen, y = mean_income))+geom_bar(stat= "identity")
ggplot(data = age_gen_income, aes(x= age_gen, y = mean_income,fill=age_gen))+geom_bar(stat= "identity")
ggplot(data = age_gen_income, aes(x= age_gen, y = mean_income))+geom_bar(stat= "identity",aes(fill=age_gen))
ggplot(data = age_gen_income,aes(x= age_gen, y= mean_income))+geom_col(aes(fill=age_gen))+scale_x_discrete(limits= c("young","g3","g4","g5","old"))#순서대로  scale_x_discrete

나이와 성별에 따른 소득 차이   
-“소득은 나이와 성별에 따라 어떻게 다른가?” 


gender_income <- welfare %>% group_by(age_gen,gender) %>% 
  summarise(mean_income = mean(income,na.rm = T))
gender_income

ggplot(data = gender_income , aes(x = age_gen , y = mean_income, fill= gender))+geom_col()+scale_x_discrete(limits= c("young","g3","g4","g5","old"))
ggplot(data = gender_income , aes(x = age_gen , y = mean_income, fill= gender))+geom_col(position= "dodge")+scale_x_discrete(limits= c("young","g3","g4","g5","old"))#겹치지 않고 옆으로 진행 

신경망
require 좀더 좋다. 없으면 알려준다.

library
data(iris)
str(iris)#불꽃데이터 ->변수
#'data.frame':	150 obs. of  5 variables:
#$ Sepal.Length: num  5.1 4.9 4.7 4.6 5 5.4 4.6 5 4.4 4.9 ... 꽃받침
#$ Sepal.Width : num  3.5 3 3.2 3.1 3.6 3.9 3.4 3.4 2.9 3.1 ...
#$ Petal.Length: num  1.4 1.4 1.3 1.5 1.4 1.7 1.4 1.5 1.4 1.5 ... 꽃잎
#$ Petal.Width : num  0.2 0.2 0.2 0.2 0.2 0.4 0.3 0.2 0.2 0.1 ...
#$ Species     : Factor w/ 3 levels "setosa","versicolor",..: 1 1 1 1 1 1 1 1 1 1 ... 불꽃의 종류
temp <- c(sample(1:50, 30),sample(51:100,30),sample(101:150,30))
temp
iris.training <- iris[temp,]
iris.testing <- iris[-temp,]
library(nnet)
neuralNetResult <- nnet(Species~., data= iris.training, size = 3, decay =0 )#종을 맞추어봐라 나머지 너비,길이 맞춰보라 
neuralNetResult
summary(neuralNetResult)
#1번째 방법
library(devtools)
source_url('https://gist.githubusercontent.com/fawda123/7471137/raw/466c1474d0a505ff044412703516c34f1a4684a5/nnet_plot_update.r')
install.packages("reshape")
library(reshape)

#2번째 방법
library(clusterGeneration)
library(scales)
library(reshape)

plot.nnet(neuralNetResult)

pred <- predict(neuralNetResult, iris.testing, type = "class")
pred
real <- iris.testing$Species
table(real, pred)
summary(neuralNetResult)

iris 데이터를 잘 알아야 한다.

 

ggplot2::diamonds #diamonds는 ggplot2에 있는 것
datasets::iris#default 설치안해도 사용할 수 있는 것 

install.packages("ggplot2movies")
require(ggplot2movies)
movies
dim(movies)

첫번째 신경망을 로젠블랏의 퍼셉트론
퍼셉트론으 x이의 문제 가능하다.
처음에 들어간 데이터가 얼마인가 
비선형함수이다.
#손글자 

train <- read.csv("mnist_train.csv")
train[10,-1]#10번째 줄의 첫번째것 없에기
train[10,]#첫번때에 label이 있다.
train[10,1]#첫번때에 label이 있다.[1] 3
#3의 특징  예는 3이다.
train

dim(train)

#28* 28 PIXEL로 해서 783개로 해서 w값들이 바꾼다.
m = matrix(unlist(train[10, -1]), nrow = 28, byrow =T) #숫자가 RGB값이다.28라인 갈때마다 끊어진다.
#첫번째는 3이고 나머지는 rgb이다.
m

image(m, col = grey.colors(255))#image를 보고 싶을때 
write.csv(m,"mnist3.csv")

rotate <- function(x) t(apply(x, 2, rev))
par(mfrow = c(2,3))
lapply(1:6, function(x) image(
                      rotate(matrix(unlist(train[x,-1]),nrow = 28, byrow = TRUE)),
                      col= grey.colors(255),
                      xlab=train[x,1]
                      ))


par(mfrow = c(1,1))

#load caret library
install.packages("caret")
library (caret)

#createDataPartition( )은 데이터를 훈련 데이터와 테스트 데이터로 분할한다.
inTrain <- createDataPartition(train$label, p = 0.8, list=F)
#caret::createDataPartition(
#  y,          # 분류(또는 레이블)
#  times=1,    # 생성할 분할의 수
#  p=0.5,      # 훈련 데이터에서 사용할 데이터의 비율
#  list=TRUE,  # 결과를 리스트로 반환할지 여부. FALSE면 행렬을 반환한다.
#)
#0.8 곱해서 한다.
training<-train[inTrain,]#데이터를 저장한다.
testing<-train[-inTrain,]#데이터를 저장한다.
training
testing

write.csv(training, file ="train-data.csv", row.names = F)
write.csv(training, file ="test-data.csv", row.names = F)

install.packages("h2o")
library(h2o)
미부함수

local.h2o <- h2o.init(ip = "localhost", port = 54321, startH2O = TRUE, nthreads=-1)
training <- read.csv("train_data.csv")
testing <- read.csv("test_data.csv")
training
testing

training[,1] <- as.factor(training[,1])#범주형이다.

trData <- as.h2o(training)
trData[,1] <- as.factor(trData[,1])
tsData <- as.h2o(testing)
tsData[,1] <- as.factor(tsData[,1])

#unilx 시간 측정
start <- proc.time()
model.dl <- h2o.deeplearning(x = 2:785,
                             y = 1,
                             trData,
                             activation = "Tanh",#sigmoid등 으로 바꿀수 있다.
                             hidden=rep(160,5),
                             epochs = 20)
end <- proc.time()

diff=end-start
print(diff)

str(pred.dl.df)
pred.dl.df$predict 
pred.dl.df[1,1] 
table(test_labels[1,1],pred.dl.df[1,1]))
반응형

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

R-7  (0) 2020.09.05
R-6  (0) 2020.09.05
R-4  (0) 2020.09.05
R-3  (0) 2020.09.05
R -2  (0) 2020.09.05

+ Recent posts