분석 Python(343)
-
[Pytorch] Error : Leaf variable has been moved into the graph interior 해결 방법 공유
torch에서 loss.backward()를 할 때 다음과 같은 에러를 경험을 했다 특정값에 inplace를 하게 되면 다음과 같은 에러가 생긴다. 필자는 아래와 같은 것이 loss에 들어가 있었다. ## 1 array[array==1] = 0.0 ## 2 array[idx] = logit 그래서 필자는 다음과 같이 여러개의 글을 보고 수정했다. 하나는 새로운 객체로 만드는 것이다 애는 단순히 개수를 세주는 역할이라서 해결됐다. array[array==1.0] = 1 count = array.sum() 두 번째는 torch.cat을 사용했다. (불확실!) 사용하지 않는 것과 사용하는 것들을 모아서 새로운 tensor를 만드니 작동했다. 물론 근데 update는 된 거지만 실제로 반영됐지는 아직 필요하다 ..
2021.01.16 -
[Python] Icecream 패키지를 사용하여 디버깅하기
파이썬 코딩을 하다 보면, 모르는 부분에 디버깅 툴이 없다면, print를 해서 찾는 경우가 많다. 필자도 print로 하나하나 하는 습관이 많이 있었지만, 실수가 있기 때문에 디버깅에 어려움을 느낀다. 그래서 어쩌다 찾게된 패키지가 icecream이다. 해당 패키지를 사용하게 되면 디버깅 시에는 프린트가 되게 하고, 안될 때에는 전부 다 안되게 할 수 있는 설정이 있다. 아래와 같이 debug시에는 사용하는 모드와 비사용모드를 선택할 수 있기 때문에 항상 프린트를 하고 지우지 않아도 프린트가 안된다라는 장점이 있다. from icecream import ic ic(1) ic.disable() ic(2) ic.enable() ic(3) # ic| 1: 1 # ic| 3: 3 뿐만 아니라 custom pr..
2021.01.16 -
[Python] itertools
Chain list들을 연결해줄 때 쓸 수 있다. list를 더할 때 + 와 같은 역할을 해준다. import itertools letters = ['a', 'b', 'c', 'd', 'e', 'f'] booleans = [1, 0, 1, 0, 0, 1] decimals = [0.1, 0.7, 0.4, 0.4, 0.5] print(list(itertools.chain(letters, booleans, decimals))) print(letters + booleans + decimals) # ['a', 'b', 'c', 'd', 'e', 'f', 1, 0, 1, 0, 0, 1, 0.1, 0.7, 0.4, 0.4, 0.5] # ['a', 'b', 'c', 'd', 'e', 'f', 1, 0, 1, 0, 0,..
2021.01.01 -
[Python] 적절한 샘플 사이즈를 찾아주는 코드
모집단이 클 경우에는 샘플링을 통해 시각화를 위해서나 통계치를 뽑아줘야 할 것이다. 이때 가장 적절한 샘플사이즈를 알려주는 코드가 있어서 공유한다. 그리고 각각에 대해서 분포별로 실험을 진행해봤다. def sampleSize( population_size, margin_error=.05, confidence_level=.99, sigma=1/2 ): """ Calculate the minimal sample size to use to achieve a certain margin of error and confidence level for a sample estimate of the population mean. Inputs ------- population_size: integer Total size o..
2021.01.01 -
[Jupyter] GPU 사용량 주기적으로 체크하는 코드
import GPUtil from threading import Thread import time class Monitor(Thread): def __init__(self, delay): super(Monitor, self).__init__() self.stopped = False self.delay = delay # Time between calls to GPUtil self.start() def run(self): while not self.stopped: GPUtil.showUtilization() time.sleep(self.delay) def stop(self): self.stopped = True monitor = Monitor(10) 멈추는 것은 STOP을 해주면 됨 monitor.stop()
2021.01.01 -
[Pandas] Code to reduce memory
def mem_usage(pandas_obj): if isinstance(pandas_obj,pd.DataFrame): usage_b = pandas_obj.memory_usage(deep=True).sum() else: # we assume if not a df it's a series usage_b = pandas_obj.memory_usage(deep=True) usage_mb = usage_b / 1024 ** 2 # convert bytes to megabytes return "{:03.2f} MB".format(usage_mb) def type_memory(data) : for dtype in ['float','int','object']: selected_dtype = data.select_d..
2021.01.01 -
[Python] Wordcloud Example
pip install wordcloud 폰트 다운로드하는 곳 https://creativestudio.kr/1734 코드 import jpype import base64 import numpy as np import pandas as pd from PIL import Image from pprint import pprint from matplotlib import font_manager, rc from wordcloud import ImageColorGenerator, WordCloud word = ["Statistics" , "Analysis" , "DATA" , "GAN", "R", "Python" , "SQL" , "tensorflow" , "ML" , "DL" , "Classification" ,..
2020.12.31 -
[Visualization] Learning Curve를 이용하여 시각화하기(Train/Valid)
def plot_learning_curve(estimator, title, X, y, ylim=None, cv=None, n_jobs=1, train_sizes=np.linspace(.1, 1.0, 5)): plt.figure() plt.title(title) if ylim is not None: plt.ylim(*ylim) plt.xlabel("Training examples") plt.ylabel("Score") train_sizes, train_scores, test_scores = learning_curve( estimator, X, y, cv=cv, n_jobs=n_jobs, train_sizes=train_sizes) train_scores_mean = np.mean(train_scores, ..
2020.12.18 -
[TIP] Class에 사전(dict)으로 property 추가하는 법
아래 코드는 특정 값들을 바로 propert에 추가하는 코드다 kwargs에 config라는 것이 들어오면, 각각의 값들을 다 property를 해준다. import numpy as np def assign_config(self, kwargs): for key, value in kwargs.items(): setattr(self, key, value) if hasattr(self, 'config'): # print(self.env_config) for key, value in self.config.items(): # Check types based on default settings if hasattr(self, key): if type(getattr(self,key)) == np.ndarray: set..
2020.12.18 -
[Pytorch] How to Apply the Weight Initialization (Code)
def weights_init(m): classname = m.__class__.__name__ if classname.find("Conv") != -1: nn.init.normal_(m.weight.data, 0.0, 0.02) elif classname.find("BatchNorm") != -1: nn.init.normal_(m.weight.data, 1.0, 0.02) nn.init.constant_(m.bias.data, 0) netD.apply(weights_init) docs.ray.io/en/master/tune/tutorials/tune-advanced-tutorial.html Guide to Population Based Training (PBT) — Ray v1.2.0.dev0 PBT ..
2020.12.17 -
[Pandas] Pandas의 Filter 함수를 사용하여 특정 컬럼(변수) 제외하기
row / test / key가 column 이름에 들어간 것들은 제외하는 regular expression data를 아래와 같이 생성 np.random.seed(1234) cols = [f"{random()}_{i}" for i in np.arange(20)] array = np.random.normal(size=(100,20)) data = pd.DataFrame(array , columns = cols) data ['col_0', 'col_1', 'test_2', 'row_3', 'type_4', 'type_5', 'type_6', 'row_7', 'col_8', 'row_9', 'col_10', 'row_11', 'test_12', 'test_13', 'col_14', 'test_15', 'ty..
2020.12.15 -
[Pytorch] torch 유용한 함수 정리하기
유용한 함수들을 발견하게 되면 정리해보기 개인적으로 중요하다고 생각하는 것에 ★ 표시 import torch import numpy as np Function 1 — torch.tensor t1 = torch.tensor([[21,39],[31,30],[23,43],[11,46],[26,46],[31,25],[21,38],[22,39],[22,19],[18, 14]]) t1 t2 = torch.tensor([]) t2 t2.size() Function 2 — torch.from_numpy a1 = np.array([[1,2,3],[4,5,6]]) a1.dtype t1 = torch.from_numpy(a1) t1.dtype Hight_Weight = np.array([[161,67],[154,76],[1..
2020.11.30