출처 : http://hunkim.github.io/ml/
ML lab 06-1: TensorFlow로 Softmax Classification의 구현하기
이론
- Softmax function은 여러개의 클래스를 예측할 때 유용하다.
- hypothesis를 통해 나온값을 softmax에 넣으면 확률로 나온다.
- cost 함수로 cross-entropy를 사용한다.
hypothesis, softmax 구현
hypothesis
softmax
hypothesis = tf.nn.softmax(tf.matmul(X, W) + b)
Cost function 구현
cost = tf.reduce_mean(-tf.reduce_sum(Y * tf.log(hypothesis), axis=1)) optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.1).minimize(cost)
전체 구현
- label은 one-hot encoding으로 표현
> tf.arg_max()를 사용하면 제일 높은값을 가지는 인덱스 리턴해줌
x_data = [[1, 2, 1, 1], [2, 1, 3, 2], [3, 1, 3, 4], [4, 1, 5, 5], [1, 7, 5, 5], [1, 2, 5, 6], [1, 6, 6, 6], [1, 7, 7, 7]]
y_data = [[0, 0, 1], [0, 0, 1], [0, 0, 1], [0, 1, 0], [0, 1, 0], [0, 1, 0], [1, 0, 0], [1, 0, 0]]
X = tf.placeholder(tf.float32, [None, 4])
Y = tf.placeholder(tf.float32, [None, 3])
nb_classes = 3
W = tf.Variable(tf.random_normal([4, nb_classes]), name='weight')
b = tf.Variable(tf.random_normal([np_classes]), name='bias')
# tf.nn.softmax computes softmax activations
# softmax = exp(Logits) / reduce_sum(exp(Logits), dim)
hypothesis = tf.nn.softmax(tf.matmul(X, W) + b)
# Cross entropy cost
cost = tf.reduce_mean(-tf.reduce_sum(Y * tf.log(hypothesis), axis=1))
optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.1).minimize(cost)
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
for step in range(2001):
sess.run(optimizer, feed_dict={X: x_data, Y: y_data})
if step % 200 == 0:
print(step, sess.run(cost, feed_dict={X: x_data, Y: y_data}))
Test & one-hot encoding
all = sess.run(hypothesis, feed_dict={X: [[1, 11, 7, 9],
[1, 3, 4, 3],
[1, 1, 0, 1]]})
print(all, sess.run(tf.arg_max(all, 1)))
ML lab 06-2: TensorFlow로 Fancy Softmax Classification의 구현하기
- cross-entropy, reshape, one-hot에 대한 구현
기존
logits = tf.matmul(X, W) + b hypothesis = tf.nn.softmax(logits) # Cross entropy cost/Loss cost = tf.reduce_mean(-tf.reduce_sum(Y * tf.log(hypothesis), axis=1))
함수사용
# Cross entropy cost/Loss cost_i = tf.nn.softmax_cross_entropy_with_logits(logits=logits, labels=Y_one_hot) cost = tf.reduce_mean(cost_i)
: 주의! hypothesis가 아닌 Logits을 넣어준다.
Animal classification
with softmax_cross_entropy_with_logits
- 0 ~ 6 숫자로 이루워진 Y를 one_hot으로 바꿔줘야함
- one_hot()에 N차원을 입력하면 N+1차원이 출력된다.
: [[0], [3]] => [[[1000000]]
[[0001000]]]
: 그래서 reshape 해줘야함
- tf.reshape()
tf.reshape(Y_one_hot, [-1, nb_classes])
: [[1000000], [0001000]]
(-1 : 알아서 해줘라)
xy = np.loadtxt('data-04-zoo.csv', delimiter=',', dtype=np.float32)
x_data = xy[:, 0:-1]
y_data = xy[:, [-1]]
np_classes = 7
X = tf.placeholder(tf.float32, [None, 16])
Y = tf.placeholder(tf.float32, [None, 1])
Y_one_hot = tf.one_hot(Y, np_classes)
Y_one_hot = tf.reshape(Y_one_hot, [-1, np_classes])
W = tf.Variable(tf.random_normal([16, np_classes]), name='weight')
b = tf.Variable(tf.random_normal([nb_classes]), name='bias')
# tf.nn.softmax computes softmax activations
# softmax = exp(Logits) / reduce_sum(exp(Logits), dim)
logits = tf.matmul(X, W) + b
hypothesis = tf.nn.softmax(logits)
# Cross entropy cost/Loss
cost_i = tf.nn.softmax_cross_entropy_with_logits(logits = logits, labels = Y_one_hot)
cost = tf.reduce_mean(cost_i)
optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.1).minimize(cost)
# 예측한 값이 맞는지 틀렸는지 판단하는 부분
prediction = tf.argmax(hypothesis, 1)
correct_prediction = tf.equal(prediction, tf.argmax(Y_one_hot, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
for step in range(2000):
sess.run(optimizer, feed_dict={X: x_data, Y: y_data})
if step % 100 == 0:
loss, acc = sess.run([cost, accuracy], feed_dict={X: x_data, Y: y_data})
print("Step: {:5}\tLoss: {:.3f}\tAcc: {.2%}".format(step, loss, acc))
pred = sess.run(prediction. feed_dict={X: x_data})
for p, y in zip(pred, y_data.flatten())
print("[{}] Prediction: {} True Y: {}".format(p == int(y), p, int(y)))
# .platten() : [[1], [0]] -> [1, 0]
# p와 y에 값 넘겨주기위해 zip으로 묶어줌
'Season.1 > BOOK] Deep learning from scratch' 카테고리의 다른 글
| 딥러닝의 기초 A to Z - 6 (0) | 2018.01.16 |
|---|---|
| 딥러닝의 기초 A to Z - 5 - 실습 (0) | 2018.01.15 |
| 딥러닝의 기초 A to Z - 5 (0) | 2018.01.15 |
| 딥러닝의 기초 A to Z - 4 - 실습 (0) | 2018.01.11 |
| 딥러닝의 기초 A to Z - 4 (0) | 2018.01.11 |