첨부 실행 코드는 나눔고딕코딩 폰트를 사용합니다.
유용한 소스 코드가 있으면 icodebroker@naver.com으로 보내주시면 감사합니다.
블로그 자료는 자유롭게 사용하세요.

■ 컨볼루션 신경망 만들기 (MNIST)

----------------------------------------------------------------------------------------------------

import tensorflow as tf

import tensorflow.examples.tutorials.mnist as mnist

 

imageSize              = 28

imageSizeSecondPooling = 7

batchSize              = 100

outputCount            = 10

learningRatio          = 0.001

epochCount             = 10

dropoutRatio           = 0.8

 

mnistDatasets = mnist.input_data.read_data_sets("data", one_hot = True)

 

inputTensor       = tf.placeholder(tf.float32, [None, imageSize, imageSize, 1])

rightOutputTensor = tf.placeholder(tf.float32, [None, outputCount])

 

dropoutTensor = tf.placeholder(tf.float32)

 

# Convolution Layer 1

weight1Variable = tf.Variable(tf.random_normal([4, 4, 1, 16], stddev = 0.01))

 

layer1OutputTensor = tf.nn.conv2d(inputTensor, weight1Variable, strides = [1, 1, 1, 1], padding = "SAME")

layer1OutputTensor = tf.nn.relu(layer1OutputTensor)

layer1OutputTensor = tf.nn.max_pool(layer1OutputTensor, ksize = [1, 2, 2, 1], strides = [1, 2, 2, 1], padding = "SAME")

 

# Convolution Layer 2

weight2Variable = tf.Variable(tf.random_normal([4, 4, 16, 32], stddev = 0.01))

 

layer2OutputTensor = tf.nn.conv2d(layer1OutputTensor, weight2Variable, strides = [1, 1, 1, 1], padding = "SAME")

layer2OutputTensor = tf.nn.relu(layer2OutputTensor)

layer2OutputTensor = tf.nn.max_pool(layer2OutputTensor, ksize = [1, 2, 2, 1], strides = [1, 2, 2, 1], padding = "SAME")

 

# Fully Connected Layer

weight3Variable = tf.Variable(tf.random_normal([imageSizeSecondPooling * imageSizeSecondPooling * 32, 256], stddev = 0.01))

 

layer3OutputTensor = tf.reshape(layer2OutputTensor, [-1, imageSizeSecondPooling * imageSizeSecondPooling * 32])

layer3OutputTensor = tf.matmul(layer3OutputTensor, weight3Variable)

layer3OutputTensor = tf.nn.relu(layer3OutputTensor)

layer3OutputTensor = tf.nn.dropout(layer3OutputTensor, dropoutTensor)

 

# Output Layer

weight4Variable = tf.Variable(tf.random_normal([256, outputCount], stddev = 0.01))

 

outputTensor = tf.matmul(layer3OutputTensor, weight4Variable)

 

costTensor = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits = outputTensor, labels = rightOutputTensor))

 

optimizerOperation = tf.train.AdamOptimizer(learningRatio).minimize(costTensor)

 

with tf.Session() as session:

    session.run(tf.global_variables_initializer())

    totalBatch = int(mnistDatasets.train.num_examples / batchSize)

    for epoch in range(epochCount):

        totalCost = 0

        for i in range(totalBatch):

            batchInputNDArray, batchRightOutputNDArray = mnistDatasets.train.next_batch(batchSize)

            batchInputNDArray = batchInputNDArray.reshape(-1, imageSize, imageSize, 1)

            _, cost = session.run([optimizerOperation, costTensor], feed_dict = {inputTensor : batchInputNDArray,\

                rightOutputTensor : batchRightOutputNDArray, dropoutTensor : dropoutRatio})

            totalCost += cost

        print("반복 : ", "%04d" % (epoch + 1), "평균 비용 : ", "{:.4f}".format(totalCost / totalBatch))

    print("학습 완료!")

 

    scoreTensor    = tf.equal(tf.argmax(outputTensor, 1), tf.argmax(rightOutputTensor, 1))

    accuracyTensor = tf.reduce_mean(tf.cast(scoreTensor, tf.float32))

 

    print("정확도 : ", session.run(accuracyTensor,\

        feed_dict = {inputTensor : mnistDatasets.test.images.reshape(-1, imageSize, imageSize, 1),\

        rightOutputTensor : mnistDatasets.test.labels, dropoutTensor : 1}))

----------------------------------------------------------------------------------------------------

Posted by 사용자 icodebroker

댓글을 달아 주세요