DEV Community

4rldur0
4rldur0

Posted on

댑덥딥 1주차 정리

'모두를 위한 딥러닝 시즌 2' 강의를 듣고 공부하는 스터디 입니다. https://deeplearningzerotoall.github.io/season2/lec_tensorflow.html


비대면 5 April, 2023

Lab-01-1

basic tensor manipulation

vector(1d)-matrix(2)-tensor(3)

pytorch tensor shape convention

-matrix 크기
2d(typical simple setting)
: |t| = (batch size, dim)으로 표현
3d(typical computer vision)
: |t| = (batch size, width, height)
3d(typical natural language processing)
: |t| = (batch size, length, dim)
: dim x length가 하나의 문장

numpy와 pytorch

##numpy
t = np.array([0., 1., ...,])
t.ndim      //rank
t.shape      //shape
t[:2]      //slicing

##pytorch
t = torch.FloatTensor([0., 1., ...,])
t.ndim()      //rank
t.shape()      //shape
t.size()      //shape
t[:2]      //slicing

t.mean()      //평균
t.mean(dim=0)      //dim=0끼리 평균
t.sum()       //
t.sum(dim=-1)      //dim=-1끼리 
t.max()      //최대
t.max(dim=1)      //dim=1  최대, argument(index)값을 같이 리턴함
Enter fullscreen mode Exit fullscreen mode

broadcasting

  • 행렬끼리 연산을 수행할 때 크기를 맞춰야 함→ broadcasting 기능을 통해 자동으로 크기가 맞춰짐
  • 자동으로 적용되므로 주의해야 함
#broadcasting
//vector + scalar
m1 = torch.FloatTensor([[1, 2]])      //(1,2)
m2 = torch.FloatTensor([3])      //(1, )->(1,2)
m1+m2

//2X 1 vector + 1X 2 vector
m1 = torch.FloatTensor([[1, 2]])      //(1,2)->(2,2)
m2 = torch.FloatTensor([3],[4])      //(2,1)->(2,2)

Enter fullscreen mode Exit fullscreen mode

Lab-01-2

view(numpy의 reshape)⭐

  • -1은 보통 가장 변동이 심한 batch size에

squeez

  • 어떤 한 dimension의 element가 1일 때, 그 dimension을 없앰
  • dimension을 명시할 수도 있음

unsqueeze

  • 원하는 dimension에 1을 넣어줌
  • dimension 명시해야 함
  • view로 동일한 결과 얻을 수 있음
#view
//|t| = (2,2,3)
t.view([-1,3])      //첫번째 차원 정하지x, 두번째 차원 3으로/(2,2,3)->(2x2, 3)->(4,3)
#squeeze
//|ft| = (3,1)
ft.squeeze()      //(3,1)->(3)
ft.squeeze(dim=0)      //변화 없음
#unsqueeze
ft.unsqueeze(0)      //(3)->(1,3)
Enter fullscreen mode Exit fullscreen mode

type casting

lt = torch.LongTensor([1,2,3,4])      //[1,2,3,4]
lt.float      //[1., 2., 3., 4.]
bt = torch.ByteTensor([True, False, False, True])
bt.long      //[1,0,0,1]  
bt.float      //[1., 0., 0., 1.]
Enter fullscreen mode Exit fullscreen mode

concatenate(이어붙이기)

x = torch.FloatTensor([[1,2], [3,4]])
x = torch.FloatTensor([[5,6], [7,8]])
torch.cat([x,y], dim=0)      //(2,2)+(2,2)->(4,2)
torch.cat([x,y], dim=1)      //(2,2)+(2,2)->(2,4)
Enter fullscreen mode Exit fullscreen mode

stacking(concatenate를 간편화시킨 것)

  • unsqueeze한 리스트로 cat하여 똑같은 결과 낼 수 있음
//|x|, |y|, |z| = (2, )
torch.stack([x, y,z])      //(2,)+(2,)+(2,)->(3,2)
torch.stack([x, y,z], dim=1)      //(2,)+(2,)+(2,)->(2,3)
Enter fullscreen mode Exit fullscreen mode

ones and zeros

  • 똑같은 shape의 1로 채운/0으로 채운 tensor를 만듦
  • device 같음
//|x|=(3,2)
torch.ones_like(x)
torch.zeros_like(x)
Enter fullscreen mode Exit fullscreen mode

in-place operation

  • ‘_’
  • 메모리를 새로 선언하지 않고 결과값을 리스트에 반영함
  • garbage collector가 잘 되어 있으므로 큰 차이 없음
x.mul(2.)
x.mul_(2.)
Enter fullscreen mode Exit fullscreen mode

Lab-02, Lab-03

#data definition
x_train = torch.FloatTensor([])      //입력
y_train = torch.FloatTensor([])      //출력

#hypothesis

//hypothesis function: y=Wx+b: 학습 데이터와 가장  맞는 하나의 직선
//w, b 0으로 초기화
W = torch.zeros(1, requires_grad=True)
b = torch.zeros(1, requires_grad=True)

hypothesis = x_train * W +b

#compute loss

//MSE활용

cost = torch.mean((hyphthesis - y_train)**2)      //predict-target

#gradient descent
//b가 없는 모델이라고 가정(w=1  가장 좋은 모델(cost=0))
//gradient descent: W= w-lr*gradW
gradient = 2* torch.mean((@*x_train-y_trina)*x_train)
lr = 0.1
W -= lr * gradient

//torch.optim으로 gradient descent를 간편하게 구현
optimizer = optim.SGD([W], lr=0.15)

//cost로 H(x)개선
optimizer.zero_grad()      //gradient0으로 초기화
cost.backward()      //gradient 계산
optimizer.step      //gradient descent
Enter fullscreen mode Exit fullscreen mode

-이를 여러 번의 iteration을 돌려 cost=0에 가까워지도록 함


대면 8 April, 2023

gradient descent and linear regression

Image of Datadog

The Future of AI, LLMs, and Observability on Google Cloud

Datadog sat down with Google’s Director of AI to discuss the current and future states of AI, ML, and LLMs on Google Cloud. Discover 7 key insights for technical leaders, covering everything from upskilling teams to observability best practices

Learn More

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay