기본 콘텐츠로 건너뛰기

1월, 2019의 게시물 표시

6. Gradient Descent with R code

Ch7. Gradient Descent with R Code Gradient Descent를 R code로 구현해보도록 하겠습니다. 1. 샘플 데이터 생성(난수) x = runif ( 300 , - 10 , 10 ) # 균일분포 난수 생성 Noise = rnorm ( n = 300 , mean = 0 , sd = 3 ) y = x + Noise ​ x DF = data.frame ( x   = x ,                 y = y ) ​ library ( ggplot2 ) ​ ggplot ( DF , aes ( x = x , y = y )) +   geom_point ( col = 'royalblue' ) +   theme_bw () 2. Learning Rate 설정 xxxxxxxxxx alpha = 0.01 3. 초기 가중치 행렬 생성 xxxxxxxxxx Weights = matrix ( c ( 0 , 0 ), nrow = 2 ) Weights xxxxxxxxxx     [,1] [1,]   0 [2,]   0 4. 회귀식 계산을 위한 행렬 생성 이러한 식을 R에서 만들어주어야 하는데, 코드는 다음과 같습니다. xxxxxxxxxx # 행렬형태로 만들어 주기 X = matrix ( x ) X = cbind ( 1 , X ) ​ head ( X ) xxxxxxxxxx     [,1]     [,2] [1,]   1 5.3357724 [2,]   1 6.8523958 [3,]   1 8.6630348 [4,]   1 4.2440585 [5,]   1 3.2915996 [6,]   1 0.4789394 5. Error Loss function 만들기 xxxxxxxxxx # Error 계산 # %*%는 행렬의 곱셈을 할 때 사용합니다. ​ Error = function ( x , y , Weight ){     sum (( y