본문 바로가기

프로그래머/Pytorch

[Pytorch] RNN으로 문장 학습시키기 아래의 문장의 RNN 모델을 통하여 모델링 한다. sentence = ("if you want to build a ship, don't drum up people together to collect wood and don't assign them tasks and work, but rather teach them to long for the endless immensity of the sea.") a. 위의 문장을 이용하여 모델을 학습 시킬 때 10문자씩 잘라서 학습시킨다. b. 학습 완료 후 학습 시 사용했던 입력 데이터를 이용하여 결과물을 출력한다. 전체코드 import torch import torch.nn as nn import torch.optim as optim import nu.. 더보기
ants/bees classification CNN model에서 배울 수 있는 소소한 팁들(python) ants/bees classification CNN model에서 배울 수 있는 소소한 팁들(python) 파일 목록 생성 for i, d in enumerate(dirs): files = os.listdir('./hymenoptera_data/' + d) 이미지 읽어 들이기 img = Image.open('./hymenoptera_data/' + d + '/' + f, 'r') 채널별로 분리해서 [0,1] 구간으로 정규화 r,g,b = resize_img.split() r_resize_img = np.asarray(np.float32(r)/255.0) g_resize_img = np.asarray(np.float32(g)/255.0) b_resi.. 더보기
[pytorch] linear regression class를 nn.Sequential로 간단하게 표현 linear regression class를 nn.Sequential로 간단하게 표현 Linear regression 전체 코드 import torch import torch.nn.functional as F import torch.nn as nn import torch.optim as optim x_data = [[1,2], [2,3], [3,1], [4,3], [5,3], [6,2]] y_data = [[0], [0], [0], [1], [1], [1]] x_train = torch.FloatTensor(x_data) y_train = torch.FloatTensor(y_data) print(x_train.size()) print(y_train.size()) ''' class l.. 더보기
[Pytorch] 기초 강의 day1 Pytorch 기초 정리 torch td = torch.linspace(0,3,4) print(td) print(torch.exp(td)) print(torch.max(td)) print(torch.log(td)) td2 = torch.tensor([[1,2,3],[4,5,7]], dtype=torch.float32) print('\n', torch.max(td2, dim=1)) print('\n', torch.max(td2, dim=1)[0]) print(torch.max(td2, dim=1)[1]) tensor([0., 1., 2., 3.]) tensor([ 1.0000, 2.7183, 7.3891, 20.0855]) tensor(3.) tensor([ -inf, 0.00.. 더보기
[Pytorch] VGG CIFAR-10에 적용 및 정리 VGG CIFAR-10에 적용 및 정리 모두의 딥러닝 시즌2 - Pytorch를 참고 했습니다. 모두의 딥러닝 시즌2 깃헙 import torch import torch.nn as nn import torch.optim as optim import torchvision import torchvision.transforms as transforms device = 'cuda' if torch.cuda.is_available() else 'cpu' torch.manual_seed(123) if device =='cuda': torch.cuda.manual_seed_all(123) transform = transforms.Compose( [transforms.ToTensor(), transforms.Norma.. 더보기
[Pytorch] VGG 구현 및 정리 VGG 구현 및 정리 모두의 딥러닝 시즌2 - Pytorch를 참고 했습니다. 모두의 딥러닝 시즌2 깃헙 import torch.nn as nn class VGG(nn.Module): def __init__(self, features, num_classes=1000, init_weights=True): super(VGG, self).__init__() self.features = features self.avgpool = nn.AdaptiveAvgPool2d(7) self.classifier = nn.Sequential( nn.Linear(512*7*7, 4096), nn.ReLU(True), nn.Dropout(), nn.Linear(4096, 4096), nn.ReLU(True), nn.Dropout.. 더보기
[Pytorch] MNIST 간단한 CNN 구현 및 정리 MNIST 간단한 CNN 구현 및 정리 모두의 딥러닝 시즌2 - Pytorch를 참고 했습니다. 모두의 딥러닝 시즌2 깃헙 import torch import torchvision.datasets as dsets import torchvision.transforms as transforms import torch.nn.init pytorch import device = 'cuda' if torch.cuda.is_available() else 'cpu' torch.manual_seed(777) if device == 'cuda': torch.cuda.manual_seed_all(123) device 설정(GPU or CPU) learning_rate = 0.001 training_epochs = 15 ba.. 더보기
[Pytorch tutorial] Autograd: 자동미분 본 포스팅은 파이토치 튜토리얼 한글판 홈페이지 바탕으로 작성하였습니다. pytorch tutorial - Autograd: 자동 미분 Autograd: 자동 미분 autograd 패키지는 tensor의 모든 연산에 대해 자동 미분을 제공 코드를 어떻게 작성하여 실행하느냐에 따라 역전파 정의됨(학습 과정의 매 단계마다 달라짐) Tensor .requires_grad=True로 설정하면 그 tensor에서 이뤄진 모든 연산들을 추적 계산 완료 후 .backward()를 호출하여 gradient 자동 계산 tensor의 변화도는 .grad 속성에 누적 .detach()를 호출하여 tensor가 기록을 추적하는 것을 방지 with torch.no_grad(): 로 코드 블럭을 감싸 기록 추적(메모리 사용) 방지.. 더보기
[Pytorch tutorial] PyTorch가 무엇인가요? 본 포스팅은 파이토치 튜토리얼 한글판 홈페이지 바탕으로 작성하였습니다. pytorch tutorial - pytorch가 무엇인가요? PyTorch가 무엇인가요? 파이썬 기반의 과학연산 패키지 Numpy를 대체하면서 GPU를 이용한 연산이 필요한 경우 최대한의 유연성과 속도를 제공하는 딥러닝 연구 플랫폼이 필요한 경우 Tensors 초기화 되지 않은 행렬 생성 x = torch.empty(5, 3) 무작위로 초기화된 행렬을 생성 x = torch.rand(5, 3) Returns a tensor filled with random numbers from a uniform distribution on the interval [0,1) 0 이상 1 미만의 수로 균등하게 초기화 dtype이 long이고 0으로 .. 더보기