본문 바로가기
AI

머신러닝 스터디 -02 Multi-Variable linear regression

by Wonryeol 2020. 3. 14.

 

단일 요소가 아닌 다중 오소가 결합되어 Linear Regression 을 도출해야 하는 경우  multi -variable linear regression 을 사용한다.

 

linear Regression 과 큰 차이는 없다. 

 

단지 matrix 개념이 들어간 것 뿐이다. 

 

 

 

이러한 식을 갖고 있는 multi- variable linear regression 은 메트릭스로 계산을 할때 가장 효율적인 계산 / 코드 식을 낮는다. 

 

코드로 나타내면 다음과 같다 

 

 

X 는 6열을 가지고 있지만 행에는 한계가 없는 메트릭스

Y 는 결과값

 

W 는 1열 6행을 가지고 있는 기울기값 이다. 

 

이를 메트릭스로 곱해주는 tf(tensorflow).matmul(X,W)  메소드를 사용한다면 상당히 간단하고 효율적이게 코딩이 가능하다. 

 

코딩 전문은 다음과 같다

 


import tensorflow as tf
import numpy as np
from google.colab import drive 



xy = np.loadtxt('/content/gdrive/My Drive/Colab Notebooks/csv file/Real estate 복사본.csv', delimiter=',', dtype=np.float32)

def min_max_scalar(data):
  numerator = data - np.min(data, 0)
  denominator = np.max(data, 0) - np.min(data, 0)
  return numerator / (denominator + 1e-7)

xy = min_max_scalar(xy)


x_data = xy[:,1:-1]
y_data = xy[:,[-1]]

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

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

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

B = tf.Variable(tf.random_normal([1,1]), name = 'Bias' )

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

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

Optimizer = tf.train.GradientDescentOptimizer(learning_rate= 0.01)


train = Optimizer.minimize(cost)

with tf.Session() as session:

  session.run(tf.global_variables_initializer())

  for i  in range(100):
    cost_val , hypo_val , _ = session.run([cost,hypothesis,train], feed_dict={X : x_data , Y : y_data}  )


    print("Cost : ", cost_val  )
  

  print(hypo_val)

#    if i == 1999:
##     print("hypo_val :" ,hypo_val)







그리고 real estimate 데이터 의 요소 총 6개로 머신러닝을 한 결과 cost 값이 0에 가까이 수렴하는것을 확인 할 수 있었다.

댓글