Skip to content

Latest commit

 

History

History
223 lines (160 loc) · 7.2 KB

4.multi-variable-linear-regression.md

File metadata and controls

223 lines (160 loc) · 7.2 KB

다변수 선형 회귀

이전에는 입력값이 하나뿐인 one-variable, one-feature을 통해 학습을 진행했다.

Predicting exam score: regression using two inputs (x1, x2)

2개 이상일 경우 multi-variable, multi-feature라 칭한다. 위 표에서 시간(x1)과 참여 횟수(x2)를 의미한다.

variable이 2개라고 하더라도 hypothesis는 각 변수에 다른 weight를 각각 적용했다고 생각하면된다. 결국 똑같은 형태의 hypothesis이며 cost function도 기존에 존재했던 것과 거의 동일하다.

하지만 변수가 많아질수록 수식으로 표현하는 방식이 지져분해지고 사람이 보기에 어려워진다는 문제점이 존재한다.

Matrix

매트릭스를 활용해서 변수가 많아 복잡했던 식을 간단하게 표현할 수 있다.

1X3 매트릭스를 W로 3X1 매트릭스를 X로 두면 H(X) = WX와 같이 간단하게 표현가능하다.

원래 hypothesis은 H(x) = Wx + b인데 여기서 b를 표현할 때는 W 매트릭스와 X 매트릭스의 가장 앞에 놓인 첫번째 요소를 통해 매트릭스로 표현한 H(X) = WX 만으로도 기존의 biasb를 그대로 살려 적용할 수 있게 된다.

각 매트릭스의 구성은 다르지만 수학자들은 W와 X를 동일한 구조로 표현하기를 원했다. 하지만 매트릭스 곱셈은 [1X4] * [4X1]과 같이 앞의 매트릭스에 대한 열과 뒷쪽의 매트릭스에 대한 행의 숫자가 동일해야한다는 문제가 발생하게 된다.

이 때 Transpose라는 개념이 등장하며 H(X) = W^TX처럼 표현할 수 있다. 즉, 행과 열의 개수를 맞추고 transpose를 통해 매트릭스 곱에 대한 조건을 맞춰 계산을 진행하게 된다. 프로그래밍을 진행할 때는 차원을 다르게주고 transpose를 통해 맞추는 작업을 할 수 있다. 차원을 어떻게 생성하느냐는 개발자의 자유이다.

import tensorflow as tf

x1_data = [1, 0, 3, 0, 5]
x2_data = [0, 2, 0, 4, 0]
y_data = [1, 2, 3, 4, 5]

W1 = tf.Variable(tf.random_uniform([1], -1.0, 1.0))
W2 = tf.Variable(tf.random_uniform([1], -1.0, 1.0))

b = tf.Variable(tf.random_uniform([1], -1.0, 1.0))

# Our hypothesis
hypothesis = W1 * x1_data + W2 * x2_data + b

# Simplified cost function
cost = tf.reduce_mean(tf.square(hypothesis - y_data))

# Minimize
a = tf.Variable(0.1)  # Learning rate, alpha
optimizer = tf.train.GradientDescentOptimizer(a)
train = optimizer.minimize(cost)

# Before starting, initialize the variables. We will 'run' this first.
init = tf.global_variables_initializer()

# Launch the graph.
sess = tf.Session()
sess.run(init)

# Fit the line.
for step in range(2001):
    sess.run(train)
    if step % 20 == 0:
        print(step, sess.run(cost), sess.run(W1), sess.run(W2), sess.run(b))

weight가 1개가 아닌 여러 개를 학습시켜야한다.

매트릭스로 표현하기 위해 배열을 통해 차원을 부여한다. 이제는 코드에 매트릭스 곱셈(matmul)을 통해 연산을 진행해야한다.

import tensorflow as tf

x_data = [[0., 2., 0., 4., 0.],
          [1., 0., 3., 0., 5.]]
y_data = [1, 2, 3, 4, 5]

# Try to find values for W
W = tf.Variable(tf.random_uniform([1, 2], -1.0, 1.0))
b = tf.Variable(tf.random_uniform([1], -1.0, 1.0))

# Our hypothesis
hypothesis = tf.matmul(W, x_data) + b
# Simplified cost function
cost = tf.reduce_mean(tf.square(hypothesis - y_data))

# Minimize
a = tf.Variable(0.1)  # Learning rate, alpha
optimizer = tf.train.GradientDescentOptimizer(a)
train = optimizer.minimize(cost)

# Before starting, initialize the variables. We will 'run' this first.
init = tf.global_variables_initializer()

# Launch the graph.
sess = tf.Session()
sess.run(init)

# Fit the line.
for step in range(2001):
    sess.run(train)
    if step % 20 == 0:
        print(step, sess.run(cost), sess.run(W), sess.run(b))

x_data의 형태가 변경되었으며 random_uniform에 전달하는 인자값도 변경이 되었다. b도 매트릭스로 표현한다면 코드는 아래와 같이 축소된다.

import tensorflow as tf

x_data = [[1, 1, 1, 1, 1],
          [0., 2., 0., 4., 0.],
          [1., 0., 3., 0., 5.]]
y_data = [1, 2, 3, 4, 5]

# Try to find values for W
W = tf.Variable(tf.random_uniform([1, 3], -1.0, 1.0))

# Our hypothesis
# previous hypothesis with b, hypothesis = tf.matmul(W, x_data) + b
hypothesis = tf.matmul(W, x_data)
# Simplified cost function
cost = tf.reduce_mean(tf.square(hypothesis - y_data))

# Minimize
a = tf.Variable(0.1)  # Learning rate, alpha
optimizer = tf.train.GradientDescentOptimizer(a)
train = optimizer.minimize(cost)

# Before starting, initialize the variables. We will 'run' this first.
init = tf.global_variables_initializer()

# Launch the graph.
sess = tf.Session()
sess.run(init)

# Fit the line.
for step in range(2001):
    sess.run(train)
    if step % 20 == 0:
        print(step, sess.run(cost), sess.run(W))

# Learn best fit is W: [1 1 0]

복잡한 데이터를 코드 내부의 변수에 두지 않고 파일에서 바로 불러오는 방법을 배운다. numpy를 통해 불러온다. unpack이란 어떤 형태로 행을 잡을지 영향을 준다.

import tensorflow as tf
import numpy as np
# http://docs.scipy.org/doc/numpy-1.10.0/reference/generated/numpy.loadtxt.html
xy = np.loadtxt('train.txt', unpack=True, dtype='float32')
x_data = xy[0:-1]
y_data = xy[-1]

print('x', x_data)
print('y', y_data)

W = tf.Variable(tf.random_uniform([1, len(x_data), -5.0, 5.0]))

# Our hypothesis
hypothesis = tf.matmul(W, x_data)
# Simplified cost function
cost = tf.reduce_mean(tf.square(hypothesis - y_data))

# Minimize
a = tf.Variable(0.1)  # Learning rate, alpha
optimizer = tf.train.GradientDescentOptimizer(a)
train = optimizer.minimize(cost)

# Before starting
init = tf.global_variables_initializer()

sess = tf.Session()
sess.run(init)

# Fit the line
for step in range(2001):
    sess.run(train)
    if step % 20 == 0:
        print(step, sess.run(cost), sess.run(W))

# Learn best fit is W: [0.1], b: [0.3]