05-02 06:32
Notice
Recent Posts
Recent Comments
관리 메뉴

Scientific Computing & Data Science

[Artificial Intelligence / TensorFlow] R-TensorFlow 예제 - Multi-variable Linear Regression 본문

Artificial Intelligence/TensorFlow

[Artificial Intelligence / TensorFlow] R-TensorFlow 예제 - Multi-variable Linear Regression

cinema4dr12 2017. 7. 8. 09:25

by Geol Choi | Jul.


이번 포스팅에서는 다중변수 선형 회귀(Multi-variable Linear Regression 또는 Multiple Linear Regression) 모델에 대한 간단한 이론과 이를 TensorFlow를 이용하여 최적화 문제로 풀고 결과를 비교해 보도록 하겠다.

1. Theory by Example 

1.1. Dataset - IQ와 신체적 특성과의 관계

지능지수에 관하여 많은 사람들이 궁금해하는 것이 있다: "과연 뇌의 크기와 지능지수와의 상관성이 있을까? 있다면, 뇌의 크기로 지능지수를 유추할 수 있을까?"

이 질문에 답을 하기 위하여 몇몇 연구자들(Willerman, et al, 1991)은 38명의 대학생들을 상대로 뇌의 신체적 특성과 IQ를 조사하였다: iqsize.txt


이 데이터셋의 각 데이터(또는 Feature)에 대한 설명은 다음과 같다:


  • PIQ(Response y): Wechsler Adult Intelligence Scale 개정판으로 평가한 지능지수(Performance Intelligent Quotient).

  • Brain(Predictor x1): MRI 스캔으로 얻은 뇌의 크기.

  • Height(Predictor x2): 인치(inches) 단위 키.

  • Weight(Predictor x3): 파운드(pounds) 단위 몸무게.

1.2. 변수에 대한 효과 분석

뇌의 크기, 높이, 무게 등 3개의 변수가 PIQ라는 응답출력(Response)에 어떻게 관여하는지 조사하는 방법 중 가장 직관적인 방법은 이러한 상관관계를 시각화하는 것이다.


이를 R을 활용하여 설명을 진행하도록 한다.


우선 분석할 데이터세트가 필요하므로, iqsize.txt 파일을 tsv(Tab Separated Values) 파일로 변환한 iqsize.tsv 파일을 다운받는다: iqsize.tsv


그리고, 데이터프레임(Dataframe) 변수로 불러온다(iqsize.tsv 파일은 현재 Working Directory 내에 존재한다고 가정한다):


1
df <- utils::read.table("./iqsize.tsv", header=TRUE, sep="\t")
cs



각 변수에 대한 효과를 시각화하는 방법으로 가장 효과적인 방법 중 하나는 Scatterplot Matrix를 뽑아보는 것이다:


1
graphics::pairs(~PIQ+Brain+Height+Weight, data=df, main="Scatterplot Matrix for Brain")
cs



그렇다면 이들 플롯이 의미하는 것은 무엇일까? 물론 두 변수간의 관계를 한 눈에 확인할 수 있다. 가령, 다음 이미지에서 빨간 박스로 표시한 부분은 PIQ와 Brain 두 데이터 간의 분포를 나타낸 것이다. 즉, x = Brain, y = PIQ인 데이터 포인트를 플롯한 것이다. 녹색 박스로 표시한 것은, 반대로 x = PIQy = Brain의 데이터 포인트를 플롯한 것이다.


 

각 변수의 응답출력에 대한 효과를 알아보는 다른 방법 중 하나는 상관관계 값을 계산해 보는 것이다. R의 함수 stats::cor()를 이용하여 상관관계 테이블을 출력할 수 있다:


1
2
# correlation table
stats::cor(x=df, use="complete.obs", method="spearman")
cs


출력 결과는 다음과 같다:

> stats::cor(x=df, use="complete.obs", method="spearman")
               PIQ     Brain      Height     Weight
PIQ     1.00000000 0.4126407 -0.06170333 0.02924883
Brain   0.41264069 1.0000000  0.56156573 0.54772332
Height -0.06170333 0.5615657  1.00000000 0.70810778
Weight  0.02924883 0.5477233  0.70810778 1.00000000

상관관계 테이블의 값들은 변수 간 상관관계 계수(Correlation Coefficient)를 의미하는데, [-1, +1] 범위의 값을가지며, +1은 완벽한 양의 상관관계, 0은 상관관계 없음, -1은 완벽한 음의 상관관계를 뜻한다.

위의 상관관계 테이블을 살펴보면, Brain이 Height, Weight에 비해 압도적으로 PIQ에 양(Positive)의 상관관계 로 영향을 미치는 것을 알 수 있다.

흥미로운 것은, 미약하긴 하지만 키(Height)는 지능지수(PIQ)와 약한 음의 상관관계가 있음을 알 수 있다.


stats::cor()가 제공하는 상관관계 계산 방식은 "pearson", "kendall", "spearman" 세 가지가 있는데, 이에 대한 자세한 설명이 있는 링크를 걸어놓았으니 관심이 있는 분들은 읽어보시기 바란다.

1.3. 모델 세우기

입력변수들 Brain(x1), Height(x2), Weight(x3)의 값으로부터 출력응답 PIQ(y)를 예측할 수 있는 모델은 어떻게 될까? 이를 표현하는 가장 심플한 모델로 다중변수 회귀(Multi-variable Linear Regression) 모델(또는 Predictor)을 세울 수 있다:


\(y_i = (b + w_1 x_{i1} + w_2 x_{i2} + w_3 x_{i3}) + \epsilon_i\)


여기서 각각의 변수에 대한 설명은 다음과 같다:


  • \(y_i\) : i번째 학생의 지능지수(PIQ)

  • \(x_{i1}\) : i번째 학생의 두뇌 크기(Brain)

  • \(x_{i2}\) : i번째 학생의 키(Height)

  • \(x_{i3}\) : i번째 학생의 몸무게(Weight)

  • \(\epsilon_i\) : i번째 학생 데이터의 오차, \(\epsilon\) ~ \(N(0, \sigma^2)\)

  • \(w_1\) ~ \(w_3\) : \(x_1 ~ x_3\)에 대한 가중치

  • \(b\) : 바이어스(Bias)


따라서, 모델을 결정하는 것은 가중치 \(w_1 ~ w_3\)의 값을 찾는 것이며, 단일 변수 선형 회귀(Single-variable Linear Regression)과 마찬가지로 최적화 문제를 통해 찾을 수 있다.


R의 stats 라이브러리가 제공하는 stats::lm() 함수를 통해 단 두 줄의 코드로 가중치 변수값들 및 이들에 대한 분석 결과를 얻을 수 있다:


1
2
3
4
## Multiple Linear Regression
fit <- stats::lm(PIQ ~ Brain + Height + Weight, data=df)
# show results
summary(fit)
cs


다음과 같은 결과를 얻을 수 있는데,


> fit <- stats::lm(PIQ ~ Brain + Height + Weight, data=df)
> summary(fit)

Call:
stats::lm(formula = PIQ ~ Brain + Height + Weight, data = df)

Residuals:
   Min     1Q Median     3Q    Max 
-32.74 -12.09  -3.84  14.17  51.69 

Coefficients:
              Estimate Std. Error t value Pr(>|t|)    
(Intercept)  1.114e+02  6.297e+01   1.768 0.085979 .  
Brain        2.060e+00  5.634e-01   3.657 0.000856 ***
Height      -2.732e+00  1.229e+00  -2.222 0.033034 *  
Weight       5.599e-04  1.971e-01   0.003 0.997750    
---
Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1

Residual standard error: 19.79 on 34 degrees of freedom
Multiple R-squared:  0.2949,	Adjusted R-squared:  0.2327 
F-statistic: 4.741 on 3 and 34 DF,  p-value: 0.007215


위의 결과로부터 다음의 몇가지를 도출할 수 있다:


  • R-squared(\(R^2\)) 값이 29.49%(0.2949)인데, 뇌의 크기, 키, 몸무게를 고려하여 PIQ로 표현되는 지능지수의 분산값이 29.49% 만큼 줄었음을 의미한다.

  • Adjusted R-squared 값은 23.27%(0.2327)인데, 이는 PIQ에 대한 다른 다중 선형 회귀 모델을 고려할 때 이 값을 이용하여 모델을 비교할 수 있음을 의미한다.

  • t-test를 통한 p-value는 Pr(>|t|)로 표시되어 있는데, Brain의 계수 \(w_1\)(p = 0.000856)와 Height의 계수 \(w_2\)(p = 0.033034)는 0으로부터 유의수준에 있는 반면, Weight의 계수 \(w_3\)(p = 0.997750)는 그렇지 못하다.


또한, Linear Regression Model의 Bias와 계수들의 값은 다음과 같았다:


> fit

Call:
stats::lm(formula = PIQ ~ Brain + Height + Weight, data = df)

Coefficients:
(Intercept)        Brain       Height       Weight  
  1.114e+02    2.060e+00   -2.732e+00    5.599e-04 


따라서 이들을 적용한 다중변수 회귀 모델은 다음과 같다:


\(\hat{y}_i = 111.4 + 2.060 * \mathrm{Brain} - 2.732 * \mathrm{Height} + 0.00056 * \mathrm{Weight}\)


여기서, \(\hat{y}_i\)는 \(y_i\)의 근사값을 의미하는데 이렇게 쓴 이유는 에러 항 \(\epsilon_i\)을 생략했기 때문이다.


위의 결과를 토대로 실제값과 Regression 된 값을 비교해보도록 하자:


1
2
3
4
5
6
7
8
## comapre the data provided & predicted
<- fit[[1]][1]
w1 <- fit[[1]][2]
w2 <- fit[[1]][3]
w3 <- fit[[1]][4]
 
df$Predicted <- base::with(df, b + w1*Brain + w2*Height + w3*Weight)
print(df[,base::c(1,5)])
cs


결과를 출력해 보면 다음과 같다:


> print(df[,base::c(1,5)])
   PIQ Predicted
1  124 103.53347
2  150 125.13487
3  128 122.40710
4  134 129.91131
5  110 114.30655
6  131 139.47107
7   98 107.17178
8   84 116.75283
9  147 120.36770
10 124 107.03547
11 128 142.62154
12 124 113.34338
13 147  95.31978
14  90 112.22315
15  96 103.97199
16 120  99.88231
17 102 105.38826
18  84  96.79255
19  86 103.41538
20  84  89.12154
21 134 104.94791
22 128 122.42791
23 102 110.69863
24 131 107.50474
25  84  90.21399
26 110 120.01570
27  72 102.80435
28 124 108.35122
29 132 117.42791
30 137 124.08054
31 110 110.80890
32  86 104.27334
33  81 101.66787
34 128 125.11626
35 124 114.45103
36  94 119.42783
37  74 100.89487
38  89  98.02962

2. Python-TensorFlow Code

기본적인 이론을 어느 정도 알아보았는데, 이를 TensorFlow 코드로 작성해서 예측 회귀 모델을 찾고 이 모델로 예측값을 구해보도록 한다.

2.1. 라이브러리 불러오기

numpy, tensorflow, matplotlib 등 필요한 라이브러리를  불러온다:


1
2
3
4
## import libraries
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
cs

2.2. 파라미터 정의

학습률(learning_rate), 학습 반복회수(training_epochs), 계산값 표시 주기(display_step)를 정의한다:


1
2
3
4
## define parameters
learning_rate = 1.0e-5
training_epochs = 40000
display_step = 500
cs

2.3. 데이터 파일로부터 데이터 불러오기

두뇌의 크기, 키, 몸무게와 지능지수가 기록되어 있는 iqsize.tsv 파일로부터 이들 데이터를 불러온다. 파일의 내용은 다음과 같다:


#PIQ	Brain	Height	Weight
124	81.69	64.5	118
150	103.84	73.3	143
128	96.54	68.8	172
134	95.15	65.0	147
110	92.88	69.0	146
131	99.13	64.5	138
98	85.43	66.0	175
84	90.49	66.3	134
147	95.55	68.8	172
124	83.39	64.5	118
128	107.95	70.0	151
124	92.41	69.0	155
147	85.65	70.5	155
90	87.89	66.0	146
96	86.54	68.0	135
120	85.22	68.5	127
102	94.51	73.5	178
84	80.80	66.3	136
86	88.91	70.0	180
84	90.59	76.5	186
134	79.06	62.0	122
128	95.50	68.0	132
102	83.18	63.0	114
131	93.55	72.0	171
84	79.86	68.0	140
110	106.25	77.0	187
72	79.35	63.0	106
124	86.67	66.5	159
132	85.78	62.5	127
137	94.96	67.0	191
110	99.79	75.5	192
86	88.00	69.0	181
81	83.43	66.5	143
128	94.81	66.5	153
124	94.94	70.5	144
94	89.40	64.5	139
74	93.00	74.0	148
89	93.59	75.5	179

데이터를 불러오고 입력 데이터와 출력 데이터 별로 구분하여 새로운 변수들에 저장한다:


1
2
3
4
5
6
7
8
## loading from data file
xy = np.loadtxt('../iqsize.tsv', delimiter='\t', dtype=np.float32)
 
y_data = xy[:, 0]
 
x1_data = xy[:,1]
x2_data = xy[:,2]
x3_data = xy[:,3]
cs

2.4. Placeholder 정의

각 입력 데이터 및 출력 데이터에 대한 Placeholder를 정의한다. Placeholder는 런타임 시 데이터를 공급하는 TensorFlow의 Symbolic Programming Model이다:


1
2
3
4
5
6
## placeholders for a tensor that will be always fed.
x1 = tf.placeholder(tf.float32)
x2 = tf.placeholder(tf.float32)
x3 = tf.placeholder(tf.float32)
 
= tf.placeholder(tf.float32)
cs

2.5. 변수 및 Hypothesis 정의

최적화 문제에 대한 변수와 Hypothesis(가설)을 정의한다:


1
2
3
4
5
6
7
8
## define varaibles & hypothesis
w1 = tf.Variable(tf.random_normal([1]), name='weight1')
w2 = tf.Variable(tf.random_normal([1]), name='weight2')
w3 = tf.Variable(tf.random_normal([1]), name='weight3')
= tf.Variable(tf.random_normal([1]), name='bias')
 
hypothesis = x1 * w1 + x2 * w2 + x3 * w3 + b
print(hypothesis)
cs

2.6. Cost 함수 및 Optimizer 정의

최적화 문제의 목적 함수(Objective Function)가 되는 Cost 함수를 정의하고 급강하경사법(Gradient Descent)으로 Optimizer를 정의한다. 학습률은 1.0e-5로 정하였다:


1
2
3
4
5
6
## cost/loss function
cost = tf.reduce_mean(tf.square(hypothesis - Y))
 
## minimize. Need a very small learning rate for this data set
optimizer = tf.train.GradientDescentOptimizer(learning_rate=learning_rate)
train = optimizer.minimize(cost)
cs

2.7. 변수 초기화

최적화 문제의 변수들인 가중치(Weights)와 바이어스(Bias) 변수들을 초기화하고, 각 Epoch에 대한 Cost 함수값을 저장하여 이를 그래프로 가시화를 위해 이들을 저장하는 변수를 초기화한다:


1
2
3
4
5
6
## initializes global variables in the graph.
tf.set_random_seed(0)
init = tf.global_variables_initializer()
 
## initialize variable for plotting
cost_res = np.zeros(shape=(training_epochs,2))
cs

2.8. TensorFlow 세션 정의 및 반복 계산

이제 TensorFlow 세션을 정의하여 초기화하고:


1
2
3
## launch the graph
with tf.Session() as sess:
    sess.run(init)
cs


전체 학습 반복 횟수 동안 Optimizer를 통해 Cost 함수를 최적화하도록 한다:


1
2
3
4
5
6
7
8
# fit all training data
for epoch in range(training_epochs):
    cost_val, hy_val, _ = sess.run([cost, hypothesis, train], feed_dict={x1: x1_data, x2: x2_data, x3: x3_data, Y: y_data})
    cost_res[epoch, 0= epoch
    cost_res[epoch, 1= np.log(cost_val)
    
    if epoch % display_step == 0:
        print("Epoch: ", (epoch+1), " , Cost: ", cost_val)
cs


위의 코드의 Line #5에서 cost_val에 로그(log)를 취한 이유는, Epoch가 진행됨에 따라 Cost 함수값의 차이가 Order of Magnitude 수준으로 차이가 나기 때문에 효과적으로 시각화 할 수 있도록 로그 스케일(Log-Scale)로 변환한 것이다.

2.9. 결과 출력 및 비교

Epoch가 진행됨에 따라 Cost 함수의 변화를 시각화한다:


1
2
3
# graphic display
plt.plot(cost_res[:,0], cost_res[:,1], 'ro', label='Cost Function Value as Epoch Proceeds')
plt.show()
cs



코드를 실행하여 얻어진 Epoch-Cost 함수 그래프를 통해 Epoch가 진행됨에 따라 점진적으로 Cost 함수값이 작아졌음을 알 수 있다.


그리고, 마지막으로 실제 데이터와 예측 모델을 통해 얻어진 데이터를 비교하도록 한다:


1
2
3
## compare results
for i in range(35):
    print(y_data[i], " , ", hy_val[i])
cs


최적화를 통해 얻어진 Weights와 Bias를 적용하여 얻은 데이터(예측 모델을 통해 얻은 데이터)와 실제 데이터를 비교하였는데 다음과 같았다 (training_epochs 값을 늘리면 좀 더 정확한 값을 얻을 수 있을 것이다):


실제 데이터, 예측 모델을 통해 얻은 데이터
124.0  ,  99.7147
150.0  ,  137.126
128.0  ,  120.896
134.0  ,  125.588
110.0  ,  116.235
131.0  ,  136.591
98.0  ,  98.0455
84.0  ,  115.489
147.0  ,  118.632
124.0  ,  103.604
128.0  ,  148.876
124.0  ,  113.8
147.0  ,  96.7191
90.0  ,  108.053
96.0  ,  104.47
120.0  ,  102.12
102.0  ,  110.281
84.0  ,  93.0202
86.0  ,  100.94
84.0  ,  96.8715
134.0  ,  95.7886
128.0  ,  125.42
102.0  ,  105.344
131.0  ,  110.758
84.0  ,  88.4335
110.0  ,  132.006
72.0  ,  97.7906
124.0  ,  102.76
132.0  ,  109.867
137.0  ,  116.353
110.0  ,  118.089
86.0  ,  99.7852
81.0  ,  97.764
128.0  ,  122.287
124.0  ,  119.632

2.10. 전체 Python Code

Multiple Linear Regression Python-TensorFlow Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
#############################################################################
# multi-variable linear regression example using TensorFlow library.
#############################################################################
# Author: Geol Choi, phD.(cinema4dr12@gmail.com)
# Date: July 5, 2017
#############################################################################
 
## import libraries
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
 
## define parameters
learning_rate = 1.0e-5
training_epochs = 40000
display_step = 500
 
## loading from data file
xy = np.loadtxt('../iqsize.tsv', delimiter='\t', dtype=np.float32)
 
y_data = xy[:, 0]
 
x1_data = xy[:,1]
x2_data = xy[:,2]
x3_data = xy[:,3]
 
## placeholders for a tensor that will be always fed.
x1 = tf.placeholder(tf.float32)
x2 = tf.placeholder(tf.float32)
x3 = tf.placeholder(tf.float32)
 
= tf.placeholder(tf.float32)
 
## define varaibles & hypothesis
w1 = tf.Variable(tf.random_normal([1]), name='weight1')
w2 = tf.Variable(tf.random_normal([1]), name='weight2')
w3 = tf.Variable(tf.random_normal([1]), name='weight3')
= tf.Variable(tf.random_normal([1]), name='bias')
 
hypothesis = x1 * w1 + x2 * w2 + x3 * w3 + b
print(hypothesis)
 
## cost/loss function
cost = tf.reduce_mean(tf.square(hypothesis - Y))
 
## minimize. Need a very small learning rate for this data set
optimizer = tf.train.GradientDescentOptimizer(learning_rate=learning_rate)
train = optimizer.minimize(cost)
 
## initializes global variables in the graph.
tf.set_random_seed(0)
init = tf.global_variables_initializer()
 
## initialize variable for plotting
cost_res = np.zeros(shape=(training_epochs,2))
 
## launch the graph
with tf.Session() as sess:
    sess.run(init)
    
    # fit all training data
    for epoch in range(training_epochs):
        cost_val, hy_val, _ = sess.run([cost, hypothesis, train], feed_dict={x1: x1_data, x2: x2_data, x3: x3_data, Y: y_data})
        cost_res[epoch, 0= epoch
        cost_res[epoch, 1= np.log(cost_val)
        
        if epoch % display_step == 0:
            print("Epoch: ", (epoch+1), " , Cost: ", cost_val)
            
    # graphic display
    plt.plot(cost_res[:,0], cost_res[:,1], 'ro', label='Cost Function Value as Epoch Proceeds')
    plt.show()
    
    ## compare results
    for i in range(35):
        print(y_data[i], " , ", hy_val[i])
 
cs

3. R-TensorFlow Code

R-TensorFlow 코드는 코드를 표현하는 방식이 Python-TensorFlow와 약간 차이가 있을 뿐, 전체적인 흐름은 동일하다. 단, 그래프 출력을 위해서 Plotly 패키지를 활용하였다.




Multiple Linear Regression R-TensorFlow Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
#############################################################################
# multi-variable linear regression example using TensorFlow library.
#############################################################################
# Author: Geol Choi, phD.(cinema4dr12@gmail.com)
# Date: July 5, 2017
#############################################################################
base::rm(list = ls())
base::gc()
 
## import libraries
if (! ("plotly" %in% rownames(installed.packages()))) { install.packages("plotly") }
library(plotly)
 
if (! ("tensorflow" %in% rownames(installed.packages()))) { install.packages("tensorflow") }
base::library(tensorflow)
 
## define parameters
learning_rate <- 1.0e-5
training_epochs <- 40000
display_step <- 500
 
## import data
df <- utils::read.table("./iqsize.tsv", header=TRUE, sep="\t")
 
## define model variables
x1_data <- df$Brain
x2_data <- df$Height
x3_data <- df$Weight
 
y_data <- df$PIQ
 
## set random seed
tensorflow::tf$set_random_seed(777)
 
## placeholders for a tensor that will be always fed.
x1 <- tensorflow::tf$placeholder(tensorflow::tf$float32)
x2 <- tensorflow::tf$placeholder(tensorflow::tf$float32)
x3 <- tensorflow::tf$placeholder(tensorflow::tf$float32)
<- tf$placeholder(tf$float32)
 
w1 <- tensorflow::tf$Variable(rnorm(n=1,mean=0,sd=100), name='weight1')
w2 <- tensorflow::tf$Variable(rnorm(n=1,mean=0,sd=100), name='weight2')
w3 <- tensorflow::tf$Variable(rnorm(n=1,mean=0,sd=100), name='weight3')
b  <- tensorflow::tf$Variable(rnorm(n=1,mean=0,sd=100), name='bias')
 
hypothesis <- tensorflow::tf$add(tensorflow::tf$add(tensorflow::tf$add(tensorflow::tf$multiply(x1, w1), tensorflow::tf$multiply(x2, w2)), tensorflow::tf$multiply(x3, w3)), b)
 
base::print(hypothesis)
 
## cost/loss function
cost <- tensorflow::tf$reduce_mean(tensorflow::tf$square(hypothesis - Y))
 
## minimize. Need a very small learning rate for this data set
optimizer <- tensorflow::tf$train$GradientDescentOptimizer(learning_rate)$minimize(cost)
 
## launch the graph in a session.
sess <- tensorflow::tf$Session()
 
## initializes global variables in the graph.
sess$run(tf$global_variables_initializer())
 
## initialize variable for plotting
cost_res <- base::matrix(data=0.0, nrow=training_epochs, ncol=2)
cost_res <- base::as.data.frame(cost_res)
base::names(cost_res) <- base::c("Epoch""Cost")
 
## fit all training data
for(epoch in 1:training_epochs) {
  sess$run(optimizer, feed_dict = dict(x1=x1_data, x2=x2_data, x3=x3_data, Y=y_data))
  cur_cost <- sess$run(cost, feed_dict = dict(x1=x1_data, x2=x2_data, x3=x3_data, Y=y_data))
  
  # record avg_cost for each epoch
  cost_res[epoch,] <- base::c(epoch, base::log(cur_cost))
  
  # Display logs per epoch step
  if((epoch+1) %% display_step == 0) {
    res <- base::sprintf("Epoch: %04d , cost = %.9f, w1 = %f, w2 = %f, w3 = %f, b = %f",
                         (epoch+1),
                         cur_cost,
                         sess$run(w1),
                         sess$run(w2),
                         sess$run(w3),
                         sess$run(b))
    base::print(res)
  }
}
 
## plotting with Plotly
<- plotly::plot_ly(data = cost_res,
                     x = ~Epoch,
                     y = ~Cost,
                     type = 'scatter',
                     mode = 'lines+markers',
                     line = list(color = 'rgb(205, 12, 24)', width = 3)) %>%
  layout(title = "Cost Function Value as Epoch Proceeds",
         xaxis = list(title = "Epoch"),
         yaxis = list (title = "Cost"))
 
# print results
print(p)
 
## compare results
w1_res <- sess$run(w1)
w2_res <- sess$run(w2)
w3_res <- sess$run(w3)
b_res <-  sess$run(b)
 
df$PIQ_PREDICTED <- base::with(df, b_res + w1_res*Brain + w2_res*Height + w3_res*Weight)
 
base::print(df[,base::c(1,5)])
 
cs


Comments