[Day12] 최적화

2021. 2. 2. 20:09·AI/부스트 캠프 AI tech

[Day12] 최적화

  • Optimization

    • https://n-brogrammer.tistory.com/69
  • CNN 첫걸음

    • https://n-brogrammer.tistory.com/70

 

 

중요

여러 최적화 방법을 비교시 필요 부분을 정리 합니다.

nn.Linear

import torch.nn as nn

nn.Linear(in_features: int, out_features: int, bias: bool=True)

선형 layer을 만드는데 in_features인자는 input의 features의 개수, out_features 인자는 output의 features개수를 설정한다. 그 다음으로 bias인자는 절편 값을 사용할 것인지에 대한 설정 값이다.

 

 

nn.Sequential

import torch.nn as nn

# nn.Sequential() 사용법
# Example of using Sequential
model = nn.Sequential(
          nn.Conv2d(1,20,5),
          nn.ReLU(),
          nn.Conv2d(20,64,5),
          nn.ReLU()
        )

# Example of using Sequential with OrderedDict
model = nn.Sequential(OrderedDict([
          ('conv1', nn.Conv2d(1,20,5)),
          ('relu1', nn.ReLU()),
          ('conv2', nn.Conv2d(20,64,5)),
          ('relu2', nn.ReLU())
        ]))

해당 함수는 여러 layer을 묶어주는 함수가 된다. layer을 초기화시 직접 입력시 순서대로 입력 가능하고 OrderedDict로 이름과 모델을 같이 입력 해 줄 수 있다.

 

import torch.nn as nn

model = nn.Sequential()
model.add_module(layer_name,layer)

아니면 위와 같이 먼저 객체를 만들고 add_module메서드을 통해서 ('layer_name',layer)을 인자로 넣어주어도 된다.

 

 

optim

최적화 방법은 아래와 같이 설정 할 수 있다.

import torch.optim as optim

optm_sgd = optim.SGD(model_sgd.parameters(),lr=LEARNING_RATE)
optm_momentum = optim.SGD(model_momentum.parameters(),lr=LEARNING_RATE,momentum=0.9)
optm_adam = optim.Adam(model_adam.parameters(),lr=LEARNING_RATE)

sgd 최적화 방법:SGD메서드를 사용하여 lr까지만 지정해 준다.

momentum 최적화 방법: SGD메서드를 사용하여 lr,momentum값을 지정해 준다.

adam 최적화 방법: Adam메서드를 사용하여 lr인자 지정해 준다.

각 방법의 첫번째 인자는 모델의 parameters()를 넣어 줘야한다.

 

 

 

피어세션

이번 피어세션에서는 알고리즘 문제를 풀고 토론하였다.

  • https://www.acmicpc.net/problem/2234

 

from collections import deque
import sys

def tuple_sort(x,y):
    return (min(x,y),max(x,y))

def bfs(i,j):
    q=deque()
    q.appendleft((i,j))
    visit[i][j]=cnt
    ans=1
    while q :
        x,y=q.pop()
        for d,s in zip(dir,bin(castle[x][y])[2:].zfill(4)):
            nx, ny = x + d[0], y + d[1]
            if 0<= nx <m and 0<= ny <n:
                if s=='0':
                    if visit[nx][ny] == 0:
                        q.appendleft((nx, ny))
                        visit[nx][ny]=cnt
                        ans+=1
                elif visit[nx][ny]!=0 and visit[nx][ny]!=cnt :
                    connect.add(tuple_sort(cnt,visit[nx][ny]))
    return ans


n,m=map(int,sys.stdin.readline().split())
visit=[[0]*n for _ in range(m)]
dir=[(1,0),(0,1),(-1,0),(0,-1)] #남, 동, 북, 서
castle=[]
connect=set()
room={}

for _ in range(m):
    castle.append(list(map(int,sys.stdin.readline().split())))

cnt=0
large_room=float('-inf')
remove=float('-inf')

# 가장 큰방과 방의 개수
for i in range(m):
    for j in range(n):
        if visit[i][j]==0:
            cnt+=1
            room[cnt]=bfs(i,j)
            if large_room < room[cnt]:
                large_room=room[cnt]

# 벽 제거하여 가장 넓은 방
for x,y in connect:
    if remove < room[x]+room[y]:
        remove=room[x]+room[y]

print(cnt)
print(large_room)
print(remove)

 

'AI > 부스트 캠프 AI tech' 카테고리의 다른 글

[Day16] NLP 기초  (0) 2021.02.15
[Day15] Generative model  (0) 2021.02.05
[Day14] RNN  (0) 2021.02.04
[Day13] CNN  (0) 2021.02.03
[Day11] 딥러닝 기초  (0) 2021.02.01
[Day10] 시각화/통계학  (0) 2021.01.29
[Day9] Pandas II,확률론  (0) 2021.01.28
[Day8] Pandas I,딥러닝 학습방법 이해하기  (0) 2021.01.27
'AI/부스트 캠프 AI tech' 카테고리의 다른 글
  • [Day14] RNN
  • [Day13] CNN
  • [Day11] 딥러닝 기초
  • [Day10] 시각화/통계학
N-analyst
N-analyst
  • N-analyst
    개발자CuCu
    N-analyst
  • 전체
    오늘
    어제
  • 공지사항

    • 티스토리에서 원하는 글 찾는 방법
    • 분류 전체보기 (140)
      • 티스토리 (4)
      • 알고리즘 (5)
        • 알고리즘 정리 (1)
        • 백준 (4)
      • 마크다운(Typora) (13)
        • 사용법 (13)
      • 에러 (1)
        • 파이썬 (1)
      • 데이터 분석 (5)
        • python_analysis (3)
        • Machine Learning (2)
      • AI (109)
        • 파이토치로 시작하는 딥러닝 기초 (2)
        • 부스트 캠프 AI tech (41)
        • 이론 (66)
      • 파이썬(python) (1)
        • 기타 (1)
      • 웹 프로그래밍 (1)
        • 설정 팁 (1)
  • 블로그 메뉴

    • 홈
    • 태그
  • 인기 글

  • 최근 글

  • 최근 댓글

  • hELLO· Designed By정상우.v4.10.6
N-analyst
[Day12] 최적화
상단으로

티스토리툴바