• Tistory
    • 태그
    • 위치로그
    • 방명록
    • 관리자
    • 글쓰기
Carousel 01
Carousel 02
Previous Next

'전공관련'에 해당되는 글 73건

  • 2022.04.01 [MXNet] 데이터 리스트를 만들고 rec 파일로 만들어 보자
  • 2021.07.13 [Pytorch] pycharm 환경에서 torch.distributed.launch를 실행하자 (1)
  • 2021.04.26 [Tensorflow] h5py 관련 오류를 해결하자
  • 2021.03.09 [ONNX] cuda 버전에 따른 python onnxruntime 버전을 맞추자.
  • 2021.02.25 [용어] Ablation Study
  • 2021.02.24 [Caffe] caffe 환경 설정없이 caffemodel 값을 확인하자
  • 2021.02.17 [Pytorch] model load시 key가 있는 레이어만 불러오자
  • 2020.04.22 [ONNX] Onnx convert 모델을 검증하자 (2)
  • 2020.03.09 [Onnx] Onnxruntime - GPU를 사용하자
  • 2020.02.26 [Onnx] onnx 모듈을 사용하기 위한 class를 만들어보자
  • 2020.02.26 [Onnx] visual studio에서 onnxruntime을 설치 해 보자
  • 2020.02.26 [Onnx] pytorch model을 onnx로 변환하여 사용하자 (1)
  • 2019.12.23 [Pytorch] Custom Dataloader를 사용하자
  • 2019.12.17 [Pytorch] multiGPU 에서 학습한 모델을 singleGPU에서 사용하자2 (1)
  • 2019.11.15 [Pytorch] pytorch 와 tensorboard를 같이 써보자.
  • 2019.03.18 [Pytorch] multiGPU 에서 학습한 모델을 singleGPU에서 사용하자
  • 2019.03.15 [Pytorch] tensor의 차원을 바꿔보자
  • 2019.03.15 [Pytorch] Multi GPU를 활용 해 보자 (2)
  • 2019.03.13 [Pytorch] network 결과물 사용시 주의사항!
  • 2019.03.13 [Pytorch] torch.load 에서 학습시와 환경이 달라서 못읽을 경우

[MXNet] 데이터 리스트를 만들고 rec 파일로 만들어 보자

전공관련/Deep Learning 2022. 4. 1. 09:44




 

MXNet 프레임워크에서는 RecordIO 를 이용하여 학습에 사용되는 데이터의 리스트를 만들고

해당파일을 rec파일로 만들어서 학습에 사용한다

 

단순히 이미지를 순차적으로 읽어 오는 경우에 비해 학습에 걸리는 시간이 유의미하게 차이나기 때문에

필요한 경우 rec파일로 만들어서 사용하면 도움이 될 수 있다.

 


파일 변환에는 im2rec.py 파일을 이용하고 해당 파일은 공식 github에서 받을 수 있다.

https://github.com/apache/incubator-mxnet/blob/master/tools/im2rec.py

 

GitHub - apache/incubator-mxnet: Lightweight, Portable, Flexible Distributed/Mobile Deep Learning with Dynamic, Mutation-aware D

Lightweight, Portable, Flexible Distributed/Mobile Deep Learning with Dynamic, Mutation-aware Dataflow Dep Scheduler; for Python, R, Julia, Scala, Go, Javascript and more - GitHub - apache/incubato...

github.com

 

 

[make list]
사용법 : python im2rec.py [outputpath/title] [DBPATH] --recursive --list --num-thread 8
예시 : python im2rec.py ./output/output /home/user/database/train --recursive --list --num-thread 8


[make rec - train]
사용법 : python im2rec.py [outputpath/] [DBPath] --recursive --pass-through --pack-label --num-thread 8
예시 : python im2rec.py ./output/ /home/user/database/train --recursive --pass-through --pack-label --num-thread 8

[make rec - test]
사용법 : python im2rec.py [outputpath/] [DBPath] --recursive --pass-through --pack-label --no-shuffle --num-thread 8

저작자표시

'전공관련 > Deep Learning' 카테고리의 다른 글

[MXNet] 데이터 리스트를 만들고 rec 파일로 만들어 보자  (0) 2022.04.01
[Pytorch] pycharm 환경에서 torch.distributed.launch를 실행하자  (1) 2021.07.13
[Tensorflow] h5py 관련 오류를 해결하자  (0) 2021.04.26
[ONNX] cuda 버전에 따른 python onnxruntime 버전을 맞추자.  (0) 2021.03.09
[용어] Ablation Study  (0) 2021.02.25
[Caffe] caffe 환경 설정없이 caffemodel 값을 확인하자  (0) 2021.02.24
블로그 이미지

매직블럭

작은 지식들 그리고 기억 한조각

트랙백 0개, 댓글 0개가 달렸습니다

댓글을 달아 주세요

[Pytorch] pycharm 환경에서 torch.distributed.launch를 실행하자

전공관련/Deep Learning 2021. 7. 13. 12:50




콘솔 환경에서 torch.distributed.launch를 이용하여 분산학습을 수행 할 경우에는 아래와 같이 사용이 가능하다

$ python -m torch.distributed.launch --params=value train.py

 

pycharm 환경에서 script의 파라미터를 주는 방법은 많이들 쓰니 잘 알지만

모듈을 실행하는 방법은 잘 몰라서 검색 후 사용 방법을 기록.


1. Edit configurations 진입

 

2. Configuration 탭의 Script Path 항목을 눌러 Module name으로 변경

 

3. Module name 에 모듈 이름을, parameters에 모듈 파라미터와 사용할 스크립트 정보를 입력

 

4. 해당 모듈 실행

 


위 방법을 이용하여 파이참 환경에서도 torch.distributed.launch 모듈을 이용한 

다중 GPU 분산 학습이 가능함을 확인 완료.

저작자표시

'전공관련 > Deep Learning' 카테고리의 다른 글

[MXNet] 데이터 리스트를 만들고 rec 파일로 만들어 보자  (0) 2022.04.01
[Pytorch] pycharm 환경에서 torch.distributed.launch를 실행하자  (1) 2021.07.13
[Tensorflow] h5py 관련 오류를 해결하자  (0) 2021.04.26
[ONNX] cuda 버전에 따른 python onnxruntime 버전을 맞추자.  (0) 2021.03.09
[용어] Ablation Study  (0) 2021.02.25
[Caffe] caffe 환경 설정없이 caffemodel 값을 확인하자  (0) 2021.02.24
블로그 이미지

매직블럭

작은 지식들 그리고 기억 한조각

트랙백 0개, 댓글 1개가 달렸습니다

댓글을 달아 주세요

  • 향란이 2021.08.21 13:10  댓글주소  수정/삭제  댓글쓰기

    와 이거 찾고있었는데 너무 감사합니다.

[Tensorflow] h5py 관련 오류를 해결하자

전공관련/Deep Learning 2021. 4. 26. 16:14




h5py is running against HDF5 1.10.5 when it was built against 1.10.4, this may cause problems~~ 

하면서 h5py 관련 오류가 발생 할 경우

 

강제로 h5py를 다시 설치 해 주면 보통은 문제가 해결 된다.

 

$ pip install h5py --upgrade --no-dependencies --force

저작자표시

'전공관련 > Deep Learning' 카테고리의 다른 글

[MXNet] 데이터 리스트를 만들고 rec 파일로 만들어 보자  (0) 2022.04.01
[Pytorch] pycharm 환경에서 torch.distributed.launch를 실행하자  (1) 2021.07.13
[Tensorflow] h5py 관련 오류를 해결하자  (0) 2021.04.26
[ONNX] cuda 버전에 따른 python onnxruntime 버전을 맞추자.  (0) 2021.03.09
[용어] Ablation Study  (0) 2021.02.25
[Caffe] caffe 환경 설정없이 caffemodel 값을 확인하자  (0) 2021.02.24
블로그 이미지

매직블럭

작은 지식들 그리고 기억 한조각

트랙백 0개, 댓글 0개가 달렸습니다

댓글을 달아 주세요

[ONNX] cuda 버전에 따른 python onnxruntime 버전을 맞추자.

전공관련/Deep Learning 2021. 3. 9. 15:31




python 환경에서 onnxruntime-gpu를 설치하여 사용하려는데 

자꾸만 "ImportError: cannot import name 'get_all_providers'" 가 발생했다.

 

구글링 해봐도 같은 증상을 겪는 사람이 많은데 한참을 찾다 발견한 내용.

onnxruntime release note에서 내가 못본건지 명확히 안쓰여있었던건지 모르겠지만

cuda 버전에 따라 지원하는 onnxruntime 버전이 다르기 떄문에 맞춰서 사용해야했다.

 

다음번 참고를 위해 onnx runtime ver - cuda ver 정보를 기록


  • onnx runtime v1.5.1 ~ v1.6.0 --> cuda 10.2 ( cuda 11 build from source)
  • onnx runtime v1.2.0 ~ v1.4.0 --> cuda 10.1
  • onnx runtime v0.5.0 ~ v1.1.2 --> cuda 10.0
  • onnx runtime v0.2.1 ~ v0.4.0 --> cuda 9.1 (nuget packages --> cuda 10.0)
저작자표시

'전공관련 > Deep Learning' 카테고리의 다른 글

[Pytorch] pycharm 환경에서 torch.distributed.launch를 실행하자  (1) 2021.07.13
[Tensorflow] h5py 관련 오류를 해결하자  (0) 2021.04.26
[ONNX] cuda 버전에 따른 python onnxruntime 버전을 맞추자.  (0) 2021.03.09
[용어] Ablation Study  (0) 2021.02.25
[Caffe] caffe 환경 설정없이 caffemodel 값을 확인하자  (0) 2021.02.24
[Pytorch] model load시 key가 있는 레이어만 불러오자  (0) 2021.02.17
블로그 이미지

매직블럭

작은 지식들 그리고 기억 한조각

트랙백 0개, 댓글 0개가 달렸습니다

댓글을 달아 주세요

[용어] Ablation Study

전공관련/Deep Learning 2021. 2. 25. 16:32




ablation 의 사전적 정의는 다음과 같다.

삭마(削磨: 풍화·침식 작용에 의해 얼음·눈·암석이 깎이는 현상)

사전적 의미만으로는 어떤 의미인지 파악이 쉽지 않다..

 

의학이나 심리학 연구에서, Ablation Study는 장기, 조직, 혹은 살아있는 유기체의 어떤 부분을 수술적인 제거 후에 이것이 없을때 해당 유기체의 행동을 관찰하는 것을 통해서 장기, 조직, 혹은 살아있는 유기체의 어떤 부분의 역할이나 기능을 실험해보는 방법을 의미한다고 한다.

 

이러한 기법을 머신러닝에 적용하여

성능에 영향을 주는 많은 요인들이 있을텐데 그러한 요인들을 제거하거나 변형하면서 

각 요인들이 최종 성능에 미치는 영향을 비교하는 실험 방법이라고 생각하면 되겠다.

저작자표시

'전공관련 > Deep Learning' 카테고리의 다른 글

[Tensorflow] h5py 관련 오류를 해결하자  (0) 2021.04.26
[ONNX] cuda 버전에 따른 python onnxruntime 버전을 맞추자.  (0) 2021.03.09
[용어] Ablation Study  (0) 2021.02.25
[Caffe] caffe 환경 설정없이 caffemodel 값을 확인하자  (0) 2021.02.24
[Pytorch] model load시 key가 있는 레이어만 불러오자  (0) 2021.02.17
[ONNX] Onnx convert 모델을 검증하자  (2) 2020.04.22
블로그 이미지

매직블럭

작은 지식들 그리고 기억 한조각

트랙백 0개, 댓글 0개가 달렸습니다

댓글을 달아 주세요

[Caffe] caffe 환경 설정없이 caffemodel 값을 확인하자

전공관련/Deep Learning 2021. 2. 24. 16:31




caffe는 안쓴지 오래되었지만 caffemodel의 값을 확인 해야 할 일이 있어서 오랜만에 caffe쪽으로 눈을 돌렸다.

caffe 환경을 세팅하기는 너무 귀찮은데다 실제 쓸일도 없는데 caffemodel의 값만 확인하고 싶은 경우를 위해 기록

 


opencv에 dnn 모듈이 3.1 부터는 추가모듈로 지원됐고 3.3 버전부터는 기본 모듈로 포함되었다.

 

이 모듈을 이용하여 caffe환경설정 따로 할 필요 없이 네트워크 불러오고 inference 하는데 전혀 문제가 없었다.

보통 기본 모델 추론용도로만 사용했었으나 갑자기 caffemodel 에 포함되어 있는 weight의 값 확인이 필요할 경우에도

opencv 의 dnn 모듈을 이용하여 확인 할 수있다는 것을 확인하여 적어둠...

 

# python 기준.. 
# c++에서는 Layer::blob을 이용하는거 같던데
# 실제 코드로 확인하지는 않았다.

import cv2

# load caffemodel
net = cv2.dnn.readNetFromCaffe(prototxt, caffemodel)

# get layer name
layer_names = net.getLayerNames()

# get params
layer_params = net.getParam(layerName)

 

저작자표시

'전공관련 > Deep Learning' 카테고리의 다른 글

[ONNX] cuda 버전에 따른 python onnxruntime 버전을 맞추자.  (0) 2021.03.09
[용어] Ablation Study  (0) 2021.02.25
[Caffe] caffe 환경 설정없이 caffemodel 값을 확인하자  (0) 2021.02.24
[Pytorch] model load시 key가 있는 레이어만 불러오자  (0) 2021.02.17
[ONNX] Onnx convert 모델을 검증하자  (2) 2020.04.22
[Onnx] Onnxruntime - GPU를 사용하자  (0) 2020.03.09
블로그 이미지

매직블럭

작은 지식들 그리고 기억 한조각

트랙백 0개, 댓글 0개가 달렸습니다

댓글을 달아 주세요

[Pytorch] model load시 key가 있는 레이어만 불러오자

전공관련/Deep Learning 2021. 2. 17. 17:00





이전에 pretrained model을 불러올 때 key set이 일치하지 않아 발생하는 문제를 dict를 수정하여 불러온 적이 있다.

 

[Pytorch] pretrained-model 의 일부만을 불러와 보자

pretrained model 의 구조 : ['A', 'B', 'C', 'D'] new model의 구조 : ['A', 'B', 'C', 'E'] 라고 가정하고.. 단순히 load_state_dict를 이용하여 pretrained model의 값을 읽어오면 Missing key(s) in state_dic..

jangjy.tistory.com

 

이러한 일련의 과정을 자동으로 처리해주는 파라미터가 load_state_dict 함수에 있어서 기록.

 


 

pretrained model 의 구조 : ['A', 'B', 'C', 'D']

new model의 구조 : ['A', 'B', 'C', 'E']  라고 가정하고..

 

단순히 load_state_dict를 이용하여 pretrained model의 값을 읽어오면

Missing key(s) in state_dict: "E.weighjt", "E.bias". 와 같은 에러를 발생시킨다.


이때 load_state_dict 함수에 strict=False 파라미터를 추가해주면 key set 이 일치하는 레이어의 값만 읽어온다.

즉, 위의 가정과 같은 상황에서는 A, B, C 는 pretrained model의 weight가 load 되고

key가 없는 E 에는 random으로 초기값이 할당된다. 

 

굳이 없는 key를 찾고 새로운 dict를 만들 필요없이 pytorch에서 제공하는 방법을 쓰면 간단하다..

저작자표시

'전공관련 > Deep Learning' 카테고리의 다른 글

[용어] Ablation Study  (0) 2021.02.25
[Caffe] caffe 환경 설정없이 caffemodel 값을 확인하자  (0) 2021.02.24
[Pytorch] model load시 key가 있는 레이어만 불러오자  (0) 2021.02.17
[ONNX] Onnx convert 모델을 검증하자  (2) 2020.04.22
[Onnx] Onnxruntime - GPU를 사용하자  (0) 2020.03.09
[Onnx] onnx 모듈을 사용하기 위한 class를 만들어보자  (0) 2020.02.26
블로그 이미지

매직블럭

작은 지식들 그리고 기억 한조각

트랙백 0개, 댓글 0개가 달렸습니다

댓글을 달아 주세요

[ONNX] Onnx convert 모델을 검증하자

전공관련/Deep Learning 2020. 4. 22. 11:29




pytorch 등의 프레임워크에서 onnx로 convert 한 모델이 잘 변환됐는지 늘 확인이 필요하다.

 

이럴 때 확인을 위한 방법 정리

 


import torch
import numpy as np
import onnxruntime as rt

def to_numpy(tensor):
    return tensor.detach().cpu().numpy() if tensor.requires_grad else tensor.cpu().numpy()
    
def test():
    model_pytorch = Net() # 네트워크 선언 및 가중치 로드 했다 치고..
    x = torch.rand(b, c, h, w)
    
    out_torch = model_pytorch(x)
    
    sess = rt.InferenceSession("onnx_model.onnx")
    input_name = sess.get_inputs()[0].name
    label_name = sess.get_outputs()[0].name
    
    out_onnx = sess.run(None, {input_name: x})
    
    np.testing.assert_allclose(to_numpy(out_torch), out_onnx[0], rtol=1e-03, atol=1e-05)
    print("Exported model has been tested with ONNXRuntime, and the result looks good!")

 

결과가 오차범위 (rtol=1e-03, atol=1e-05) 안에 있다면 마지막 프린트문이 출력 될 것이고

오차범위 밖이라면 에러가 발생한다. 이는 변환이 잘못됐다는 얘기지..

저작자표시

'전공관련 > Deep Learning' 카테고리의 다른 글

[Caffe] caffe 환경 설정없이 caffemodel 값을 확인하자  (0) 2021.02.24
[Pytorch] model load시 key가 있는 레이어만 불러오자  (0) 2021.02.17
[ONNX] Onnx convert 모델을 검증하자  (2) 2020.04.22
[Onnx] Onnxruntime - GPU를 사용하자  (0) 2020.03.09
[Onnx] onnx 모듈을 사용하기 위한 class를 만들어보자  (0) 2020.02.26
[Onnx] visual studio에서 onnxruntime을 설치 해 보자  (0) 2020.02.26
블로그 이미지

매직블럭

작은 지식들 그리고 기억 한조각

트랙백 0개, 댓글 2개가 달렸습니다

댓글을 달아 주세요

  • 유니디니 2020.08.05 19:18 신고  댓글주소  수정/삭제  댓글쓰기

    좋은 글 감사합니다.궁금한 점이 있어 글 남깁니다.

    np.testing.assert_allclose 함수의 두번째 인자(pred[0])의 경우 위의 sess.run 함수에서 나온 결과인 out_onnx 값을 넣으면 되는 건가요?

    유용한 정보라서 출처 밝히고 퍼가도 괜찮을까요?

    • 매직블럭 2020.08.07 13:36 신고  댓글주소  수정/삭제

      코드상 오류가 있어서 수정하였습니다.

      위 내용은 pytorch 튜토리얼 문서에 있는 내용이므로 자유롭게 사용하셔도 됩니다.

[Onnx] Onnxruntime - GPU를 사용하자

전공관련/Deep Learning 2020. 3. 9. 16:08




지난번 작성한 글에서 class를 생성하여 사용하는 부분까지는 구현을 했다.( https://jangjy.tistory.com/356 )

 

[Onnx] onnx 모듈을 사용하기 위한 class를 만들어보자

onnxruntime 예제코드에는 struct를 생성하여 사용하는 방법이 나와있다. 코드 중 주요 부분만 떼서 보면 아래와 같다. struct ETRI_FV { ETRI_FV() { auto memory_info = Ort::MemoryInfo::CreateCpu(OrtDeviceAl..

jangjy.tistory.com

 

그런데 학습 했던 모델을 이용하여 추론을 돌려보니 이상하게 속도가 느리다..

VS Nuget 패키지가 문제인가.. 이것저것 깔았다 지웠다.. 소스로부터 빌드도 시도 해보고..

아무리 봐도 이건 GPU 에서 도는 속도가 아니라 CPU에서 도는 속도였다..

그래서 찾고 방황하다 github 에 문의 한 결과 답변을 얻을 수 있었다.

 


아주 간단한 문제로, GPU를 사용하기 위해서는 session을 생성할 때 옵션을 지정 해 줘야한다.

#include <cuda_provider_factory.h>

Ort::SessionOptions session_options;
// cuda 사용하기 위해 provider 추가
Ort::ThrowOnError(OrtSessionOptionsAppendExecutionProvider_CUDA(session_option, 0));
// 추가 graph 최적화 옵션 
session_options.SetGraphOptimizationLevel(GraphOptimizationLevel::ORT_ENABLE_EXTENDED);

session_ = new Ort::Session(env, wPath, session_options);

 

CUDA 옵션의 두번째 파라미터는 gpu 번호다.

다중 GPU 환경에서 어느 GPU가 연산을 담당할지 지정 가능하다.

 

별거 아닌 문제였는데 이놈 떄문에 일주일을 까먹었네..

저작자표시

'전공관련 > Deep Learning' 카테고리의 다른 글

[Pytorch] model load시 key가 있는 레이어만 불러오자  (0) 2021.02.17
[ONNX] Onnx convert 모델을 검증하자  (2) 2020.04.22
[Onnx] Onnxruntime - GPU를 사용하자  (0) 2020.03.09
[Onnx] onnx 모듈을 사용하기 위한 class를 만들어보자  (0) 2020.02.26
[Onnx] visual studio에서 onnxruntime을 설치 해 보자  (0) 2020.02.26
[Onnx] pytorch model을 onnx로 변환하여 사용하자  (1) 2020.02.26
블로그 이미지

매직블럭

작은 지식들 그리고 기억 한조각

트랙백 0개, 댓글 0개가 달렸습니다

댓글을 달아 주세요

[Onnx] onnx 모듈을 사용하기 위한 class를 만들어보자

전공관련/Deep Learning 2020. 2. 26. 13:08




onnxruntime 예제코드에는 struct를 생성하여 사용하는 방법이 나와있다. 

코드 중 주요 부분만 떼서 보면 아래와 같다.

struct onnx_struct {
	onnx_struct() {
		auto memory_info = Ort::MemoryInfo::CreateCpu(OrtDeviceAllocator, OrtMemTypeCPU);
		input_tensor_ = Ort::Value::CreateTensor<float>(memory_info, input_image_.data(), input_image_.size(), input_shape_.data(), input_shape_.size());
		output_tensor_ = Ort::Value::CreateTensor<float>(memory_info, results_.data(), results_.size(), output_shape_.data(), output_shape_.size());
	}

	std::array<float, 1000> Run() {
		const char* input_names[] = { "input" };
		const char* output_names[] = { "output" };

		session_.Run(Ort::RunOptions{ nullptr }, input_names, &input_tensor_, 1, output_names, &output_tensor_, 1);

		// result_ = std::distance(results_.begin(), std::max_element(results_.begin(), results_.end()));
		return results_;
	}

	static constexpr const int width_ = 128;
	static constexpr const int height_ = 128;

	std::array<float, width_ * height_> input_image_{};
	std::array<float, 1000> results_{};
	// int64_t result_{ 0 };

private:
	Ort::Env env;
	Ort::Session session_{ env, L"./data/test_onnx.onnx", Ort::SessionOptions{ nullptr } };

	Ort::Value input_tensor_{ nullptr };
	std::array<int64_t, 4> input_shape_{ 1, 1, width_, height_ };

	Ort::Value output_tensor_{ nullptr };
	std::array<int64_t, 2> output_shape_{ 1, 1000 };
};

입력 사이즈와 출력 크기가 다 하드코딩 되어있을 뿐 아니라 모델 로드 부분도 구조체 생성단계에서 수행하니

활용 측면에서는 영 꽝이다. 

 


 

그래서 동적으로 사용 가능하도록 클래스 수정 중..

필요한 기능에 따라 지속적으로 수정 예정. ( 혹 비효율 적이거나 다른 방법이 있다면 알려주세요)

class onnx_module
{
public:
	onnx_module(std::string sModelPath, int nInputC, int nInputWidth, int nInputHeight, int nOutputDims);
	onnx_module(std::string sModelPath, int nInputC, int nInputWidth, int nInputHeight, int nOutputC, int nOutputWidth, int nOutputHeight);
	void Run(std::vector<float>& vResults);

	std::vector<float> results_;
	std::vector<float> input_image_;

private:
	Ort::Env env;
	Ort::Session* session_;

	Ort::Value input_tensor_{ nullptr };
	std::vector<int64_t> input_shape_;

	Ort::Value output_tensor_{ nullptr };
	std::vector<int64_t> output_shape_;
};

onnx_module::onnx_module(std::string sModelPath, int nInputC, int nInputWidth, int nInputHeight, int nOutputDims)
{
	std::string sPath = sModelPath;
	wchar_t* wPath = new wchar_t[sPath.length() + 1];
	std::copy(sPath.begin(), sPath.end(), wPath);
	wPath[sPath.length()] = 0;

	session_ = new Ort::Session(env, wPath, Ort::SessionOptions{ nullptr });
	delete[] wPath;

	const int batch_ = 1;
	const int channel_ = nInputC;
	const int width_ = nInputWidth;
	const int height_ = nInputHeight;

	input_image_.assign(width_*height_*channel_, 0.0);
	results_.assign(nOutputDims, 0.0);

	input_shape_.clear();
	input_shape_.push_back(batch_);
	input_shape_.push_back(channel_);
	input_shape_.push_back(width_);
	input_shape_.push_back(height_);

	output_shape_.clear();
	output_shape_.push_back(batch_);
	output_shape_.push_back(nOutputDims);



	auto memory_info = Ort::MemoryInfo::CreateCpu(OrtDeviceAllocator, OrtMemTypeCPU);
	input_tensor_ = Ort::Value::CreateTensor<float>(memory_info, input_image_.data(), input_image_.size(), input_shape_.data(), input_shape_.size());
	output_tensor_ = Ort::Value::CreateTensor<float>(memory_info, results_.data(), results_.size(), output_shape_.data(), output_shape_.size());
}

onnx_module::onnx_module(std::string sModelPath, int nInputC, int nInputWidth, int nInputHeight, int nOutputC, int nOutputWidth, int nOutputHeight)
{
	std::string sPath = sModelPath;
	wchar_t* wPath = new wchar_t[sPath.length() + 1];
	std::copy(sPath.begin(), sPath.end(), wPath);
	wPath[sPath.length()] = 0;


	session_ = new Ort::Session(env, wPath, Ort::SessionOptions{ nullptr });
	delete[] wPath;

	const int batch_ = 1;

	const int channel_in = nInputC;
	const int width_in = nInputWidth;
	const int height_in = nInputHeight;

	const int channel_out = nOutputC;
	const int width_out = nOutputWidth;
	const int height_out = nOutputHeight;

	input_image_.assign(width_in * height_in * channel_in, 0.0);
	results_.assign(nOutputWidth * nOutputHeight * nOutputC, 0.0);

	input_shape_.clear();
	input_shape_.push_back(batch_);
	input_shape_.push_back(channel_in);
	input_shape_.push_back(width_in);
	input_shape_.push_back(height_in);

	output_shape_.clear();
	output_shape_.push_back(batch_);
	output_shape_.push_back(channel_out);
	output_shape_.push_back(width_out);
	output_shape_.push_back(height_out);



	auto memory_info = Ort::MemoryInfo::CreateCpu(OrtDeviceAllocator, OrtMemTypeCPU);
	input_tensor_ = Ort::Value::CreateTensor<float>(memory_info, input_image_.data(), input_image_.size(), input_shape_.data(), input_shape_.size());
	output_tensor_ = Ort::Value::CreateTensor<float>(memory_info, results_.data(), results_.size(), output_shape_.data(), output_shape_.size());
}

void onnx_module::Run(std::vector<float>& vResults)
{
	const char* input_names[] = { "input" };
	const char* output_names[] = { "output" };

	(*session_).Run(Ort::RunOptions{ nullptr }, input_names, &input_tensor_, 1, output_names, &output_tensor_, 1);

	vResults.assign(results_.begin(), results_.end());
}

 

아직 수정해야 할 부분이 많다... 어렵다.. ㅋ

저작자표시

'전공관련 > Deep Learning' 카테고리의 다른 글

[ONNX] Onnx convert 모델을 검증하자  (2) 2020.04.22
[Onnx] Onnxruntime - GPU를 사용하자  (0) 2020.03.09
[Onnx] onnx 모듈을 사용하기 위한 class를 만들어보자  (0) 2020.02.26
[Onnx] visual studio에서 onnxruntime을 설치 해 보자  (0) 2020.02.26
[Onnx] pytorch model을 onnx로 변환하여 사용하자  (1) 2020.02.26
[Pytorch] Custom Dataloader를 사용하자  (0) 2019.12.23
블로그 이미지

매직블럭

작은 지식들 그리고 기억 한조각

트랙백 0개, 댓글 0개가 달렸습니다

댓글을 달아 주세요

[Onnx] visual studio에서 onnxruntime을 설치 해 보자

전공관련/Deep Learning 2020. 2. 26. 12:57




onnx를 inference 용으로 사용하기 위해서는 ms에서 제공하는 onnxruntime을 이용하는 것이 좋다.

https://microsoft.github.io/onnxruntime/

 

ONNX Runtime | Home

Get Started Easily Select your requirements and use the resources provided to get started quickly

microsoft.github.io

 

위 공식 페이지에서는 다양한 os, 언어, 하드웨어가속기를 선택하여 설치하는 옵션을 제공하니

다른 방법을 원한다면 한번 찾아보자.

 


visual studio를 이용할 경우에는 Nuget 패키지 관리자를 이용하는 것이 가장 편한 것 같다.

물론 다양한 다른 옵션을 필요로 한다면 소스로부터 빌드해야겠지만..

 

설치 순서는 아래와 같다.

  • VS Solution - Tools - NuGet Package Manager - Package Manager Console
  • PM> Install-Package Microsoft.ML.OnnxRuntime.Gpu -Version 1.1.0
    (참고 : https://www.nuget.org/packages/Microsoft.ML.OnnxRuntime.gpu )
 

Microsoft.ML.OnnxRuntime.Gpu 1.1.2

This package contains ONNX Runtime for .Net platforms

www.nuget.org

 

설치가 완료 된 후에는 패키지 관리자에서 프로젝트 단위로 설치 제거 등도 손쉽게 처리 가능하다.

저작자표시

'전공관련 > Deep Learning' 카테고리의 다른 글

[Onnx] Onnxruntime - GPU를 사용하자  (0) 2020.03.09
[Onnx] onnx 모듈을 사용하기 위한 class를 만들어보자  (0) 2020.02.26
[Onnx] visual studio에서 onnxruntime을 설치 해 보자  (0) 2020.02.26
[Onnx] pytorch model을 onnx로 변환하여 사용하자  (1) 2020.02.26
[Pytorch] Custom Dataloader를 사용하자  (0) 2019.12.23
[Pytorch] multiGPU 에서 학습한 모델을 singleGPU에서 사용하자2  (1) 2019.12.17
블로그 이미지

매직블럭

작은 지식들 그리고 기억 한조각

트랙백 0개, 댓글 0개가 달렸습니다

댓글을 달아 주세요

[Onnx] pytorch model을 onnx로 변환하여 사용하자

전공관련/Deep Learning 2020. 2. 26. 12:52




onnx는 open neural network exchange의 약자로 신경망 모델을 framework 간 변환하도록 만들어진 것이다.

 

기존 framework만을 사용할 수 있는 환경이라면 그냥 사용해도 문제가 없지만
여러 이유로 인하여 onnx로의 변환이 필요할 수 있다.

 

그래서 우선 torch model을 onnx 모델로 변환하는 방법 정리.

 

변환 방법은 torchScript를 이용하여 pt 파일을 생성하는 것과 거의 동일한 형태로 변환이 가능하다.

 


# model load
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model = pytorch_model()
model.to(device)
model.eval()

checkpoint = torch.load("./model/pytorch_model_weight.pth.tar", map_location=device)
checkpoint_dict = get_state_dict(checkpoint["state_dict"])
model.load_state_dict(checkpoint_dict)

# make dummy data
batch_size = 1
# model input size에 맞게 b c h w 순으로 파라미터 설정
x = torch.rand(batch_size, 1, 128, 128, requires_grad=True).to(device)
# feed-forward test
output = model(x)

# convert
torch.onnx.export(model, x, "./test_onnx.onnx", export_params=True, opset_version=10, do_constant_folding=True
                  , input_names = ['input'], output_names=['output']
                  # , dynamic_axes={'input' : {0 : 'batch_size'}, 'output' : {0 : 'batch_size'}}
                  # dynamic axes 는 pytorch 1.2 부터 지원하는듯??
                  )
저작자표시

'전공관련 > Deep Learning' 카테고리의 다른 글

[Onnx] onnx 모듈을 사용하기 위한 class를 만들어보자  (0) 2020.02.26
[Onnx] visual studio에서 onnxruntime을 설치 해 보자  (0) 2020.02.26
[Onnx] pytorch model을 onnx로 변환하여 사용하자  (1) 2020.02.26
[Pytorch] Custom Dataloader를 사용하자  (0) 2019.12.23
[Pytorch] multiGPU 에서 학습한 모델을 singleGPU에서 사용하자2  (1) 2019.12.17
[Pytorch] pytorch 와 tensorboard를 같이 써보자.  (0) 2019.11.15
블로그 이미지

매직블럭

작은 지식들 그리고 기억 한조각

트랙백 0개, 댓글 1개가 달렸습니다

댓글을 달아 주세요

  • 익명 2021.12.02 22:01  댓글주소  수정/삭제  댓글쓰기

    비밀댓글입니다

[Pytorch] Custom Dataloader를 사용하자

전공관련/Deep Learning 2019. 12. 23. 10:21




torch를 사용하다보면 단순 classification이면 기본 폴더로부터 읽어오는 dataloader를 써도 되지만 

새로운 작업을 하거나 classification 외의 다른 학습을 위해서는 custom dataloader가 필요한 경우가 있다.

 

필요한 기능에 따라 custum dataloader의 기본형을 정리 해 둘 예정!

 


1. 각 class 폴더 안에 이미지 데이터가 있는 경우

    (단, 이 경우 실제 class 이름(폴더명)을 가져오려면 폴더명 list에서 id번째 폴더명을 받아와야함)

class customDL(Dataset):
    def read_data_set(self):
        all_img_files = []
        all_labels = []

        class_names = os.walk(self.data_set_path).__next__()[1]

        for index, class_name in enumerate(class_names):
            label = index
            img_dir = os.path.join(self.data_set_path, class_name)
            img_files = os.walk(img_dir).__next__()[2]

            for img_file in img_files:
                img_file = os.path.join(img_dir, img_file)
                img = cv2.imread(img_file, flags=cv2.IMREAD_GRAYSCALE)
                if img is not None:
                    all_img_files.append(img_file)
                    all_labels.append(label)

        return all_img_files, all_labels, len(all_img_files), len(class_names)

    def __init__(self, folder_path, transform=None):
        self.data_set_path = folder_path
        self.image_files_path, self.labels, self.length, self.num_classes = self.read_data_set()
        self.transform = transform

    def __getitem__(self, idx):
        img_origin = cv2.imread(self.image_files_path[idx], flags=cv2.IMREAD_GRAYSCALE)

       # 필요한 연산 수행.

        id = self.labels[idx]

        return img_origin, id

    def __len__(self):
        return self.length

 

 

 

[추가 예정..]

 

 
저작자표시

'전공관련 > Deep Learning' 카테고리의 다른 글

[Onnx] visual studio에서 onnxruntime을 설치 해 보자  (0) 2020.02.26
[Onnx] pytorch model을 onnx로 변환하여 사용하자  (1) 2020.02.26
[Pytorch] Custom Dataloader를 사용하자  (0) 2019.12.23
[Pytorch] multiGPU 에서 학습한 모델을 singleGPU에서 사용하자2  (1) 2019.12.17
[Pytorch] pytorch 와 tensorboard를 같이 써보자.  (0) 2019.11.15
[Pytorch] multiGPU 에서 학습한 모델을 singleGPU에서 사용하자  (0) 2019.03.18
블로그 이미지

매직블럭

작은 지식들 그리고 기억 한조각

트랙백 0개, 댓글 0개가 달렸습니다

댓글을 달아 주세요

[Pytorch] multiGPU 에서 학습한 모델을 singleGPU에서 사용하자2

전공관련/Deep Learning 2019. 12. 17. 17:35




[Pytorch] multiGPU 에서 학습한 모델을 singleGPU에서 사용하자

지난난 글에서 사용한한 방법은 저장 단계에서 적용해야 하는 문제가 있어서 

이번에는 다시 state_dict를 읽어서 key에서 module을 제거하고 다시 넣어주는 방법을 사용.


우선 state_dict의 key에서 module 을 제거한 새로운 dict를 반환하는 함수 선언

def get_state_dict(origin_dict):
    old_keys = origin_dict.keys()
    new_dict = {}

    for ii in old_keys:
        temp_key = str(ii)
        if temp_key[0:7] == "module.":
            new_key = temp_key[7:]
        else:
            new_key = temp_key

        new_dict[new_key] = origin_dict[temp_key]
    return new_dict

 

이후 네트워크 가중치를 읽을때 위 함수를 통해 다시 읽어주면 문제없이 사용 가능하다.

# 위쪽은 생략

net = CNN_Network(num_classes=1000)
net.to(device)
net.eval()

checkpoint = torch.load('model_path/model_file.pth.tar', map_location=device)
checkpoint_dict = get_state_dict(checkpoint["state_dict"])
net.load_state_dict(checkpoint_dict)

 

 

(21.01.06. 수정)

위의 get_state_dict를 람다식을 이용하여 깔끔하게 구현된 코드를 확인하여 기록.

(출처 : github.com/biubug6/Pytorch_Retinaface / RetinaFace)

 

def remove_prefix(state_dict, prefix):
    ''' Old style model is stored with all names of parameters sharing common prefix 'module.' '''
    print('remove prefix \'{}\''.format(prefix))
    f = lambda x: x.split(prefix, 1)[-1] if x.startswith(prefix) else x
    return {f(key): value for key, value in state_dict.items()}
    
# 사용할때는
pretrained_dict = remove_prefix(pretrained_dict, 'module.')
저작자표시

'전공관련 > Deep Learning' 카테고리의 다른 글

[Onnx] pytorch model을 onnx로 변환하여 사용하자  (1) 2020.02.26
[Pytorch] Custom Dataloader를 사용하자  (0) 2019.12.23
[Pytorch] multiGPU 에서 학습한 모델을 singleGPU에서 사용하자2  (1) 2019.12.17
[Pytorch] pytorch 와 tensorboard를 같이 써보자.  (0) 2019.11.15
[Pytorch] multiGPU 에서 학습한 모델을 singleGPU에서 사용하자  (0) 2019.03.18
[Pytorch] tensor의 차원을 바꿔보자  (0) 2019.03.15
블로그 이미지

매직블럭

작은 지식들 그리고 기억 한조각

트랙백 0개, 댓글 1개가 달렸습니다

댓글을 달아 주세요

  • yong 2020.03.10 21:04  댓글주소  수정/삭제  댓글쓰기

    검색하다가 쉽게 해결했네요. 감사합니다 ^^

[Pytorch] pytorch 와 tensorboard를 같이 써보자.

전공관련/Deep Learning 2019. 11. 15. 15:09




pytorch 환경에서는 적당한 log visualization tool이 없었다.

log를 파싱해서 plot 하거나, visdom을 쓴다고 해도 부족한 부분이 있어서 아쉬운점이 있었지만

pytorch가 1.3버전으로 올라가면서부터 tensorflow의 tensorboard와 연동이 가능해 졌다.

그래서 사용 방법 정리!

 


우선 anaconda의 가상환경을 사용하는 것을 것을 전제로 시작. pip와 큰 차이는 없다.

 

1. tensorflow 설치

tensorflow와 함께 설치되는 tensorboard가 있어야 한다.

# install tensorflow
conda install tensorflow

 

2. tensorboardx 설치

pip를 이용 할 경우 버전 문제로 에러가 발생하는 경우도 있다해서 나는 conda로 설치 (190115 기준)

# pip
pip install tensorboardx

# conda
conda install -c conda-forge tensorboardx

 

3. import tensorboardx

SummaryWriter를 생성하면 실행중인 경로에 runs 폴더가 자동 생성됨. 이벤트는 여기에 저장.

from tensorboardx import SummaryWriter
summary = SummaryWriter()

 

4. tensorboard 출력을 위한 값 저장하기

summarywriter에는 다양한 값을 저장 할 수 있다.

아래 예 외에도 오디오, 임베딩, json export, pr curve 등의 옵션도 존재한다. 

(참고 : https://pytorch.org/docs/stable/tensorboard.html)

writer를 close 하지 않으면 값이 저장되지 않으니 close 해주던가 with 안에 넣어주자.

# 단일 변수
writer.add_scalar("그룹/변수명", 변수, iter)

# 다중 변수
# 한 그래프에 여러 변수를 그릴경우는 dict 형태로 넘겨준다
writer.add_scalars("그룹/변수명", 변수dict, iter)

# 이미지, index는 N, C , W, H 순
# 3차원 numpy array도 가능. 4차원 이상은 tensor로 변환 필요
writer.add_image("그룹/변수명", tensor(or numpyArr), iter)

# 텍스트
writer.add_text("그룹/변수명", "text", iter)

# named_param
for name, param in NET.named_parameters():
	writer.add_histogram(name, param.clone().cpu.data.numpy(), iter)
    
# 저장 후에는 반드시 writer close 해주기
writer.close()

 

5. tensorboard 서버 활성화 하여 결과 확인하기

tensorboard --logdir [log 경로] --port=XXXX(Optional, default=6006)
# example
tensorboard --logdir ./runs

 

6. tensorboard 서버 접근

# web browser에서 
localhost:[설정한 포트]

# ex
localhost:6006
저작자표시

'전공관련 > Deep Learning' 카테고리의 다른 글

[Pytorch] Custom Dataloader를 사용하자  (0) 2019.12.23
[Pytorch] multiGPU 에서 학습한 모델을 singleGPU에서 사용하자2  (1) 2019.12.17
[Pytorch] pytorch 와 tensorboard를 같이 써보자.  (0) 2019.11.15
[Pytorch] multiGPU 에서 학습한 모델을 singleGPU에서 사용하자  (0) 2019.03.18
[Pytorch] tensor의 차원을 바꿔보자  (0) 2019.03.15
[Pytorch] Multi GPU를 활용 해 보자  (2) 2019.03.15
블로그 이미지

매직블럭

작은 지식들 그리고 기억 한조각

트랙백 0개, 댓글 0개가 달렸습니다

댓글을 달아 주세요

[Pytorch] multiGPU 에서 학습한 모델을 singleGPU에서 사용하자

전공관련/Deep Learning 2019. 3. 18. 10:04




일반적으로 테스트 환경이 아닌 실제 메인 모델을 학습 할 때에는 다중 GPU를 이용하여 학습하는 경우가 많다
이럴 경우 보통 pytorch에서 지원하는 nn.DataParallel ([Pytorch] Multi GPU를 활용 해 보자) 을 이용한다


이렇게 잘 학습을 하고 inference를 위해 모델을 load 할 때 map_location을 이용하여 single GPU를 지정했다
( [Pytorch] torch.load 에서 학습시와 환경이 달라서 못읽을 경우 )


이러면 동일하게 읽을 수 있을 줄 알았는데 "layer.0.weight, layer.1.weight, ... " 이런 형태의 key값을 찾지 못한다며 에러를 발생시켰다.


이럴 경우에는 저장 단계에서 

torch.save(net.state_dict(), savePath)

를 사용하지 말고 대신에

torch.save(net.module.state_dict(), savePath)

와 같이 .module을 붙여서 저장하면 일반적으로 사용하듯이 model 을 load 할 수 있다.


저작자표시비영리

'전공관련 > Deep Learning' 카테고리의 다른 글

[Pytorch] multiGPU 에서 학습한 모델을 singleGPU에서 사용하자2  (1) 2019.12.17
[Pytorch] pytorch 와 tensorboard를 같이 써보자.  (0) 2019.11.15
[Pytorch] multiGPU 에서 학습한 모델을 singleGPU에서 사용하자  (0) 2019.03.18
[Pytorch] tensor의 차원을 바꿔보자  (0) 2019.03.15
[Pytorch] Multi GPU를 활용 해 보자  (2) 2019.03.15
[Pytorch] network 결과물 사용시 주의사항!  (0) 2019.03.13
블로그 이미지

매직블럭

작은 지식들 그리고 기억 한조각

트랙백 0개, 댓글 0개가 달렸습니다

댓글을 달아 주세요

[Pytorch] tensor의 차원을 바꿔보자

전공관련/Deep Learning 2019. 3. 15. 16:14




사용하다 보면 tensor의 차원을 바꿔야 할 경우가 있다.

ex) single data로 테스트를 하려는데 nn.module의 입력은 4차원 텐서일 경우 등.


이럴 경우 차원을 늘리거나 줄여야 할 때는 torch.squeeze() 와 torch.unsqueeze() 함수를 이용한다.

# a => torch.Size([1, 128, 128])
a = torch.squeeze(a) # a => torch.Size([128, 128])
a = torch.unsqueeze(a, 0) # a => torch.Size([1, 128, 128])
a = torch.unsqueeze(a, 0) # a => torch.Size([1, 1, 128, 128])
a = torch.unsqueeze(a, 3) # a => torch.Size([1, 1, 128, 1, 128])
a = torch.squeeze(a, 3) # a => torch.Size([1, 1, 128, 128])


저작자표시비영리

'전공관련 > Deep Learning' 카테고리의 다른 글

[Pytorch] pytorch 와 tensorboard를 같이 써보자.  (0) 2019.11.15
[Pytorch] multiGPU 에서 학습한 모델을 singleGPU에서 사용하자  (0) 2019.03.18
[Pytorch] tensor의 차원을 바꿔보자  (0) 2019.03.15
[Pytorch] Multi GPU를 활용 해 보자  (2) 2019.03.15
[Pytorch] network 결과물 사용시 주의사항!  (0) 2019.03.13
[Pytorch] torch.load 에서 학습시와 환경이 달라서 못읽을 경우  (0) 2019.03.13
블로그 이미지

매직블럭

작은 지식들 그리고 기억 한조각

트랙백 0개, 댓글 0개가 달렸습니다

댓글을 달아 주세요

[Pytorch] Multi GPU를 활용 해 보자

전공관련/Deep Learning 2019. 3. 15. 10:18




일반적으로 하나의 gpu를 사용할 경우 아래와 같이 이용 가능

device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
net = Net()
net.to(device)


multi-gpu를 이용하기 위해서는 아래와 같이 nn.DataParallel을 이용하여 손쉽게 사용 가능하다.

device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
net = Net()
if torch.cuda.device_count() > 1:
net = nn.DataParallel(net)
net.to(device)

이런식으로 설정 할 경우 선언한 batch size가 알아서 각 gpu로 분배되는 방식.

여러 gpu를 효율적으로 사용하려면 사용할 gpu 수만큼 batch size도 늘려주자.



추가적으로 어느 gpu를 사용할 것인가에 대한 선택의 방법은 확인 후 수정. 아래의 방법을 사용.

pytorch 기능을 써서 설정하는 방법은 모르겠다. 

os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"
os.environ["CUDA_VISIBLE_DEVICES"] = "1,3"


저작자표시비영리

'전공관련 > Deep Learning' 카테고리의 다른 글

[Pytorch] multiGPU 에서 학습한 모델을 singleGPU에서 사용하자  (0) 2019.03.18
[Pytorch] tensor의 차원을 바꿔보자  (0) 2019.03.15
[Pytorch] Multi GPU를 활용 해 보자  (2) 2019.03.15
[Pytorch] network 결과물 사용시 주의사항!  (0) 2019.03.13
[Pytorch] torch.load 에서 학습시와 환경이 달라서 못읽을 경우  (0) 2019.03.13
[Pytorch] pretrained-model 의 일부만을 불러와 보자  (0) 2019.03.12
블로그 이미지

매직블럭

작은 지식들 그리고 기억 한조각

트랙백 0개, 댓글 2개가 달렸습니다

댓글을 달아 주세요

  • 쌍갑포차 2020.06.01 16:00  댓글주소  수정/삭제  댓글쓰기

    잘 배우고 갑니다

  • Haewon Lee 2020.06.19 10:57 신고  댓글주소  수정/삭제  댓글쓰기

    이 부분은 device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
    device = "cuda" if torch.cuda.is_available() else "cpu" 만써도 무방하며 gpu를 바꿀 때에는
    cuda:0, cuda:1, cuda:2 이런식으로 바꾸면 됩니다.

[Pytorch] network 결과물 사용시 주의사항!

전공관련/Deep Learning 2019. 3. 13. 14:34




일반적으로 deep learning network를 통과 한 결과값은 해당 scope를 벗어나면 자동으로 release 된다.


하지만 결과로 받은 값을 다른 곳에 그대로 사용 할 경우 그 값은 release가 되지 않고 반복되면 메모리가 꽉 차서

프로그램이 죽어버리는 결과를 낳게 된다.


결과 값을 사용해야 할 경우에는 그대로 사용하지말고 .data 를 이용하여 값만을 복사하여 사용하자.


메모리 누수 발생 O

feature1 = net(transformed_img1)
feature2 = net(transformed_img2) result = 결과값이용함수(feature1, feature2)


메모리 누수 발생 X

feature1 = net(transformed_img1)
feature2 = net(transformed_img2)
tfeature1 = feature1.data[0]
tfeature2 = feature2.data[0]
result = 결과값이용함수(tfeature1, tfeature2)


저작자표시비영리

'전공관련 > Deep Learning' 카테고리의 다른 글

[Pytorch] tensor의 차원을 바꿔보자  (0) 2019.03.15
[Pytorch] Multi GPU를 활용 해 보자  (2) 2019.03.15
[Pytorch] network 결과물 사용시 주의사항!  (0) 2019.03.13
[Pytorch] torch.load 에서 학습시와 환경이 달라서 못읽을 경우  (0) 2019.03.13
[Pytorch] pretrained-model 의 일부만을 불러와 보자  (0) 2019.03.12
[Pytorch] 학습 한 모델을 저장하고 불러오자  (1) 2019.03.12
블로그 이미지

매직블럭

작은 지식들 그리고 기억 한조각

트랙백 0개, 댓글 0개가 달렸습니다

댓글을 달아 주세요

[Pytorch] torch.load 에서 학습시와 환경이 달라서 못읽을 경우

전공관련/Deep Learning 2019. 3. 13. 13:53




학습은 cuda:2 환경에서 진행한 모델을 다른 pc에서 불러와 cuda:0 환경에서 inference를 시도

device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")

net = Net()
net.to(device)
net.load_state_dict(torch.load("./output/trained_model.pth"))

이러한 경우 torch.load 에서 에러가 발생.

학습 당시의 환경은 cuda:2 인데 그 환경과 다르다는것! 


이럴 경우 map_location 파라미터를 설정 해 주면 정상적으로 읽기 가능

net.load_state_dict(torch.load("./output/0074.pth", map_location='cuda:0'))


저작자표시비영리

'전공관련 > Deep Learning' 카테고리의 다른 글

[Pytorch] Multi GPU를 활용 해 보자  (2) 2019.03.15
[Pytorch] network 결과물 사용시 주의사항!  (0) 2019.03.13
[Pytorch] torch.load 에서 학습시와 환경이 달라서 못읽을 경우  (0) 2019.03.13
[Pytorch] pretrained-model 의 일부만을 불러와 보자  (0) 2019.03.12
[Pytorch] 학습 한 모델을 저장하고 불러오자  (1) 2019.03.12
Deconvolution 파라미터에 따른 출력 크기 계산하기  (0) 2018.10.19
블로그 이미지

매직블럭

작은 지식들 그리고 기억 한조각

트랙백 0개, 댓글 0개가 달렸습니다

댓글을 달아 주세요

  • «
  • 1
  • 2
  • 3
  • 4
  • »

카테고리

  • 살다보니.. (414)
    • 주절거림 (3)
    • 취미생활 (36)
      • 지식과 지혜 (3)
      • 풍경이 되어 (4)
      • Memories (17)
      • 엥겔지수를 높여라 (2)
    • mathematics (6)
      • Matrix Computation (2)
      • RandomProcesses (3)
    • English.. (8)
    • Programming (134)
      • C, C++, MFC (51)
      • C# (1)
      • OpenCV (17)
      • Python (47)
      • Git, Docker (3)
      • Matlab (4)
      • Windows (3)
      • Kinect V2 (2)
      • 기타 etc. (6)
    • 전공관련 (73)
      • Algorithm (6)
      • Deep Learning (49)
      • 실습 프로그램 (4)
      • 주워들은 용어정리 (8)
      • 기타 etc. (6)
    • Computer (104)
      • Utility (21)
      • Windows (24)
      • Ubuntu, Linux (55)
      • NAS (2)
      • Embedded, Mobile (2)
    • IT, Device (41)
      • 제품 사용기, 개봉기 (14)
      • 스마트 체험단 신청 (27)
    • Wish List (3)
    • TISTORY TIP (5)
    • 미분류. 수정중 (1)

태그목록

  • 스마트체험단
  • 칼로리 대폭발
  • random variable
  • Computer Tip
  • ReadString
  • matlab
  • ColorMeRad
  • 후쿠오카
  • CStdioFile
  • Deep Learning
  • 크롬
  • 오봉자싸롱
  • 갤럭시노트3
  • DSLR
  • 매트랩 함수
  • matlab function
  • 포르투갈
  • 딥러닝
  • Convolutional Neural Networks
  • 매트랩
  • function
  • portugal
  • 일본
  • 에누리닷컴
  • LIBSVM
  • 큐슈
  • DeepLearning
  • utility
  • SVM
  • review

달력

«   2022/06   »
일 월 화 수 목 금 토
      1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30    
06-25 10:02

LATEST FROM OUR BLOG

  • 골뱅이 연산자의 의미 (행렬곱)..
  • 프린터 용지 부족 문제를 해⋯.
  • [MXNet] 데이터 리스트를 만⋯.
  • 예쁘게 출력하자 pprint - pr⋯.
  • 작업표시줄 미리보기를 리스⋯.
  • 이미지 실제 파일 포맷 확인하기.
  • 알리 등 해외배송 배송상태를⋯.
  • 티스토리 코드블럭 내용을 복⋯.
  • warning 을 on/off 하자.
  • windows 10 파일 선택, 파일⋯.
RSS 구독하기

BLOG VISITORS

  • Total : 1,130,073
  • Today : 34
  • Yesterday : 378

Copyright © 2015 Socialdev. All Rights Reserved.

티스토리툴바