머신러닝

· 머신러닝
기록용. 1. Model GPU 사용량 체크 print('Memory Usage:') print('Max Alloc:', round(torch.cuda.max_memory_allocated(0)/1024**3, 1), 'GB') print('Allocated:', round(torch.cuda.memory_allocated(0)/1024**3,1), 'GB') # MB 단위 : print(torch.cuda.memory_allocated() / 1024 /1024) print('Cached: ', round(torch.cuda.memory_cached(0)/1024**3,1), 'GB') ⚠️nvidia-smi는 reserved memory를 포함한 값이기 때문에 실제 모델의 GPU 사용량을 보여주는 것..
딥러닝 모델 input이 3channel (RGB)기반 모델인데, Grayscale로 inference/validate을 진행하고 싶을 때는 기존 RGB Load방식에서 아래와 같이 1 channel로 로드하고 동일한 layer를 3겹 쌓아서 넘겨주면 됨. 맨날 함수를 까먹어서 기록용. im = cv2.imread(f, cv2.IMREAD_GRAYSCALE) if len(im.shape)
기존에 적은 게시물의 연장이라 보면 될 것 같다. [PIL] Crop / Clip image by Polygon points. / PIL로 이미지 자르기 # FOR PNG shape import numpy from PIL import Image, ImageDraw # read image as RGB and add alpha (transparency) im = Image.open("crop.jpg").convert("RGBA") # convert to numpy (for convenience) imArray = numpy.asarray(im) # create mask polygon = [(444,203),( yjs-program.tistory.com 일전에 작성한대로 crop을 한 후, 해당 글자 이미지를..
class RawDataset(Dataset): def __init__(self, root): self.rgb = True self.image_path_list = [] for dirpath, dirnames, filenames in os.walk(root, followlinks=True): for name in filenames: _, ext = os.path.splitext(name) ext = ext.lower() if ext == ".jpg" or ext == ".jpeg" or ext == ".png": self.image_path_list.append(os.path.join(dirpath, name)) self.image_path_list = natsorted(self.image_path_li..
(tensor == target_value).nonzero(as_tuple=True) https://stackoverflow.com/questions/47863001/how-pytorch-tensor-get-the-index-of-specific-value How Pytorch Tensor get the index of specific value With python lists, we can do: a = [1, 2, 3] assert a.index(2) == 1 How can a pytorch tensor find the .index() directly? stackoverflow.com
1. Dataloader shuffle=False일 때, dataset = torchvision.datasets.ImageFolder(, transforms=) dataloader = torch.utils.data.DataLoader(dataset, batch_size=, shuffle=False) # 이미 기존 DataLoader에서 shuffle을 사용하지 않을 경우, "dataloader.dataset.samples"안에 # (파일경로, 라벨) 튜플로 이루어진 list형태로 저장되어 있다. allFiles, _ = map(list, zip(*dataloader.dataset.samples)) for i, (inputs, labels) in enumerate(dataloader): inputs = i..
def strike(draw, img, font, text): # Get the image, and calculate the average of font thickness. twidth, theight = img.size lx, ly = twidth, theight/2 thickness = 2 if twidth >200 or theight > 200 else 1 draw.line((0, ly, lx, ly), fill="black", width=thickness) # [0, height/2] ~ [width, height/2] # "*"처럼 위로 올려붙는 특수 문자의 경우, font의 getmask함수로 영역을 잡아줘야 함. def special_strike(draw, img, font, text): t..
https://stackoverflow.com/questions/43060479/how-to-get-the-font-pixel-height-using-pils-imagefont-class How to get the font pixel height using PIL's ImageFont class? I am using PIL' ImageFont module to load fonts to generate text images. I want the text to tightly bound to the edge, however, when using the ImageFont to get the font height, It seems that it incl... stackoverflow.com Font Loading..
64의 배수로 input size를 조정해주면 된다. 내가 많이 쓰는 input size는 640 .... , 1024, 1600... 등이 있다. https://github.com/CompVis/stable-diffusion/issues/301
matplotlib plt.subplots warning 삭제 for문과 matplotlib를 사용해서 이미지를 그릴 때, 다음과 같은 warning이 나오는 경우가 있다. RuntimeWarning: More than 20 figures have been opened. Figures created through the pyplot interface (`matplotlib.pyplot.figure`) are retained until explicitly closed and may consume too much memory. (To control this warning, see the rcParam `figure.max_open_warning`). 이럴때는 내가 열어준 fig를 close()해주지 않아서 ..
https://matplotlib.org/stable/gallery/shapes_and_collections/hatch_style_reference.html Hatch style reference — Matplotlib 3.7.1 documentation Note Click here to download the full example code Hatch style reference Hatches can be added to most polygons in Matplotlib, including bar, fill_between, contourf, and children of Polygon. They are currently supported in the PS, PDF, SVG, OSX, and Agg bac..
이미 예전부터 많은 사람들이 쓰고 있는 LR 스케줄러로, 통상적으로 이런 포맷을 만들 수 있다는 점에서 큰 장점을 가진다. Pytorch에 공식으로 구현된 CosineAnnealingWarmRestart는 Warmup start가 구현되어 있지 않고 lr 최댓값이 감소하는 방안에 대해서 구현되어 있지 않다고 한다. 아래 블로그 링크를 참고하면 친절하신 어느 개발자께서 구현해주신 Custom Cosine AnnealingWarmupRestart를 많이 사용하곤 하는데, 나는 이상하게 저분 코드만 사용하면 기대하는 모습의 lr_scheduler가 나오지 않는다. 더보기 (optimzer의 초기 lr을 0로 두고 진행하는데도, 이상하게 아래 이미지 초록색 라인처럼 자꾸 lr이 위로 올라감.) https://g..
· 머신러닝
https://github.com/open-mmlab/mmdetection/issues/2739#issuecomment-631196300 Loss becomes NAN after a few iterations · Issue #2739 · open-mmlab/mmdetection I am training a bespoke dataset using the default Mask RCNN parameterisation (see parameters below). I have converted my bespoke dataset to COCO format, with the annotations in JSON files (polygons... github.com TO DO LIST check if the datase..
import torch from tqdm.notebook import tqdm import glob from PIL import Image from torchvision.transforms import ToTensor target_path = "./images/*" img_lst = glob.glob(target_path) totensor = ToTensor() img_val_lst = [] for img in tqdm(img_lst): img_RGB = Image.open(img).convert("RGB") img_val = totensor(img_RGB) img_val_lst.append(img_val) mean = torch.zeros(3) std = torch.zeros(3) print('==> ..
https://pypi.org/project/polygon-pascalvoc-writer/ polygon-pascalvoc-writer For generating Pascal VOC XML image annotation files pypi.org 응용 코드 import glob from tqdm import tqdm import os import json import xmltodict import cv2 import codecs import numpy as np from shutil import copyfile from polygon_pascalvoc_writer import VocWriter CLASS_label = ['CLASS_A', 'CLASS_B', ...] #https://blog.actors..
Js.Y
'머신러닝' 카테고리의 글 목록