Python Tensorflow 다중선형회귀
Tensorflow/ML
In [244]:
#필요한 모듈 세팅
import tensorflow as tf
import numpy as np
#텐서플로우 버전 확인
print(tf.__version__)
tf.random.set.seed()¶
tf.random.set.seed()에 대해 잠시 알아보겠습니다. 초기값을 지정해주는 역활을 합니다.
아래 예 2가지를 보면, tf.random.set.seed()를 지정하지 않았을땐 난수가 계속 생성되는데, tf.random.set.seed()를 지정하면, 난수가 고정되어 나오는 걸 확인 할 수있습니다.
In [245]:
for i in range(10):
a = tf.Variable(tf.random.uniform((1,), -1.0, 1.0))
b = tf.Variable(tf.random.uniform((1,), -1.0, 1.0))
print(a.numpy(),b.numpy())
In [246]:
for i in range(10):
tf.random.set_seed(0)
a = tf.Variable(tf.random.uniform((1,), -1.0, 1.0))
b = tf.Variable(tf.random.uniform((1,), -1.0, 1.0))
print(a.numpy(),b.numpy())
2변량 선형회귀 -1.변수 선언¶
In [247]:
# tf.random.set.seed()는 변수, 여기선 W1,W2값을 고정해 주는 역활을 합니다.
# 해당 코드를 몇번을 반복해도 같은 값을 돌려주게 됩니다.
tf.random.set_seed(0)
#변수 x1, x3 선언
x1_data = [5.,0.,3.,4.,5.]
x2_data = [4.,3.,1.,2.,0.]
#정답인 y값 선언
y_data = [1.,2.,3.,4.,5.]
2변량 선형회귀 -2.W초기값, learning_rate할당¶
In [248]:
#변수가 2개이기 때문에 W(가중치, 기울기)도 2개를 선언해 줍니다.
#tf.random.uniform 균등분포를 따르는 난수를 생성해줍니다, -10~10사이의수
W1 = tf.Variable(tf.random.uniform((1,), -10.0, 10.0))
W2 = tf.Variable(tf.random.uniform((1,), -10.0, 10.0))
b = tf.Variable(tf.random.uniform((1,), -10, 10.0))
learning_rate=tf.Variable(0.001)
2변량 선형회귀 -3.경사하강법으로 cost, W1,W2,b도출¶
In [249]:
#단순 선형회귀에서 사용한 경사하강법과 동일합니다.
for i in range(1000+1):
#tape에 모든 with연산기록 저장
with tf.GradientTape() as tape:
#hypothesis(추론,공식)을 전해줍니다.
hypothesis = W1 * x1_data + W2* x2_data+b
cost = tf.reduce_mean(tf.square(hypothesis - y_data))
W1_grad, W2_grad, b_grad = tape.gradient(cost, [W1,W2, b])
W1.assign_sub(learning_rate * W1_grad)
W2.assign_sub(learning_rate * W2_grad)
b.assign_sub(learning_rate * b_grad)
if i % 50 ==0:
print("{:5} | {:10.6f} | {:10.4f} | {:10.4f} | {:10.6f}".format(
i, cost.numpy(), W1.numpy()[0], W2.numpy()[0], b.numpy()[0]))
2변량 선형회귀(메트릭스)¶
In [250]:
#이번엔 같은 예제를 메트릭스를 활용하여 도출하겠습니다.
#메트릭스를 사용하지 않았을때(위예시)와 비교하면서 확인해야합니다.
#x와, y데이터를 따로따로 주었습니다.
x_data = [
[5.,0.,3.,4.,5.],
[4.,3.,1.,2.,0.]
]
y_data = [1.,2.,3.,4.,5.]
tf.random.set_seed(0)
W = tf.Variable(tf.random.uniform((1,2), -10.0, 10.0))
b = tf.Variable(tf.random.uniform((1,), -10.0, 10.0))
learning_rate = tf.Variable(0.001)
for i in range(1000+1):
with tf.GradientTape() as tape:
hypothesis = tf.matmul(W, x_data) + b
cost = tf.reduce_mean(tf.square(hypothesis - y_data))
W_grad, b_grad = tape.gradient(cost, [W, b])
W.assign_sub(learning_rate * W_grad)
b.assign_sub(learning_rate * b_grad)
if i % 50 ==0:
print("{:5} | {:10.6f} | {:10.4f} | {:10.4f} | {:10.6f}".format(
i, cost.numpy(), W.numpy()[0][0], W.numpy()[0][1], b.numpy()[0]))
3변량 단순 선형회귀¶
In [251]:
#값 고정 역활
tf.random.set_seed(0)
# 데이터 세팅
x1 = [ 60., 91., 78., 64., 74.]
x2 = [ 70., 87., 60., 80., 67.]
x3 = [ 73., 92., 93., 99., 71.]
Y = [130., 170., 160., 170., 150.]
# 변수만큼 w갯수 세팅
w1 = tf.Variable(tf.random.normal((1,)))
w2 = tf.Variable(tf.random.normal((1,)))
w3 = tf.Variable(tf.random.normal((1,)))
b = tf.Variable(tf.random.normal((1,)))
learning_rate = 0.000001
print("epoch | cost")
#경사하강법
for i in range(1000+1):
with tf.GradientTape() as tape:
hypothesis = w1* x1 + w2*x2 + w3*x3 + b
cost =tf.reduce_mean(tf.square(hypothesis -Y))
w1_grad, w2_grad, w3_grad, b_grad = tape.gradient(cost, [w1,w2,w3,b])
w1.assign_sub(learning_rate * w1_grad)
w2.assign_sub(learning_rate * w2_grad)
w3.assign_sub(learning_rate * w3_grad)
b.assign_sub(learning_rate * b_grad)
if i % 500 == 0:
print("{:5} | {:12.4f}".format(i, cost.numpy()))
3변량 단순 선형회귀(메트릭스)¶
In [252]:
#np배열로 x와 y 선언
data = np.array([
# X1, X2, X3, y
[ 60., 70., 73., 130. ],
[ 91., 87., 92., 170. ],
[ 78., 60., 93., 160. ],
[ 64., 80., 99., 170. ],
[ 74., 67., 71., 150. ]
], dtype=np.float32)
# 슬라이스로, 엑스와, y를 명확히 선언및 대입
X = data[:, :-1]
y = data[:, [-1]]
#x의 변수가 3개인것을 주의
W = tf.Variable(tf.random.normal((3, 1)))
b = tf.Variable(tf.random.normal((1,)))
learning_rate = 0.000001
# hypothesis, prediction function
def predict(X):
return tf.matmul(X, W) + b
print("epoch | cost")
n_epochs = 1000
for i in range(n_epochs+1):
# tf.GradientTape() to record the gradient of the cost function
with tf.GradientTape() as tape:
cost = tf.reduce_mean((tf.square(predict(X) - y)))
# calculates the gradients of the loss
W_grad, b_grad = tape.gradient(cost, [W, b])
# updates parameters (W and b)
W.assign_sub(learning_rate * W_grad)
b.assign_sub(learning_rate * b_grad)
if i % 50 ==0:
print("{:5} | {:10.6f} | {:10.4f} | {:10.4f} | {:10.6f}".format(
i, cost.numpy(), W.numpy()[0][0], W.numpy()[1][0], b.numpy()[0]))
다변량 선형회귀 요약¶
다변량 선형회귀는 변수를 직접 선언하는것과, 메트릭스를 통해 선언 하는 두가지 방법이 있다.
전자는 변수가 많을 경우 하나하나 모두 세팅을 해줘야하는 반면,
후자는 변수가 많아도 메트릭스를 사용해 한번만 세팅이 가능하다.
더 빠른 결과, 정확도가 높은 결과를 도출 할 수있다.
다변량 선형회귀 확인 및 예측(바로 위 예제를 통한)¶
In [253]:
#y값 확인
y
Out[253]:
In [254]:
#X값 확인
X
Out[254]:
In [255]:
#b값 확인
b
Out[255]:
def predict(X): return tf.matmul(X, W) + b
In [256]:
#predict공식을 통한 해 도출
predict(X).numpy()
Out[256]:
In [257]:
#x1,x2,x3값 할당한 후 예측값
predict([[ 1., 1., 4.]]).numpy()
Out[257]:
In [258]:
#2개의 해 동시 도출
predict([[ 1., 1., 4.],[ 145., 50., 50.]]).numpy()
Out[258]:
In [259]:
#3개의 해 동시 도출
#특히 마지막 배열은 최초 선언시 주었던 x값임
predict([[ 1., 1., 4.],[ 145., 50., 50.],[ 74., 67., 71.]]).numpy()
Out[259]:
해당 포스팅은 부스트코스 강의와, 텐서플로우공식 홈페이지를 참고하여 작성하였습니다.
In [ ]:
'Tensorflow > ML' 카테고리의 다른 글
Tensorflow 다중선형회귀 공부 (0) | 2020.08.07 |
---|---|
Python Logistic Regression (0) | 2020.07.28 |
Python Tensorflow 단순선형회귀 (0) | 2020.07.20 |