반응형

분류 전체보기 823

폴리곤을 segmentation mask로 변환하기(Polygon to mask)

폴리곤 좌표로 표현되어 있는 mask를 binary mask로 변환하는 방법을 알아보겠다. 구글링 해보니 잘 안나와서 한번 작성해본다. 여러 자료를 찾아봤는데 skimage.draw.polygon2mask 가 제일 편한것 같다. from skimage.draw import polygon2mask 로 함수를 불러와서 image_shape와 np.array 타입의 polygon을 넣어주면 된다. https://scikit-image.org/docs/stable/api/skimage.draw.html#skimage.draw.polygon2mask Module: draw — skimage v0.19.2 docs The range of values to sample pixel values from. For gra..

segmentation mask 덩어리 갯수 확인하기

위 그림은 mask가 두 덩어리로 이루어 있습니다. 이 케이스를 파악하는 코드를 짜보았는뎅 공유합니다. def count_contours(masks, threshold=1000): if type(masks[0]) == torch.Tensor: masks = [mask.cpu().numpy() for mask in masks] counts = [] for mask in masks: count = 0 contours, _ = cv2.findContours(mask.astype(np.uint8), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE) for contour in contours: area = cv2.contourArea(contour) if area >= threshold:..

Segmentation mask의 center point 계산하기

Segmentation mask의 center point를 얻어오는게 필요해서 코드를 짜 보았습니다. mask는 0 또는 1의 값을 갖고 있으므로 numpy 혹은 pytorch의 nonzero 함수를 사용사용하면 됩니다. coordinates = np.nonzero(mask) x_coordinates = coordinates[0] y_coordinates = coordinates[1] x_min, x_max, y_min, y_max = np.min(x_coordinates), np.max(x_coordinates), np.min(y_coordinates), np.max(y_coordinates) x_center, y_center = (x_max + x_min) / 2, (y_max + y_min) / 2..

Self-supervised Learning에 대하여

심심해서 적어보는 글. Self-supervised learning은 데이터가 부족한 환경에서 사용하는 것이 아니라, 데이터는 많은데 annotation이 없는 경우에 사용하는 것이다. unlabeled data 로부터 어떻게 pretask를 만들어서 효율적인 representation을 뽑아내느냐가 중요하며, 작년 까지 핫했던 SSL 모델들(DINO, MoCO, SimCL?)은 unlabeled data에 aumentation에 강하게 줘서 contrastive learning으로 augmentation에 불변한 representation을 뽑아내는 방향으로 발전해왔다. 22년 SSL 논문은 안읽어봐서 모르겠는데 현재도 비슷한 방향으로 연구가 진행되고 있지 않을까 싶다. 또한 SSL방법론이 성능을 내기..

[PyTorch] CLIP의 text encoder에는 attention mask가 존재합니다.

CLIP의 text encoder 내부의 Multi_head_attention에서 attention mask가 None으로 입력되는 줄 알았다. 아이디어를 구현하기 위해 attention mask 부분을 만들어서 넣어줬더니.. 성능이 엄청 떨어졌다. 한번 확인해보니 CLIP의 text encoder에서 attention mask가 None으로 입력되는 것이 아니라 다음과 같이 들어간다. 근데 어떤 layer에서는 None으로 들어가기 때문에 구체적으로 확인해볼 필요는 있다. 항상 저렇게 attention mask가 들어가는게 아니다. BERT 구조임에도 autoregressive하게 문장을 보게 하려는 의도 인듯?

[PyTorch] Multi_head_attention에서 target sequence length와 source sequence length 의미

Multi_head_attention에서 target sequence length와 source sequence length 의미 연구를 위해 pytorch의 multi head attention에 attention mask를 씌워줘야 했다. 도큐먼트를 보면 L은 target sequence length를 의미하고 S는 source sequence length를 말하는데, 이 둘은 무엇일까? pytorch 내부 코드를 뜯어보니 target sequence length는 query의 길이를 의미한다. soure sequence length는 key의 길이를 의미함. 구글링해도 관련 내용을 찾기 어려워서 작성해본당. 나만 모르고 다 아는 내용이라서 구글링해도 못찾았던 거일수도?

[PyTorch] Tensor.retain_grad()

a.reatain_grad()를 통해 gradient가 사라지는 것을 예방할 수 있다. 계산그래프에서 leaf node가 아닌 tensor의 gradient는 계산 후 날라가는데, retain_grad를 통해 날라가지 않고 붙잡을 수 있다. https://blog.paperspace.com/pytorch-hooks-gradient-clipping-debugging/ Debugging and Visualisation in PyTorch using Hooks In this post, we cover debugging and Visualisation in PyTorch. We go over PyTorch hooks and how to use them to debug our backpass, visualise ..

[PyTorch] register_hook을 사용하여 Transformer 내부의 Attention matrix(Torch.Tensor)의 gradient 받아오기

register_hook을 사용하여 Transformer 내부의 Attention matrix(Torch.Tensor)의 gradient 받아오기 모델의 파라미터에 대한 grad가 아닌, Tensor object에 대한 grad는 계산만하고 날라가버린다. 즉, loss.backward()를 통해 backpropagation을 진행하면 중간 연산에 필요한 Tensor 변수의 gradient는 .grad로 저장이 안되고 계산이 끝나면 날라간다는 말이다. 따라서 Tensor object에 register_hook 함수로 gradient를 한번 붙잡아야 한다. 붙잡는다는 말은 gradient가 계산되었을 때, 날라가도록 두는게 아니라 다른 변수에 저장해야 한다는 말이다. 나는 중간 연산의 Tensor objec..

[Pytorch] Sementation mask 시각화 하기

이미지를 segmentation 모델로 전달하여 pred를 얻었다고 가정하겠습니다. for image, target in data_loader: pred_masks = model(image) # [N, H, W], dtype= Tensor.bool 이 pred_masks를 matplotlib를 사용하여 시각화 하겠습니다. 우선, pred_masks, target, image를 동일한 사이즈로 resize 해줘야 합니다. 안되어있는 경우 resize 합니다. import torchvision.transforms.functional as TF h, w = image.shape[2], image.shape[3] pred_masks = TF.resize(pred_masks, (h, w)).type(torch.b..

파이참에서 원격 주피터 노트북 사용하기

파이참으로 원격 서버의 interpreter를 사용하여 주피터 노트북 사용하는 방법을 알아보겠습니다. 우선 local에 ipynb 파일을 생성합니다. ipynb 파일을 실행하면 상단에 interpreter를 설정할 수 있는 옵션이 있습니다. 다음 옵션으로 interpreter를 설정하면 Jupyter server process failed to start Illegal char :> at index 4 에러가 발생합니다. configured server 로 설정을 해줘야 하는데요. 원격 서버에서 jupyter notebook을 실행 후 생성된 주소와 토큰을 configured server에 입력해주면 됩니다. 127.0.0.1 부분을 원격 서버의 ip로 설정해주어야 합니다.

반응형