반응형

Python/PyTorch 공부 70

[PyTorch] Boolean value of Tensor with more than one value is ambiguous

pred와 target값을 loss function에 전달하여 loss를 계산할때 아래와 같은 오류가 발생했다. Boolean value of Tensor with more than one value is ambiguous loss 계산 코드를 잘못 짠게 원인이었다. def mse_loss(pred, target): loss = nn.MSELoss(pred, target) return loss 위 코드를 아래와 같이 수정하니 오류 해결! def mse_loss(pred, target): loss_func = nn.MSELoss() loss = loss_func(pred, target) return loss

[에러 해결] CUDA error: CUBLAS_STATUS_INTERNAL_ERROR when calling `cublasCreate(handle)

pytorch lightning으로 분산학습시에 오류가 발생했다. CUDA error: CUBLAS_STATUS_INTERNAL_ERROR when calling `cublasCreate(handle)` 오류 발생시 해결방법은 pytorch 버전과 cuda 버전을 맞춰줘야 한다 !@ 아래 코드를 입력하면 최신 버전 torch로 업데이트 해준다. 하하하 pip install torch==1.8.0+cu111 torchvision==0.9.0+cu111 torchaudio==0.8.0 -f https://download.pytorch.org/whl/torch_stable.html 출처 https://discuss.pytorch.org/t/cuda-error-cublas-status-internal-error..

[PyTorch] nn.Sequential 을 상속받아 Class 정의하기

안녕하세요, 이번 포스팅에서는 class를 정의하는 경우에 nn.Module이 아닌 nn.Sequential을 상속하여 사용하는 것에 대해 알아보겠습니다. nn.Module 대신에 nn.Sequential을 subclass하면 어떤 이점이 있을까요?? 바로 forward method를 작성하지 않아도 됩니다 ㅎㅎ 예시 코드를 살펴보겠습니다. # Subclassing nn.Sequential to avoid writing the forward method. class FeedFowardBlock(nn.Sequential): def __init__(self, emb_size, expansion=4, drop_p=0.): super().__init__( nn.Linear(emb_size, expansion *..

이미지 분류 신경망의 결과를 t-SNE 시각화하기

안녕하세요ㅎㅎ 이번 포스팅에서는 이미지 분류 task를 목적으로 학습된 신경망의 출력값을 t-SNE으로 시각화 해보겠습니다. 제가 학습한 모델은 STL-10 dataset에서 성능이 36% 밖에 안나오기 때문에, t-SNE 시각화 그림이 명확하지 않습니다. from sklearn.manifold import TSNE import seaborn as sns tsne = TSNE() # t-SNE 시각화 함수 정의 def plot_vecs_n_labels(v, labels, fname): fig = plt.figure(figsize = (10,10)) plt.axis('off') sns.set_style('darkgrid') sns.scatterplot(v[:,0], v[:,1], hue=labels, le..

[PyTorch] ShuffleSplit와 subset 함수를 사용하여 dataset 분할하기

안녕하세요! 이번 포스팅은 sklearn 패키지에서 제공하는 ShuffleSplit과 torch.utils.data의 Subset 함수를 사용하여 데이터셋을 분할하도록 하겠습니다. shufflesplit 함수는 데이터셋 인덱스를 무작위로 사전에 설정한 비율로 분할합니다. 즉, 4:1 로 분할하고 싶은 경우에 무작위 인덱스로 4:1 비율로 분할합니다. subset 함수로 데이터셋을 생성하면 부모 set이 업데이트(transformation)된 경우에 subset도 함께 업데이트 됩니다. 제가 사용하는 데이터셋은 999개의 이미지로 구성됩니다. train 0.8, test 0.2로 분할하겠습니다. # split the data into two groups # trian 0.8, test 0.2 from sk..

[PyTorch] VOC Segmentation 데이터셋 사용하기

안녕하세요, 이번 포스팅에서는 PyTorch에서 제공하는 VOC Segmentation dataset을 사용해보도록 하겠습니다. 우선 transformation을 정의하기 위한 albumentations 모듈을 설치합니다. !pip install -U albumentations 필요한 라이브러리를 import 합니다. from torchvision.datasets import VOCSegmentation from torchvision.transforms.functional import to_tensor, to_pil_image from PIL import Image import torch import numpy as np from skimage.segmentation import mark_boundari..

[PyTorch] Dice coefficient 을 PyTorch로 구현하기

안녕하세요, 이번 포스팅에서는 image segmentation 분야에서 자주 사용되는 metric인 Dice coefficient를 PyTorch로 구현해보겠습니다. 또한 이 dice coefficient를 loss로 활용하는 법도 살펴봅니다. Dice coefficient dice coefficient는 주로 medical image analysis에서 사용됩니다. 그리고 예측값과 gt 사이의 overlap area에 2를 곱하고 예측값과 gt 영역을 합한 것으로 나눠줍니다. 이는 IoU와 매우 유사합니다. Dice를 boolean data(binary segmentation map)에 적용할 때, Dice coefficient는 F1 score와 동일합니다. PyTorch 코드 아래 코드는 pred..

[PyTorch] to_pil_image 명령어로 tensor를 pil image로 변경하기

안녕하세요 ㅎㅎ!! 이번 포스팅에서는 tensor인 데이터를 to_pil_image 명령어로 pil data type으로 변경하는 법을 살펴보겠습니다. 정말 편리하게 사용하고 있는데요, 자꾸 까먹어서 기록합니다 ㅎㅎ !! 임의의 데이터를 갖고 왔는데요, 해당 데이터는 data loader에서 추출하여 tensor 형태의 [C,H,W]로 되어있습니다. # 임의의 데이터를 갖고 오겠습니다. for x, y in train_dl: print(x.shape, y.shape) break img = x[0] target = y[0] print(img.shape, target.shape) print(img.dtype) 위 tensor 데이터를 pil 데이터로 변경하여 손쉽게 시각화 할 수 있는 함수가 to_pil_i..

반응형