[PyTorch] 모델 저장/불러오기 및 모델 수정하기
·
연구 Research/인공지능 Artificial Intelligent
빠른 학습을 위하여 이미 학습된 파라미터를 가지고 오고 싶을 때가 있다. 그래서 이 글에서는 기본적인 모델 저장, 불어오기 뿐 아니라 내가 좀 더 커스터마이징 할 수 있는 방법에 대해서 고민했다. 1. 모델 저장 파이토치 매뉴얼에서는 다음과 같이 모델을 저장하라고 권한다. PATH = '(모델이름).pth' torch.save(modelA.state_dict(), PATH) 이렇게 해서 pth 파일을 저장할 수 있다. state_dict는 내부 상태 사전(internal state dictionary)으로서 학습된 모델의 매개변수를 저장한다. modelA.state_dict()를 출력하면 다음과 같은 형태가 나온다. 위의 OrderedDict는 dictionary 자료형인데 파이썬에서 순서 정렬에 유리하..
[Pytorch] multi-output일 때 input gradient 구하기
·
프로그래밍 Programming/파이썬 Python
output에 대한 input의 gradient를 구하는 방법은 여러가지인데 input tensor에 대해 requires_grad는 반드시 True로 지정해야 한다. 그래야 gradient 추적이 가능하다. 그 다음에는 두 가지 방법으로 나뉜다. 1. backward()를 이용하고 (input tensor).grad를 통해 가져오는 방법 2. torch.autograd.grad를 이용해서 직접 계산하는 방법 1번이 전형적으로 gradient를 구하는 방법이지만 나는 얻어낸 gradient에 대하여 graph를 연장해야했다. 그러려면 1번 방법으로는 충분하지 않다. 그래서 2번을 해야하는데 multioutput일 때는 gradient에 대한 이해도가 좀 더 요구되는 편이다. 1번 방법. backward(..
[JupyterLab] 코드 줄 번호 default 표시, 폰트 사이즈, family 변경
·
프로그래밍 Programming
이번에 Jupyter notebook에서 Jupyter Lab으로 넘어왔다. Jupyter Lab이 좀 더 편하다고 주변 친구가 말해주기도 했고 다른 환경에서도 써보고 싶어서였다. 아쉬운 점이 있다면 theme 종류의 부족이다. Jupyter lab에서 제공해주는 theme가 dark와 light 밖에 없어서 custom으로 바꾸고 싶으면 css를 따로 바꿔줘야 할 것 같다. 기본적인 font와 size라도 바꿔야겠다 싶어서 쓰는 글이다. 1. settings으로 들어가기 상단에 있는 Settings를 누르면 [advanced setting editors]로 들어간다. 2. Settings의 좌측의 Notebook 클릭 이렇게 하면 아래처럼 show line numbers가 있다 위의 그림에 표시한 것처..
[에러기록] RuntimeError: Expected a 'cuda' device type for generator but found 'cpu'
·
프로그래밍 Programming
이 에러는 pytorch에서 dataloader를 쓸 때 발생할 수 있는 에러이다. RuntimeError: Expected a 'cuda' device type for generator but found 'cpu' dataloader는 클래스라서 내부를 뜯어보지 않는 이상 잘 모르지만 나는 항상 텐서를 torch.cuda.FloatTensor 또는 torch.cuda.DoubleTensor로 쓴다. torch.set_default_tensor_type(torch.cuda.FloatTensor) 그런데 이렇게 하더라도 데이터로더 상에서는 cpu 텐서를 내뱉는다. 그래서 dataloader 코드를 바꿔줘야 한다. dtype = torch.float device = torch.device("cuda") tr..
[에러기록] Pytorch 모델 weight가 업데이트되는지 확인
·
프로그래밍 Programming
Pytorch 모델을 업데이트하려고 optimizer를 쓰는데 loss가 전혀 변하지 않는 것을 보고 업데이트 된 것인지 확인하고 싶었다. 다음 코드와 같이 일치하지 않는 부분이 있는지 확인하였다. optimizer.zero_grad() a = list(model.parameters())[0] print(list(model.parameters())[0].grad) # gradient가 잘 계산되었는지 확인, None이면 이상한 것 loss.backward() optimizer.step() b = list(model.parameters())[0] print(torch.equal(a.data, b.data)) # a와 b가 일치하는지 확인 업데이트 전 후의 parameter 값을 비교함으로써 업데이트되는지 ..
[에러기록] oserror: [winerror 182] 운영 체제가 %1을(를) 실행할 수 없습니다. Error loading "\lib\site-packages\torch\lib\shm.dll" or one of its dependencies
·
프로그래밍 Programming
이 에러 때문에 얼마나 고생했는지 모르겠다. 분명 다른 사람들도 에러가 있다고 말했고 해결 방법들을 봤는데 근본적인 해결책은 아닌 듯 했다. 다음과 같이 에러가 떴다. oserror: [winerror 182] 운영 체제가 %1을(를) 실행할 수 없습니다. Error loading "(경로)\lib\site-packages\torch\lib\shm.dll" or one of its dependencies 분명 처음 설치할 때는 잘만 돌아가더니 왜 갑자기 이러나 싶었다. 다른 사람들이 제시한 방법으로는 1. 아나콘다를 다시 깔아라 2. 아나콘다를 업데이트해라 3. 파이토치를 다운그레이드 or 다시 설치해라 가 있었다. 시도1) 일단 아나콘다를 지우기 싫어서 아나콘다를 업데이트했는데 실패 시도2) dll을 ..
[에러기록] 아나콘다와 관련된 수많은 에러들
·
프로그래밍 Programming
아나콘다를 쓰다보면 정말 많은 오류를 접하게 된다. 이 경우에 검색해서 방법을 찾기는 하지만 기본적으로 남들이 자주 겪는 에러는 아나콘다에서 다 설명한 경우가 많았다. https://docs.anaconda.com/anaconda/user-guide/troubleshooting/ Troubleshooting — Anaconda documentation Troubleshooting If you have a troubleshooting issue that is not listed here, obtain free support for Anaconda through the Nucleus community. For Anaconda installation or technical support options, vis..
[에러기록] matplotlib에서 figure만 그려지고 plot이 없는 경우
·
프로그래밍 Programming/파이썬 Python
matplotlib을 쓰다가 갑자기 figure는 그려지는데 plot은 없는 상황이 있었다. 다른 코드를 돌릴 때는 문제가 없어서 찾아보았다. 결론적으로는 matplotlib의 문제가 아니었고 data_x와 data_y가 shape이 (1,N)인 2차원 numpy array였는데 matplotlib에서는 이를 자동으로 squeeze하지 않고 그래프를 그려서 그런 것이었다. 따라서 np.squeeze(data_x)와 같이 차원을 1차원으로 바꿔주면 해결되었다. 라이브러리 문제 자체가 아닌 데이터의 문제였다.
[MATLAB] MATLAB 테마 바꾸는 방법
·
프로그래밍 Programming/매트랩 MATLAB
MATLAB 테마 바꾸는 방법은 2가지가 있다. 1. matlab-schemer 사용 아래의 github에서 code를 다운받아 사용하는 방법이 있다. https://github.com/scottclowe/matlab-schemer GitHub - scottclowe/matlab-schemer: Apply and save color schemes in MATLAB with ease. Apply and save color schemes in MATLAB with ease. Contribute to scottclowe/matlab-schemer development by creating an account on GitHub. github.com 여기에서 Download ZIP으로 다운받는다. 압축을 풀면 다..
[에러기록] CondaHTTPError: HTTP 000 CONNECTION FAILED for url
·
프로그래밍 Programming
다음과 같은 에러가 떴을 때가 있었다. Downloading and Extracting Packages CondaHTTPError: HTTP 000 CONNECTION FAILED for url https://conda.anaconda.org/pytorch/win-64/pytorch-1.12.1-py3.9_cuda11.6_cudnn8_0.tar.bz2> Elapsed: - An HTTP error occurred when trying to retrieve this URL. HTTP errors are often intermittent, and a simple retry will get you on your way. 검색해보면 많은 trouble shooting이 있는데 한 번에 해결되었다. conda c..