1015 SeSAC(새싹) 3기 32일차

육은별·2021년 10월 15일
0

SeSAC(새싹)

목록 보기
25/31
post-thumbnail
import torch

//tensor = 3차원
x_train = torch.FloatTensor([[30],[60],[90]]) //학습데이터 x
y_train = torch.FloatTensor([[700],[750],[800]]) //학습데이터 y
W = torch.zeros(1) //zeros -> n차원의 tensor를 만드는것, 1을 넣으면 1차원 -> 학습데이터가 행렬이기 때문에 계산을 위해 행렬로 
b = torch.zeros(1) //b는 항상 하나

lr = 0.0002

epochs = 400000

len_x = len(x_train) //3행이라서 3을 반환

for epoch in range(epochs):
  hypothesis = x_train * W + b //h(x) = wx + b 행렬을 썼기때문에 한줄로 처리
  cost = torch.mean((hypothesis -y_train)**2) //mean = 평균을 낸다.

  gradient_w = torch.sum((W*x_train - y_train +b)*x_train)/ len_x
  //cost함수를 w에 대해서 편미분을 때린 것. w축으로 어떻게 경사를 타고 내려갈지 정하는 것. 미분 -> 기울기니깐 그걸 구하고 평균내서 왼쪽 오른쪽을 정하는거지...
  gradient_b = torch.sum((W*x_train - y_train +b))/len_x
  //cost 함수를 b에 대해서 편미분을 떄리는 것. 2(wx1 + b -y1) -> 2는 편의상 날라가고. b축으로 어떻게 경사를 타고 내려갈지 정하는 것
  

  W -= lr * gradient_w //w_min -= lr * c'(w_min)
  b -= lr * gradient_b //w_min -= lr * c'(w_min)
  
  if epoch % 10000 == 0:
    print('Epoch {:4d}/{} W:{:.6f} b:{:.6f} Cost: {:.6f}'.format(epoch,epochs,W.item() ,b.item() , cost.item()))

30 -> 700
60 -> 750
90 -> 800
120 -> ?

h(x) = 5 / 3 * x + 650
= wx + b

w = 5/3
b = 650

행렬연산을 사용하면 복잡하고 여러개의 식으로 표현해야만 하는 연산을 한번에 처리할 수 있어요.


lr가 커지면 cost 증가
만약 작은 보폭으로 떨어지면 cost도 천천히 떨어짐


gradient_w = torch.sum((Wx_train - y_train +b)x_train)/ len_x
(Wx_train - y_train +b)x_train = ( wx1 - y1 + b ) x1
= x1^2w - y1x1 + bx1

(h(x1)-y1)^2 = cost 구하는 함수 = (x1w + b - y1)^2 -> 이걸 미분하면
2( w
x1 - y1 + b ) * x1 이게 나온다는거지? -> 2는 편의상 날라감.

그래서 ( wx1 - y1 + b ) x1

w_min -= lr * c'(w_min) 경사하강


	
a = [242,256,237,223,263,81,46]
 
n = len(a)
my_sum = 0
my_avg = 0
i = 0
 
for i in range( 0, n ):
    my_sum = my_sum+a[i]
 
my_avg = my_sum/n
 
print("Total Sum : ",my_sum)
print("Total Average : ",my_avg)

실습

인공지능 학습이 완료되었습니다!!

<script>
   var W = {{W}};
   var b = {{b}};
   
   function predict(){
      alert( W * document.getElementById("days").value + b + "점 맞으시겠네요!" );
   }
</script>

<br>
<br>
<br>

얼마나 공부하실 예정이신가요?

<input id="days" type="text"> <button type="button" onclick="predict()">예측</button>
당신의 기존 학습 데이터를 입력하세요!!

<form method="post">
   {% csrf_token %}

   공부일수1 : <input type="text" name="day1">
   성적1 : <input type="text" name="score1">
   
   <br>

   공부일수2 : <input type="text" name="day2">
   성적2 : <input type="text" name="score2">
   
   <br>

   공부일수3 : <input type="text" name="day3">
   성적3 : <input type="text" name="score3">
   
   <button type="submit">학습 시작!</button>
</form>
import torch

def toeic_ai(req):
    if req.method == 'POST':
        x_train = torch.FloatTensor([[int(req.POST.get('day1'))],[int(req.POST.get('day2'))],[int(req.POST.get('day3'))]])
        y_train = torch.FloatTensor([[int(req.POST.get('score1'))],[int(req.POST.get('score2'))],[int(req.POST.get('score3'))]])
        W = torch.zeros(1)
        b = torch.zeros(1)

        lr = 0.0002

        epochs = 200000

        len_x = len(x_train)

        for epoch in range(epochs):
          hypothesis = x_train * W + b
          cost = torch.mean((hypothesis -y_train)**2)

          gradient_w = torch.sum((W*x_train - y_train +b)*x_train)/ len_x
          gradient_b = torch.sum((W*x_train - y_train +b))/len_x

          W -= lr * gradient_w
          b -= lr * gradient_b

        return render( req, 'toeic_output.html', { 'W':W.item(), 'b':b.item() } )
    else:
        return render(req, 'toeic_input.html')
profile
Front-end Engineer, Web Developer & UX/UI Design

0개의 댓글

Powered by GraphCDN, the GraphQL CDN