관리 메뉴

ComputerVision Jack

[모두의 딥러닝 Chapter04] 본문

DeepLearning/DL_ZeroToAll

[모두의 딥러닝 Chapter04]

JackYoon 2020. 1. 15. 15:15
반응형

[04-1 multi_variable_linear_regression]

이번엔 여러개의 테이터를 갖고 linear regression을 학습한다.

 

multi variable

x1_data = [73., 93., 89., 96., 73.]

x2_data = [80., 88., 91., 98., 66.]

x3_data = [75., 93., 90., 100., 70.]

 

y_data = [152., 185., 180., 196., 142.]

#전과 다르게 데이터가 많아졌다. y_data를 보는 법은

x1_data[0] x2_data[0] x3_data[0] 이 y_data[0] 과 매칭이 된다고 생각하면 된다.

 

x1 = tf.placeholder(tf.float32)

x2 = tf.placeholder(tf.float32)

x3 = tf.placeholder(tf.float32)

 

Y = tf.placeholder(tf.float32)

#각각에 맞는 placeholder를 여러개 생성해준다.

 

w1 = tf.Variable(tf.random_normal([1]), name = 'weight'

w2 = tf.Variable(tf.random_normal([1]), name = 'weight')

w3 = tf.Variable(tf.random_normal([1]), name = 'weight')

 

b = tf.Variable(tf.random_normal([1]), name = 'bias')

#그리고 각각에 연결될 가중치는 생성하는데

바이어스는 하나만 연결해준다. 그 이유는 나중에 따로 정리해서 올리겠습니다.

x1 은 0~4 인덱스에 w1 가중치를 곱해준다.

 

hypothesis = x1 * w1 + x2 * w2 + x3 * w3 + b

#준비된 데이터와 가중치 편향을 갖고 모델을 생성합니다.

 

cost =tf.reduce_mean(tf.square(hypothesis - Y))

#cost함수를 제정한다.

 

optimizer = tf.train.GradientDescentOptimizer(learning_rate = 1e-5)

train = optimizer.minimize(cost)

#경사하강법을 통하여 cost를 깍아 내려가서 최소점을 찾는다.

 

sess = tf.Session()

sess.run(tf.global_variables_initializer())

 

for step in range(2001):

  cost_val, hy_val, _ = sess.run([cost, hypothesis, train],

                                 feed_dict = {x1 : x1_data, x2 : x2_data, x3 : x3_data, Y: y_data})

  

  if step % 10 == 0:

    print(step, "Cost : ", cost_val, "\n Prediction : ", hy_val)

# session을 돌려 결과를 보면 잘 예측한다.

[04-2 multi_variable_matmul_linear_regression]

행렬을 통하여 linear regression 수행

x_data = [[73., 80., 75.],

          [93., 88., 93.],

          [89., 91., 90.],

          [96., 98., 100.],

          [73., 66., 70.]]

 

y_data = [[152.],

          [185.],

          [180.],

          [196.],

          [142.]]

#4-1의 예제를 행렬로 묶에서 만든다. 

x_data = (5, 3)의 형태 y_data = (5, 1) 형태

 

X = tf.placeholder(tf.float32, shape =[None, 3])

Y = tf.placeholder(tf.float32, shape = [None, 1])

#이로 인해 placeholder를 만들어 줄 때, shape의 모양을 조금 신경 써야한다.

shape은 [None, 3] = [ 몇개가 들어올진 모르지만, 3가지 특성을 가지고 있을것이다]

 

W = tf.Variable(tf.random_normal([3, 1]), name = 'weight')

b = tf.Variable(tf.random_normal([1]), name ='bias')

#가중치또한 변화가 생긴다.

결국 우리는 x와 w를 곱하기 때문에 행렬의 곱으로 전환하면 된다. 

행렬의 곱셈 조건을 상기하면서 [None, 3] x [3, ?] 형태로 가중치를 만든다.

?값이 1이 들어가는 이유는 결론으로 나올 y_data를 참고하여 설정하면된다. 따라서 [3, 1]로 weight을 설정할 수 있다.

 

hypothesis = tf.matmul(X, W) + b

#가설도 행렬의 곱을 지원하는 tf.matmul() 메소드를 사용하여 준비된 data와 weight, bias를 넣는다.

 

나머지 코드는 4-1 예제와 동일하다.

[04-3 file_input_linear_regression]

이번엔 file을 읽어 들여 처리한다.

from google.colab import files

uploaded = files.upload()

#작업 환경이 코렙이기 때문에 colab에서 바탕화면의 파일을 읽어 오기위한 라이브러리를 import 한다.

 

github 자료 가져오기

김성훈 교수님 github에 들어가 csv파일을 선택하고, Raw버튼을 누르면 데이터를 복사할 수 있게 생성이된다.

메모장을 켜고 붙여 넣은다음 파일 저장을 .csv로 하면된다. 저장형식 또한 모든 파일로 바꾸어준다.

 

import tensorflow as tf

import numpy as np

tf.set_random_seed(777)

# 수치해석 라이브러리 numpy를 import 한다.

 

xy = np.loadtxt('data-01-test-score.csv', delimiter =',', dtype = np.float32)

x_data = xy[:, 0:-1]

y_data = xy[:, [-1]]

#데이터를 읽어와서 x_data와 y_data로 빼놓는다.

그리고 슬라이싱을 통하여 뒤의 마지막빼고 나머지를 x 뒷부분을 value인 y에 저장한다.

 

print(x_data, "\nx_data shape : ", x_data.shape)

print(y_data, "\ny_data shape : ", y_data.shape)

#shape을 찍어보고 weight과 bias를 설정하고 4-2 예제 처럼 실행하면 작동한다.

[04-4 tf_reader_linear_regression]

filename_queue 사용하기

이번 예제는 dataset이 클 경우 filename_queue를 이용하여 데이터를 나눈후 작업시키는 방법을 알아본다.

filename_queue = tf.train.string_input_producer(

    ['data-01-test-score.csv'], shuffle = False, name = 'filename_queue'

)

#마찬가지로 구글에서 파일을 읽어온뒤 filename_queue를 생성한다.

큐를 생성하면 큐에 있는 파일을 하나씩 읽어올 Reader를 생성하여야 한다.

 

reader = tf.TextLineReader()

key, value = reader.read(filename_queue)

#이런식으로 reader를 통하여 파일을 읽으면 value에 읽은 파일이 반환된다.

 

record_defaults = [[0.], [0.], [0.], [0.]]

xy = tf.decode_csv(value, record_defaults = record_defaults)

#다음에 reader로 읽어들인 데이터를 디코드한다.

 

train_x_batch, train_y_batch = \

tf.train.batch([xy[0: -1], xy[-1:]], batch_size = 10)

#batch_size를 생성해서 학습에 넣을 준비를 한다.

 

sess = tf.Session()

sess.run(tf.global_variables_initializer())

coord = tf.train.Coordinator()

threads = tf.train.start_queue_runners(sess = sess, coord = coord)

# session을 만든후 반드시 Coodinator()를 제작하여 Queue Runner안의 별도의 thread를 관리해 준다.

 

for step in range(2001):

  x_batch, y_batch = sess.run([train_x_batch, train_y_batch])

  cost_val, hy_val, _ = sess.run([cost, hypothesis, train], feed_dict = {X: x_batch, Y: y_batch})

 

  if step % 10 == 0:

    print(step, "Cost : ", cost_val, "\nPrediction : ", hy_val)

 

coord.request_stop()

coord.join(threads)

 

#Ask my score

print("Your score will be ", sess.run(hypothesis, feed_dict = {X: [[100, 70, 101]]}))

print("Other score will be ", sess.run(hypothesis, feed_dict = {X: [[60, 70, 110], [90, 100, 80]]}))

#그리고 학습을 시켜 결과를 예측하면된다.

 

filename_queue를 이해하기 위하여 조대협님의 블로그를 많이 참조하였다.

위 내용 이외에도 많은 딥러닝에 대한 자료가 있다. 정말 공부해 나아가며 많은 도움을 받아서 

감사의 인사를 드리고 싶다.

https://bcho.tistory.com/1163?category=555440

 

텐서플로우-파일에서 학습 데이타를 읽어보자 #1 (큐 사용 방법과 구조)

텐서플로우 - 파일에서 학습데이타를 읽어보자#1 조대협 (http://bcho.tistory.com) 텐서플로우를 학습하면서 실제 모델을 만들어보려고 하니 생각보다 데이타 처리에 대한 부분에서 많은 노하우가 필요하다는 것..

bcho.tistory.com

조대협님의 블로그에 들어가 공부해 보는 것을 추천한다.

04-1-multi_variable_linear_regression.ipynb
0.02MB
04-2-multi_variable_matmul_linear_regression.ipynb
0.03MB
04-3-file_input_linear_regression.ipynb
0.10MB
04-4-tf_reader_linear_regression.ipynb
0.06MB

반응형

'DeepLearning > DL_ZeroToAll' 카테고리의 다른 글

[모두의 딥러닝 Chapter07]  (0) 2020.01.19
[모두의 딥러닝 Chapter06]  (0) 2020.01.17
[모두의 딥러닝 Chapter05]  (0) 2020.01.16
[모두의 딥러닝 Chapter03]  (0) 2020.01.14
[모두의 딥러닝 Chapter02]  (0) 2020.01.13
Comments