tensorflow v1: regression

km-ji·2024년 1월 30일

tensorflow

목록 보기
1/9
post-thumbnail

구름 부트캠프에서 텐서플로우를 배우는데, 공부하는 김에 텐서플로우 자격증까지 따는 것이 목표이다.
일단, 오늘 배운 것들 정리를 해보자

version 1 환경으로 회귀와 분류를 공부 중이다.
1에서 지원해주는 몇 개의 데이터가 나에게는 안떠서(왜 안뜨는 거지?) load_diabetes()으로 진행했다.

✔️환경 설정 (import, ..)

import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn import datasets

데이터 가져오기

x_data = datasets.load_diabetes().data[:,2]
y_data = datasets.load_diabetes().target

df 만들어주기

df = pd.DataFrame([x_data, y_data]).transpose()
df.head()

✔️차원 설정

_x_data = tf.reshape(x_data, [len(x_data), 1])
_y_data = tf.reshape(y_data, [len(x_data), 1])


W = tf.Variable(tf.random_normal([1,5], dtype=tf.float64))
W_out = tf.Variable(tf.random_normal([5,1], dtype = tf.float64))

hidden = tf.nn.sigmoid(tf.matmul(_x_data, W)) #shape : [506, 5]
output = tf.matmul(hidden, W_out) #shape : [506, 1]

x_data와 y_data의 차원을 reshape 해주면서 len(~)행 1열로 맞춰주었다.
tensorflow ver1에서는 차원을 설정해주는 것이 중요하다!!
W은 weight로, 1행을 받아온 후 hidden layer 5개를 지정해주었다.
그 5개가 핑퐁되는 느낌으로 W_out에 연결되고, output 이 1열이므로 [5,1]로 맞춰진다.

# loss = tf.reduce_mean(tf.square(output - y_data))
loss = tf.losses.mean_squared_error(output, _y_data)
optimizer = tf.train.GradientDescentOptimizer(0.001)
train = optimizer.minimize(loss)

선형회귀 때 쓰는 코드이다.
output과 _y_data 간의 오차 제곱의 값을 loss 에 입력해주고,
train 시간은 0.001초로 지정.
손실을 최소화하는 방향으로 train.

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    
    for step in range(50000):
        sess.run(train)
        
        if step % 5000 == 0 :
            print("Step {} || Loss : {}".format(step, sess.run(loss)))
            
    output = sess.run(output)

실제로 훈련되는 코드는 sess.run(tf.global_variables_initializer() 뿐이다.
나머지는 출력되는 코드.

plt.figure(figsize = (10,10))
plt.plot(x_data, y_data, 'bo', label='Real data')
plt.plot(x_data, output, 'ro', label='Prediction')
plt.legend()
plt.show()

그래프를 그려본다.

추가) 성능 향상 확인 요소

  • Other Activation Functions (tanh, relu)
  • Other Optimizers (Adam, Adagrad, RMSProp)
  • Other Learning Rates (0.01, 0.0001)
  • More learning steps (75000, 100000)
  • More layers & nodes (64, 128, 256, ..)

끝!

profile
I'm mz. Do you want to try mzing?

0개의 댓글