일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 | 31 |
- flask
- 파이썬
- R
- 오버로그
- rstudio
- Data Analysis
- 오버워치
- Rfacebook
- Python
- TensorFlow
- 파이썬3
- Web Programming
- rcv
- webcrawling
- Programming
- Cssselector
- Crawling
- python3
- Ajou University
- Server
- ajoubamboo
- mongoDB
- Barplot
- 웹크롤링
- 머신러닝
- 크롤링
- 선형회귀
- Linear Regression
- chaining
- web
- Today
- Total
R is well
[파이썬3 머신러닝] Machine Learning Basic and Linear Regression with Python Tensorflow 본문
[파이썬3 머신러닝] Machine Learning Basic and Linear Regression with Python Tensorflow
Sanghou 2018. 1. 12. 12:31Machine Learning Study Week1¶
: Lec 0 ~ 4¶
2017년 12월 27일 안상호¶
머신러닝, 텐서 플로우, 선형회귀
목차¶
- Lec00 & Lec01: 머신러닝의 기본 + TensorFlow 기초
- Lec02: 선형회귀 기초
- Lec03: Cost 최소화 알고리즘
- Lec04: 다변수 선형 회귀
- Optional: Feature Scaling and Normal Equation
Lec00: 머신러닝 OT¶
Lec01: 머신러닝의 기본¶
Tensorflow의 설치 및 기본적인 operations¶
- TensorFlow란?
edges와 nodes로 구조화된 graph로 프로그램이 구성
여기서 nodes는 어떤 동작이 일어나는지에 관한 operation이고 (쉽게 말해 함수)
edges는 이러한 nodes를 동작시키기 위한 Data, Tensor이다.
Data가 여러 Operation 들을 통해 연결되고 연산됨을 생각해보며 밑의 예제들을 풀어나가보자
1.1. Hello TensorFlow!¶
- Check installation and version
import tensorflow as tf
tf.__version__
- 역시 프로그래밍은 "Hello, World" 부터 시작!
hello = tf.constant("Hello, TensorFlow!") ### hello라는 node
# start a TF session
sess = tf.Session()
# run the op and get result
print(sess.run(hello))
1.2. Computational Graph¶
TensorFlow로 코딩을 하면 크게 3단계로 나누어진다.
- Init: 처음에 변수를 만들어 주는 단계
- Build: 만들어진 변수들을 통해 모델을 만드는 단계
- Run: 만들어진 모델에 데이터를 주어서 실행 or 그냥 실행
밑의 예제를 통해서는 텐서플로우가 어떠한 방법을 거쳐서 결과를 내는지를 보도록하자
P.S. 강의에서는 Build -> Feed&Run -> Update 순이다 ML lab01
1.2.1. Build graph(tensors) using TensorFlow operations¶
node1 = tf.constant(3.0, tf.float32)
node2 = tf.constant(4.0) # also tf.float32 implicitly
node3 = tf.add(node1, node2)
print("node1:", node1, "node2:", node2)
print("node3: ", node3)
sess = tf.Session()
print("sess.run(node1, node2): ", sess.run([node1, node2]))
print("sess.run(node3): ", sess.run(node3))
1.3. Data Type¶
텐서플로우는 뉴럴네트워크에 최적화되어 있는 개발 프레임웤이기 때문에, 그 자료형과, 실행 방식이 약간 일반적인 프로그래밍 방식과 상이하다. 그래서 삽질(?)을 많이했다
1.3.1. 상수형 (Constant)¶
간단히 말해서 상수인 값들을 할당한다
- tf.constant(value, dtype=None, shape=None, name='Const', verify_shape=False)
- value: 상수 값
- dtype: 저장되는 데이터 타입. tf.float32와 같이 실수, 정수 등의 데이터 타입을 정의한다.
- shape: 행렬 차원 정의! m by n 행렬
- name: 상수의 이름을 정의한다.
# Build
node1 = tf.constant(3.0, tf.float32)
# Run
sess = tf.Session()
print("sess.run(node1): {}".format(sess.run(node1)))
1.3.2. 플레이스 홀더 (Placeholder)¶
간단히 말해 빈 변수를 만들어주고, 값이 입력 되기를 기다리는 것이다!
이렇게 해서 모델을 먼저 만들고나면 어떤 값이든 부여할 수 있게 된다.
즉, 학습을 위한 학습용 데이터 타입!
- tf.tf.placeholder(dtype,shape,name)
- dytpe: 저장되는 데이터 타입
- shape: 행렬 차원 정의! m by n 행렬
- name: placeholder의 이름
# Build
node_data1 = 3.0
node_data2 = 1.0
node1 = tf.placeholder(tf.float32)
# Run
sess = tf.Session()
print("sess.run(node1): {}".format(sess.run(node1, feed_dict={node1: node_data1})))
print("sess.run(node1): {}".format(sess.run(node1, feed_dict={node1: node_data2})))
feed_dict
로 데이터를 할당해주는 것에 주목하자
1.3.3. 변수형 (Variable)¶
모델을 통한 학습이 진행될 때, 계속해서 값을
업데이트하는 식으로 바꾸어주어야 하는 값들이 있다.
그 변수들을 위한 자료형!
trainable
값, 즉 학습시 tensorflow가 변경 가능한 값
- tf.Variable.init(initial_value=None, trainable=True, collections=None, validate_shape=True, caching_device=None, name=None, variable_def=None, dtype=None, expected_shape=None, import_scope=None)
node_data = [1,2,3,4,5]
x = tf.placeholder(dtype=tf.float32)
W = tf.Variable([2],dtype=tf.float32)
y = W*x
sess = tf.Session()
sess.run(tf.global_variables_initializer())
result = sess.run(y,feed_dict={x:node_data})
print(result)
밑에서 학습에 따라 변화하는 W를 보도록 하자
Lec02: 선형 회귀 (Linear Regression) 기초¶
TensorFlow로 간단한 linear regression을 구현¶
상관 관계에 관해서는 다들 한번씩 들어보았을 것이다. 그렇지만 두변수가 높은 상관 관계를 보이고 있다고 해서 이것들 간에 인과관계가 있는 것은 아니다. 바로 이 회귀 분석 방법이 인과관계를 찾아가는 과정이라고 생각하면 된다. 다음과 같은 Step을 따른다.
Step1: 가설 설정 -
Hypothesis
(Build)Step2: 비용 계산식 설정 -
Cost
(Build)Step3: 비용 최소화식 설정 -
Gradient Descent
(Build)Step4: 실행 (Run)
2.1. Hypothesis 설정¶
- Def
- X에 대한 Y 값을 예측해주는 가설
import tensorflow as tf
tf.set_random_seed(777) # 재연을 위한 난수표
# X and Y data
x_train = [1, 2, 3]
y_train = [1, 2, 3]
W = tf.Variable(tf.random_normal([1]), name= 'Weight')
b = tf.Variable(tf.random_normal([1]), name= 'bias')
hypothesis = x_train*W + b
# cost/loss function
cost = tf.reduce_mean(tf.square(hypothesis - y_train))
# Minimize
optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.01)
train = optimizer.minimize(cost)
2.4. Run¶
# Launch the graph in a session.
sess = tf.Session()
# Initializes global variables in the graph.
sess.run(tf.global_variables_initializer())
- 세션 열고
tf.global_variables_initializer()
: 변수형과 세트! 그래프를 실행하기 전에 초기화하여 W에 지정한 값이 변수에 지정되도록 한다
# Fit the line
for step in range(2001):
sess.run(train)
if step % 200 == 0:
print("Stpe: {}, Cost: {}, Weight: {}, bias: {}".format(step, sess.run(cost), sess.run(W), sess.run(b)))
200번의 연산마다 Cost, Weight, bias 순으로 출력해보았다.
데이터 셋에서 생각할 수 있는
가 로 거의 근사 값에 도달 했음을 알 수 있다.
Placeholder Version¶
W = tf.Variable(tf.random_normal([1]), name= 'Weight')
b = tf.Variable(tf.random_normal([1]), name= 'bias')
X = tf.placeholder(tf.float32, shape=[None]) ### shope = None 무슨 값들어와도 상관 없음
y = tf.placeholder(tf.float32, shape=[None])
hypothesis = X*W + b
cost = tf.reduce_mean(tf.square(hypothesis - y))
optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.01)
train = optimizer.minimize(cost)
sess = tf.Session()
# Initializes global variables in the graph.
sess.run(tf.global_variables_initializer())
for step in range(2001):
cost_val, W_val, b_val, _ = sess.run([cost, W, b, train], feed_dict = {X: [1,2,3,4,5], y: [2.1,3.1,4.1,5.1,6.1]})
if step % 200 == 0:
print(step, cost_val, W_val, b_val)
이 으로 거의 근사 값에 도달 했음을 알 수 있다.
Test out model¶
print(sess.run(hypothesis, feed_dict = {X: [5]}))
print(sess.run(hypothesis, feed_dict = {X: [2.5]}))
print(sess.run(hypothesis, feed_dict = {X: [1.5, 3.5]}))
import tensorflow as tf
import matplotlib.pyplot as plt
tf.set_random_seed(777) # for reproducibility
X = [1, 2, 3]
Y = [1, 2, 3]
W = tf.placeholder(tf.float32)
# Our hypothesis for linear model X * W
hypothesis = X * W
# cost/loss function
cost = tf.reduce_mean(tf.square(hypothesis - Y))
# Launch the graph in a session.
sess = tf.Session()
# Variables for plotting cost function
W_history = []
cost_history = []
for i in range(-30, 50):
curr_W = i * 0.1
curr_cost = sess.run(cost, feed_dict={W: curr_W})
W_history.append(curr_W)
cost_history.append(curr_cost)
# Show the cost function
%matplotlib inline
plt.plot(W_history, cost_history)
plt.show()
3.1. Build - Init¶
tf.set_random_seed(777) # for reproducibility
x_data = [1, 2, 3]
y_data = [1, 2, 3]
W = tf.Variable(tf.random_normal([1]), name= 'Weight')
X = tf.placeholder(tf.float32)
Y = tf.placeholder(tf.float32)
cost = tf.reduce_mean(tf.square(W*X - Y))
3.2. Build - Minimize¶
# Minimize: Gradient Descent using derivative: W -= learning_rate * derivative
learning_rate = 0.1
gradient = tf.reduce_mean((W * X - Y) * X)
descent = W - learning_rate * gradient
update = W.assign(descent)
3.3. Run - Graph¶
# Launch the graph in a session.
sess = tf.Session()
# Initializes global variables in the graph.
sess.run(tf.global_variables_initializer())
for step in range(21):
sess.run(update, feed_dict={X: x_data, Y: y_data})
print(step, sess.run(cost, feed_dict={X: x_data, Y: y_data}), sess.run(W))
3.4. GradientDescentOptimizer 사용¶
tf.set_random_seed(777) # for reproducibility
x_data = [1, 2, 3]
y_data = [1, 2, 3]
# W = tf.Variable(tf.random_normal([1]), name= 'Weight')
W = tf.Variable(-300.0)
X = tf.placeholder(tf.float32)
Y = tf.placeholder(tf.float32)
cost = tf.reduce_mean(tf.square(W*X - Y))
optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.1)
train = optimizer.minimize(cost)
# Launch the graph in a session.
sess = tf.Session()
# Initializes global variables in the graph.
sess.run(tf.global_variables_initializer())
for step in range(21):
print(step, sess.run(W))
sess.run(train, feed_dict={X: x_data, Y: y_data})
# sess.run(train, feed_dict={X: x_data, Y: y_data})
# print(step, sess.run(cost, feed_dict={X: x_data, Y: y_data}), sess.run(W))
Quiz!¶
다들 강의에서 외부에 있는 데이터를 가져오는 방법은 배우셨을 것입니다!
다들 새로운 데이터를 가지고 회귀모델을 만들어 보도록합시다.
준비한 데이터에 관한 설명입니다.
The first column is the population of a city
the second column is the profit of a food truck in that city.
이제 아래 질문에 대한 답을 찾아주세요!
import tensorflow as tf
import numpy as np
tf.set_random_seed(777)
# Data Load
data = np.loadtxt('data/ex1data1.txt', delimiter=',')
X_data = data[:,0]
y_data = data[:,1]
R
로 치면ggplot2
와 비슷한matplotlib
으로 데이터의 시각화를 해보십니다.
import matplotlib.pyplot as plt
plt.scatter(X_data, y_data, s=30, c='r', marker='x', linewidths=1)
plt.xlim(4,24)
plt.xlabel('Population of City in 10,000s')
plt.ylabel('Profit in $10,000s')
- 위 데이터에 적합한 Weight와 bias를 구하시오
### Your Code
- 인구 값이
6.1101
일 때 푸드트럭의 예상 수익은 얼마입니까?
### Your Code
import tensorflow as tf
tf.set_random_seed(777) # for reproducibility
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.]
# placeholders for a tensor that will be always fed.
x1 = tf.placeholder(tf.float32)
x2 = tf.placeholder(tf.float32)
x3 = tf.placeholder(tf.float32)
Y = tf.placeholder(tf.float32)
w1 = tf.Variable(tf.random_normal([1]), name='weight1')
w2 = tf.Variable(tf.random_normal([1]), name='weight2')
w3 = tf.Variable(tf.random_normal([1]), name='weight3')
b = tf.Variable(tf.random_normal([1]), name='bias')
hypothesis = x1 * w1 + x2 * w2 + x3 * w3 + b
print(hypothesis)
4.1.2. Build - minimize¶
# cost/loss function
cost = tf.reduce_mean(tf.square(hypothesis - Y))
# Minimize. Need a very small learning rate for this data set
optimizer = tf.train.GradientDescentOptimizer(learning_rate=1e-5)
train = optimizer.minimize(cost)
4.1.3. Run - Graph¶
# Launch the graph in a session.
sess = tf.Session()
# Initializes global variables in the graph.
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 % 200 == 0:
print("Step: {} Cost: {} \nPrediction:\n {} Weight: {} | {} | {}".format(step, cost_val, hy_val, sess.run(w1), sess.run(w2), sess.run(w3)))
x_data = [[73., 80., 75.],
[93., 88., 93.],
[89., 91., 90.],
[96., 98., 100.],
[73., 66., 70.]]
y_data = [[152.],
[185.],
[180.],
[196.],
[142.]]
# placeholders for a tensor that will be always fed.
X = tf.placeholder(tf.float32, shape=[None, 3]) ### n X 3
Y = tf.placeholder(tf.float32, shape=[None, 1]) ### n X 1
W = tf.Variable(tf.random_normal([3, 1]), name='weight') ### (n X 3) X () = (n X 1)
b = tf.Variable(tf.random_normal([1]), name='bias')
# Hypothesis
hypothesis = tf.matmul(X, W) + b
위에서 x1
, x2
, x3
로 표시되던 column들이 행렬 형태로 묶여 있는 것을 확인할 수 있다.
4.2.2. Build - minimize¶
# Simplified cost/loss function
cost = tf.reduce_mean(tf.square(hypothesis - Y))
# Minimize
optimizer = tf.train.GradientDescentOptimizer(learning_rate=1e-5)
train = optimizer.minimize(cost)
4.2.3. Run - Graph¶
# Launch the graph in a session.
sess = tf.Session()
# Initializes global variables in the graph.
sess.run(tf.global_variables_initializer())
for step in range(2001):
cost_val, hy_val, _ = sess.run(
[cost, hypothesis, train], feed_dict={X: x_data, Y: y_data})
if step % 200 == 0:
print("{} Cost: {} \nPrediction:\n {}".format(step, cost_val, hy_val))
sess.run(hypothesis, feed_dict={X: x_data})
[[152.], [185.], [180.], [196.], [142.]]
Quiz!¶
당연히 이번에도 있겠죠!
다들 새로운 데이터를 가지고 다변수 선형 회귀모델을 만들어 보도록합시다.
준비한 데이터에 관한 설명입니다.
The first column is the size of the house (in square feet)
the second column is the number of bedrooms
the third column is the price of the house.
이제 아래 질문에 대한 답을 찾아주세요!
- 위 데이터에 적합한 Weight와 bias를 구하시오
### Your Code
- 평방 미터 제곱 값이
2104
, 방의 갯수가3
일 때 에측되는 집값은 얼마입니까?
### Your Code
고생하셨습니다!¶
Optional: Feature Scaling and Normal Equation¶
5.1. Feature Scaling¶
위의 퀴즈에서 본 것처럼 집 평방 미터 제곱 값과 방의 갯수에 관한 두 Feature는 매우 상이한 범위를 가지고 있다. 그래서 Gradient Descent 방법에서 상당히 많은 시간을 요구하게 된다. 그래서 사용하는 방법이 바로 Feature Scaling 이다. 상이한 범위를 가진 데이터들의 범위를 같게 만들어 주어서 더욱 빠르게 수렴하도록 만든다.
스케일링 해주는 방법은 데이터들을 각각 해당 열의 평균에서 뺀 값을 해당 열의 표준편차로 나누어주는 방법이 대표적이다. 혹은 최댓 값에서 최솟값을 빼준 값으로 나누어 주어도 무방하다.
5.1.1. 데이터 load¶
import tensorflow as tf
import numpy as np
tf.set_random_seed(777)
# Data Load
data = np.loadtxt('data/ex1data2.txt', delimiter=',')
X_data = data[:,0:-1]
y_data = data[:,[-1]]
# y_data = data[:,-1] 차이는 47로 구성된 벡터냐, 아니면 47X1 행렬이냐
print(X_data.shape, y_data.shape)
5.1.2. Feature Sacaling 함수¶
- X의 평균 값 리스트와 표준편차 리스트도 함께 반환
from __future__ import division
def FeatureScale(data):
data_shape = data.shape
data_mean, data_std = [], []
data_norm = np.zeros(data_shape)
for i in range(data_shape[1]):
data_i = data[:,i]
m = data_i.mean()
s = data_i.std()
data_norm[:,i] = (data_i - m)/(s)
data_mean.append(m)
data_std.append(s)
return data_norm, data_mean, data_std
# (X_data - X_data.mean())/X_data.std()
X_norm, X_mean, X_std = FeatureScale(X_data)
y_norm, y_mean, y_std = FeatureScale(y_data)
5.1.3. 학습¶
X = tf.placeholder(tf.float32, shape = [None, 2])
y = tf.placeholder(tf.float32, shape = [None, 1])
W = tf.Variable(tf.random_normal([2, 1]), name= 'Weight')
b = tf.Variable(tf.random_normal([1]), name= 'bias')
# Build
h = tf.matmul(X, W) + b
cost = tf.reduce_mean(tf.square(h - y))
# 3e-3
# 1e-10
optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.01)
train = optimizer.minimize(cost)
# Run
sess = tf.Session()
sess.run(tf.global_variables_initializer())
for step in range(2001):
sess.run(train, feed_dict= {X: X_norm, y: y_norm})
if step % 200 == 0:
print(step, sess.run(W), sess.run(b), sess.run(cost, feed_dict= {X: X_norm, y: y_norm}))
5.1.4. Prediction¶
- input 값을 Feature Scaling 형태로 입력
# Build
X_test = np.array([[2104, 3]])
X_test= (X_test- X_mean)/X_std
print(X_test)
# Run
print(sess.run(h, feed_dict= {X: X_test} ), sess.run(W))
- Prediction 값이 스케일링 되어 있으므로, 다시 원 값으로 돌림
prediction = 0.12829466*y_std[0] + y_mean[0]
# prediction - 399900
prediction
5.2. Normal Equation¶
행렬의 역행렬을 이용하면 Gradient Descent 없이도 바로 Weight 값을 구할 수 있다는 놀라운 사실
하지만 n^3의 컴퓨팅 파워가 소모
import numpy as np
data = np.loadtxt('data/ex1data2.txt', delimiter=',')
X_data = data[:,0:-1] ### 47 X 3 -> Transpose 3 X 47
y_data = data[:,[-1]]
# x_data = np.array([[73., 80., 75.],
# [93., 88., 93.],
# [89., 91., 90.],
# [96., 98., 100.],
# [73., 66., 70.]])
# y_data = np.array([[152.],
# [185.],
# [180.],
# [196.],
# [142.]])
x_inv = np.linalg.pinv(X_data)
# theta = x_inv.dot(y_data)
theta = np.linalg.pinv(X_data.T.dot(X_data)).dot(X_data.T.dot(y_data))
np.array([[2014, 3]]).dot(theta)
'프로그래밍 > Python' 카테고리의 다른 글
[파이썬3 웹프로그래밍] Flask & MongoDB 응용 (2) | 2017.10.11 |
---|---|
[파이썬3 웹프로그래밍] Flask & MongoDB 입문 (0) | 2017.10.11 |
[파이썬3 웹크롤링] Python3 Webcrawling with BeautifulSoup (23) | 2016.11.18 |
[파이썬3 웹크롤링] Python3 Webcrawling Basic with Cssselector (2) | 2016.11.18 |