Data Science

Python

pytorch 이미지 모델링 II

모델 정의 nn.Module 상속 클래스 정의 nn.Module을 상속받는 클래스 정의 __init__(): 모델에서 사용될 모듈과 활성화 함수 등을 정의 forward(): 모델에서 실행되어야 하는 연산을 정의 class Model(nn.Module): def __init__(self,inputs):#초기화 super(Model,self).__init__() self.layer = nn.Linear(inputs,1) self.activation = nn.Sigmoid() def forward(self,x): x = self.layer(x) x = self.activation(x) return x model = Model(1) print(list(model.children())) print(list(mo..

Python

pytorch 이미지 모델링

토치비전(torchvision)은 파이토치에서 제공하는 데이터셋들이 모여있는 패키지 transforms: 전처리할 때 사용하는 메소드 (https://pytorch.org/docs/stable/torchvision/transforms.html) transforms에서 제공하는 클래스 이외는 일반적으로 클래스를 따로 만들어 전처리 단계를 진행 import torch from torch.utils.data import Dataset,DataLoader import torchvision.transforms as transforms from torchvision import datasets DataLoader의 인자로 들어갈 transform을 미리 정의할 수 있고, Compose를 통해 리스트 안에 순서대로 ..

Python

pytorch 기본문법 II

강의 출처: https://www.youtube.com/watch?v=k60oT_8lyFw&list=LL&index=1&t=4103s 텐서의 조작(manipulations) 인덱싱(Indexing): NumPy처럼 인덱싱 형태로 사용가능 x = torch.Tensor([[1,2],#0위치 [3,4]])#1위치 print(x) print(x[0,0]) print(x[0,1]) print(x[1,0]) print(x[1,1]) print(x[:, 0]) print(x[:, 1]) print(x[0:, ]) print(x[1:, ]) tensor([[1., 2.], [3., 4.]]) tensor(1.) tensor(2.) tensor(3.) tensor(4.) tensor([1., 3.]) tensor([2..

Python

pytorch 기본 문법 I

강의 출처: https://www.youtube.com/watch?v=k60oT_8lyFw&list=LL&index=1&t=4103s 파이토치 구성요소 torch.autograd: 자동 미분 기능 torch.nn: 신경망 구축을 위한 데이터 구조나 레이어 등의 라이브러리 torch.multiprocessing: 병렬처리 기능 torch.optim: SGD(Stochastic Gradient Descent)를 중심으로 한 파라미터 최적화 알고리즘 torch.utils: 데이터 조작 등 유틸리티 기능 torch.onnx: ONNX(Open Neural Network Exchange), 서로 다른 프레임워크 간의 모델을 공유 Tensor 텐서 0D tensor : 스칼라, rank 0, shape: ( ) -..

Deep Learning/from scratch II

[밑바닥부터 시작하는 딥러닝 2] - 8장 어텐션 III

어텐션에 관한 남은 이야기 양방향 RNN 양방향 LSTM은 역방향으로 처리하는 LSTM 계층도 추가한다. 각 시각에서는 이 두 LSTM 계층의 은닉 상태를 연결 시킨 벡터를 최종 은닉 상태로 처리한다(연결 외 합(sum), 평균(average) 내는 방법도 있다) 양방향으로 처리함으로써 각 단어에 대응하는 은닉상태 벡터에는 좌와 우 양쪽 방향으로부터의 정보를 집약하여 균형 잡힌 정보가 인코딩 되게 한다. 입력문장을 왼쪽->오른쪽(순방향 LSTM) 과 오른쪽->왼쪽(역방향 LSTM) 각 출력을 연결되게 한다. 출처: https://github.com/oreilly-japan/deep-learning-from-scratch-2/blob/master/common/time_layers.py class TimeB..

Deep Learning/from scratch II

[밑바닥부터 시작하는 딥러닝 2] - 8장 어텐션 II

어텐션을 갖춘 seq2seq 구현 Encoder 구현 앞의 Encoder 클래스는 LSTM의 계층의 마지막 은닉 상태 벡터를 반환한 반면, 모든 은닉 상태를 반환하여 구현한다. # coding: utf-8 import sys sys.path.append('..') from time_layers import * from seq2seq import Encoder, Seq2seq from attention_layer import TimeAttention class AttentionEncoder(Encoder): def forward(self, xs): xs = self.embed.forward(xs) hs = self.lstm.forward(xs) return hs #모든 은닉상태 벡터 def backward..

Deep Learning/from scratch II

[밑바닥부터 시작하는 딥러닝 2] - 8장 어텐션 I

어텐션의 구조 어텐션 메커니즘은 seq2seq를 한 층 더 강력하게 해준다. seq2seq의 문제점 seq2seq에서는 encoder가 시계열 데이터를 인코딩한다. 이때의 출력은 고정 길이 벡터인데, 고정길이는 입력 문장의 길이가 아무리 길어도 항상 같은 길이의 벡터로 변환 한다는 특징이 있다. 이러한 seq2seq의 문제점은 필요한 정보가 벡터에 다 담기지 못하게 된다. Encoder 개선 여태까지 encoder에서 LSTM 계층 마지막 은닉 상태만을 decoder에 전달했다. encoder 출력 길이는 입력문장의 길이에 따라 바꿔주는 것이 개선 포인트이다. 각 단어의 은닉 상태 벡터를 모두 이용하면 입력된 단어와 같은 수의 벡터를 얻을 수 있다. 5개가 입력되었고, encoder는 5개의 벡터를 출력..

Deep Learning/from scratch II

[밑바닥부터 시작하는 딥러닝 2 ] - 7장 RNN을 사용한 문장 생성 II

seq2seq 개선 seq2seq를 개선하기 위한 두가지 방법을 제안한다. 입력데이터 반전(Reverse) 입력데이터의 순서를 반전시킨다 (x_train, t_train), (x_test, t_test) = sequence.load_data('addition.txt') char_to_id, id_to_char = sequence.get_vocab() # Reverse input? ================================================= is_reverse = False # True if is_reverse: x_train, x_test = x_train[:, ::-1], x_test[:, ::-1] x_test[:, ::-1]을 통해 배열의 행을 반전 시킨다. 입력 데이터..

해파리냉채무침
'분류 전체보기' 카테고리의 글 목록 (7 Page)