data analysis & visualization

전이학습이란?

 

전이 학습의 아이디어는 이미 구축된 잘 만들어진 모형을 활용하자는 아이디어에서 비롯됬다.

 

즉, 이미 훈련된 모델(Pre trained Model)의 가중치를 가져와 해결하고자 하는 과제에 맞게

 

재보정해서 사용하는 것을 의미하며, 일부 레이어를 고정하고 나머지 레이어에 대해 추가 교육을

 

수행하여 목적에 맞게 조정하는 방법이다.

 

전이학습의 장점은 완성된 모델을 사용하므로 하드웨어가 부족하더라도 사용이 가능하다는 장점이 있다.

 

Learning from scratch

일반적으로 모델을 학습하는 방식으로 처음부터 모델의 가중치를 학습하는 방식을 의미한다.

 

Pre trained model

내가 풀고자하는 문제와 비슷하며 사이즈가 큰 데이터로 이미 학습되어 있는 모델을 의미한다.

 

보틀넥 피쳐(Bottleneck feature)

가장 마지막 CNN 블록을 의미하며, Fully connected layer 직전의 CNN블록의 결과를 의미한다.

 

Fine Tuning

전이학습을 Fine Tuning용어와 같이 혼용되곤 한데 Fine Tuning은 일부 레이어의 가중치 고정을 해제하고

 

학습율을 줄여 파라미터를 미세 조정하는 방법을 의미한다.

 

피처를 추출해내는 레이어의 파라미터를 업데이트하지 않는 경우 파인튜닝이라 하지 않는다.

 

 

'딥러닝' 카테고리의 다른 글

기울기 소실 문제와 ResNet  (0) 2021.05.25
순환신경망(1/3)  (0) 2021.04.11
tensorboard 외부접속  (0) 2020.11.27
GPU 메모리 조절 방법  (0) 2019.11.19
CNN channel 1개와 3개의 성능비교(cats and dogs)  (0) 2019.06.18

기울기 소실 문제(Gradient Vanishing Problem)

 

학습과정에서 출력값과 멀어질수록 학습이 잘 안되는 현상

 

레이어가 깊어질수록 미분 많아지므로 오차역전파(Backpropagation)를 진행해도

 

앞의 레이어일수록 미분값이 작아져 그만큼 출력값(Output)에 영향을 미치는 가중치가 작아지는 현상

 

기울기 소실문제의 해결 방안으로 그라디언트 클래핑, 다양한 활성화함수(swish, mish) 등이 제시

 

ResNet

 

기존 딥러닝 알고리즘은 y=H(x)를 찾는 과정이였다면, 

 

ResNet은 H(x)-y를 최소화 하는 방향으로 진행하며, 

 

기울기 소실 문제를 해결하기 위해서 F(x)+x=H(x)로 하고, F(x)=0이 되게 학습을 진행

 

F(x)+x의 미분값은 F'(x)+1이므로 모든 층에서 적어도 1이상의 gradient를 가지게 됨

 

'딥러닝' 카테고리의 다른 글

전이학습(Transfer Learning)  (0) 2021.05.25
순환신경망(1/3)  (0) 2021.04.11
tensorboard 외부접속  (0) 2020.11.27
GPU 메모리 조절 방법  (0) 2019.11.19
CNN channel 1개와 3개의 성능비교(cats and dogs)  (0) 2019.06.18

순환신경망(1/3)

딥러닝2021. 4. 11. 19:04

 

 

 

 

 

 

 

 

'딥러닝' 카테고리의 다른 글

전이학습(Transfer Learning)  (0) 2021.05.25
기울기 소실 문제와 ResNet  (0) 2021.05.25
tensorboard 외부접속  (0) 2020.11.27
GPU 메모리 조절 방법  (0) 2019.11.19
CNN channel 1개와 3개의 성능비교(cats and dogs)  (0) 2019.06.18

tensorboard 외부접속

딥러닝2020. 11. 27. 00:07

나는 tensorboard는 유용해 보였지만 사용법을 몰라서 못쓰던 유저였다. 그래서 외부접속 같은 옵션들을 간략하게 설명하려고 한다.

 

먼저 내 콘다는 /root/anaconda3/envs/jupyter/에 있다.

해당 콘다의 python의 패키지는 어디에 존재하는지는 운영체제마다 다르겠지만 linux(ubuntu20.04)는 

가상환경의 경로안에 lib/<python버전>/site-packages에 패키지들이 존재한다. 

에러에 대한 원래 코드를 확인하고 싶다면 아래 경로를 확인해보았으면 한다. 

 

 

 

 

 

 

위 코드는 keras의 tensor board의 예제이다

 

tutorials.pytorch.kr/intermediate/tensorboard_tutorial.html

 

TensorBoard로 모델, 데이터, 학습 시각화하기 — PyTorch Tutorials 1.6.0 documentation

TensorBoard로 모델, 데이터, 학습 시각화하기 파이토치(PyTorch)로 딥러닝하기: 60분만에 끝장내기 에서는 데이터를 불러오고, nn.Module 의 서브클래스(subclass)로 정의한 모델에 데이터를 공급(feed)하고,

tutorials.pytorch.kr

내 코드의 경로는 '/home/ducj/jupyter/pytorch_study'에 해당하는데 

 

from torch.utils.tensorboard import SummaryWriter

writer = SummaryWriter('runs/fashion_mnist_experiment_1')

 

명령어를 사용하게 되면

/home/ducj/jupyter/pytorch_study/runs/fashion_mnist_experiment_1에 생성이 된다.

 

그런 후 tensorboard --logder <run까지만> 입력을 하게되면 실행되고 port의 default 값은 6006이다.

 

외부접속을 허용하게 하려면 방화벽을 열어야 되는데 sudo ufw allow 6006을 하게되면 6006 포트가 열린다.

 

또한 인터넷에서 포트포워딩 같은 것을 해주어야 접속이 가능하다. host 0.0.0.0은 모든 host를 허용한다고 하는 것인데 우리가 매번 치던 localhost는 127.0.0.1에 해당된다.

 

bind_all이라는 기능도 있던데 따로 host를 생성해주는 것 같았다. 

 

 

마지막으로 ssh를 사용하고 있을 때이다.

 

ssh -L <내 로컬컴퓨터에서 접속할 port>:<매칭할호스트:포트> <계정명>@<ssh 호스트>

 

자 ssh를 통해 외부접속이 열렸다. 한번 확인해보자. 

 

위와 같이 localhost를 열었다.

 

 

잘들어가진다.

'딥러닝' 카테고리의 다른 글

전이학습(Transfer Learning)  (0) 2021.05.25
기울기 소실 문제와 ResNet  (0) 2021.05.25
순환신경망(1/3)  (0) 2021.04.11
GPU 메모리 조절 방법  (0) 2019.11.19
CNN channel 1개와 3개의 성능비교(cats and dogs)  (0) 2019.06.18

#data generate
library(tensorflow)
library(keras)


#holdout cross validation
set.seed(1)
data=data.frame(norm=sort(rnorm(100)),uni=sort(runif(100)))
set.seed(1)
idx=sort(sample(1:nrow(data),0.7*nrow(data)))
trainData=data[idx,]
testData=data[-idx,]
target='uni'

#standardization
source('/home/ducj/standard.R')
#normalization
train=trainData

min=apply(train[,sapply(train,is.numeric)],2,min)
max=apply(train[,sapply(train,is.numeric)],2,max)
xy=names(which(sapply(train,is.numeric)))
train_data=t(apply(train[,xy],1,function(x){(x-min)/(max-min)}))
train_data=as.matrix(train_data[,colnames(train_data)!=target])
train_label=as.matrix(train[,target,drop=F])

test=testData

test_data=t(apply(test[,xy],1,function(x){(x-min)/(max-min)}))
test_data=as.matrix(test_data[,colnames(test_data)!=target])
test_label=as.matrix(test[,target,drop=F])

train_data=array(train_data,dim=c(nrow(train_data),ncol(train_data),1))
train_label=array(train_label,dim=c(nrow(train_data),1))

test_data=array(test_data,dim=c(nrow(test_data),ncol(test_data),1))
test_label=array(test_label,dim=c(nrow(test_data),1))

#custom loss function
# quantile <- 0.5
# loss <- function(q, y, f) {
#   e <- y - f
#   k_mean(k_maximum(q * e, (q - 1) * e), axis = 2)
# }
loss <- function(y, f) {
  e <- y - f
  k_mean(e^2, axis = 2)
}


sess <- k_get_session()
ys <- k_constant(c(1,2,3,4), shape = c(2,2))
yhats <- k_constant(c(1,3,3,4), shape = c(2,2))
sess$run(loss( ys, yhats))

#dnn
dim(train_data)=c(nrow(train_data),ncol(train_data))
dim(test_data)=c(nrow(test_data),ncol(test_data))
model =keras_model_sequential()%>%
  layer_dense(units = 3, input_shape = c(ncol(train_data)),activation = 'sigmoid') %>%
  # layer_activation_leaky_relu() %>%
  layer_dense(units = 1)

model %>% compile(
  optimizer = "adam",
  loss = function(y_true, y_pred)
    loss(y_true, y_pred),
  metrics = "mae"
)

# history <-model %>% fit(train_data,train_label,epochs = 120,batch_size = 10)
history <-model %>% fit(train_data,train_label,epochs = 500,batch_size = 5,validation_data=list(test_data,test_label))
history <-model %>% fit(train_data,train_label,epochs = 1,batch_size = 70,validation_data=list(test_data,test_label))

pred=predict(model,test_data)
spTimer::spT.validation(z=test$uni,zhat=(pred-min[2])/(max[2]-min[2]))

#lstm
dim(train_data)=c(nrow(train_data),ncol(train_data),1)
dim(test_data)=c(nrow(test_data),ncol(test_data),1)

model=keras_model_sequential()%>%
  layer_cudnn_lstm(units=3,input_shape=c(ncol(train_data),1))%>%
  layer_dense(units=1)
model %>% compile(
  optimizer = "adam",
  loss = function(y_true, y_pred)
    loss(y_true, y_pred),
  metrics = "mae"
)
# model%>%compile(optimizer=optimizer_rmsprop(),loss='mae')
# model%>%compile(optimizer=optimizer_adam(lr=0.003),loss='mae')
history=model %>% fit(train_data,train_label, epochs=500, batch_size=5,validation_data=list(test_data,test_label))

pred2=predict(model,test_data)
spTimer::spT.validation(z=test$uni,zhat=(pred2-min[2])/(max[2]-min[2]))
plot(test$uni,type='l',ylab='unif')
lines((pred-min[2])/(max[2]-min[2]),type='l',col='2')
lines((pred2-min[2])/(max[2]-min[2]),type='l',col='3')

먼저 python에서 

tf.GPUOptions(per_process_gpu_memory_fraction=0.333)

sess = tf.Session(config=tf.ConfigProto(gpu_options=gpu_options))

을 활용하면 메모리를 제한 할 수 있다.

 

config = tf.ConfigProto()

config.gpu_options.allow_growth = True 

session = tf.Session(config=config, ...)

을 활용하면 탄력적으로 메모리를 활용한다.

 

이제 R에서

gpu_options <- tf$GPUOptions(per_process_gpu_memory_fraction = 0.333)

config <- tf$ConfigProto(gpu_options = gpu_options)

 

config=tf$ConfigProto()
tf$Session(config=config)
gpu_options <- tf$GPUOptions(allow_growth = TRUE)
config <- tf$ConfigProto(gpu_options = gpu_options)
k_set_session(tf$Session(config = config))

 

을 활용하면 탄력적으로 메모리를 활용한다.

'딥러닝' 카테고리의 다른 글

전이학습(Transfer Learning)  (0) 2021.05.25
기울기 소실 문제와 ResNet  (0) 2021.05.25
순환신경망(1/3)  (0) 2021.04.11
tensorboard 외부접속  (0) 2020.11.27
CNN channel 1개와 3개의 성능비교(cats and dogs)  (0) 2019.06.18