TensotFlow 응용 예: 09-classification 분류기

3114 단어
TensotFlow 응용 예: 09-classification 분류기
본고는 제가 Tensot Flow를 공부할 때 기록한 노트입니다. 필요한 분들을 도와주셨으면 좋겠습니다.
classification은 분류기로서 분류의 문제를 해결하는 데 사용된다. 이전의 예에서 모두 선형 회귀의 문제나 비선형 데이터이다. 입력과 출력은 한 (조) 대 한 (조)의 수치이다. 이전에는 모두 연속적인 데이터이고 출력은 같은 조의 연속적인 데이터이다.
classification은 일부 분류의 문제이다. 입력한 것은 하나의 데이터이고 출력의 결과는 하나의 확률이다. 전체 확률의 값을 더하면 결과는 1이고 가장 가까운 값을 선택하여 출력의 결과로 할 수 있다.
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data


# classification          
#                   ,       ,       ( )  ( )   
#             

# classification        ,        ,          ,        
#    1,       1         

# number 1 to 10 image data
#             ,    ,       
# MNIST_data            
mnist = input_data.read_data_sets('MNIST_data', one_hot=True)

#      
def add_layer(inputs, in_size, out_size, activation_function=None):
    # Weights define
    #   ,          
    #                           
    Weights = tf.Variable(tf.random_normal([in_size, out_size]))
    # biases define
    #    ,     ,    ,     0 + 0.1
    biases = tf.Variable(tf.zeros([1, out_size]) + 0.1)
    # W * x + b
    Wx_plus_b = tf.matmul(inputs, Weights) + biases
    #   activation_function                     
    if activation_function is None:
        outputs = Wx_plus_b
    else:
        outputs = activation_function(Wx_plus_b)
    return outputs


#      
# compute_accuracy    
def compute_accuracy(v_xs, v_ys):
    global prediction
    #
    y_pre = sess.run(prediction, feed_dict={xs: v_xs})
    correct_prediction = tf.equal(tf.argmax(y_pre, 1), tf.argmax(v_ys, 1))
    accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
    # result       ,          
    result = sess.run(accuracy, feed_dict={xs: v_xs, ys: v_ys})
    return result

# define placeholder for inputs to network
#      28*28      28 * 28 = 784
#      0 9       
#      float32
# None         sample,       
xs = tf.placeholder(tf.float32, [None, 784])
ys = tf.placeholder(tf.float32, [None, 10])

# add output layer
# activation_function    softmax
# softmax          
# prediction    ,   1*10     
prediction = add_layer(xs, 784, 10,  activation_function=tf.nn.softmax)

# the error between prediction and real data
# loss function
# cross_entropy          softmax + cross_entropy    
cross_entropy = tf.reduce_mean(-tf.reduce_sum(ys * tf.log(prediction),
                                              reduction_indices=[1]))
train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)

sess = tf.Session()

# important step
# tf.initialize_all_variables() no long valid from
# "2017-03-02", "Use `tf.global_variables_initializer` instead."
init = tf.global_variables_initializer()
sess.run(init)


for i in range(1000):
    #            100     
    #                
    #                   

    batch_xs, batch_ys = mnist.train.next_batch(100)
    sess.run(train_step, feed_dict={xs: batch_xs, ys: batch_ys})
    if i % 50 == 0:
        print(compute_accuracy(mnist.test.images, mnist.test.labels))



본문 코드 GitHub 주소 tensorflowlearning_notes

좋은 웹페이지 즐겨찾기