1. 程式人生 > >TensorFlow CNN

TensorFlow CNN

import cv2 as cv
import numpy as np
import os
from tensorflow.examples.tutorials.mnist import input_data
import scipy.misc
import tensorflow as tf
import matplotlib.pyplot as plt


mnist = input_data.read_data_sets('MNIST_data/', one_hot=True)
x = tf.placeholder(tf.float32, [None, 784])
y_label = tf.placeholder(tf.float32, [None, 10])
#   batch*width*height*channel
x_image = tf.reshape(x, [-1, 28, 28, 1])

# 隨機產生權值var
def weight_var(shape):
    initial = tf.truncated_normal(shape, stddev=0.1)
    return tf.Variable(initial)


def bias_var(shape):
    initial = tf.constant(0.1, shape=shape)
    return tf.Variable(initial)

#  W: [filter_height, filter_width, in_channels, out_channels]
#  x: [batch, in_height, in_width, in_channels]
#  define convolution
def con2d(x, W):
    return tf.nn.conv2d(x, W, [1, 1, 1, 1], padding='SAME')


def max_pool2(x):
    return tf.nn.max_pool(x, [1, 2, 2, 1], [1, 2, 2, 1], padding='SAME')


#  卷積,relu, pooling
w_conv1 = weight_var([5, 5, 1, 32])
b_conv1 = bias_var([32])
pooling1 = max_pool2(tf.nn.relu(con2d(x_image, w_conv1)+b_conv1))

w_conv2 = weight_var([5, 5, 32, 64])
b_conv2 = bias_var([64])
pooling2 = max_pool2(tf.nn.relu(con2d(pooling1, w_conv2)+b_conv2))


#  full connected
w_fc1 = weight_var([7*7*64, 1024])
b_fc1 = bias_var([1024])
#  卷積後攤平成二維, 經過隱含全連線層
pooling2_flat = tf.reshape(pooling2, [-1, 7*7*64])
fc1_out = tf.nn.relu(tf.matmul(pooling2_flat, w_fc1)+b_fc1)

keep_prob = tf.placeholder(tf.float32)
fc1_drop_out = tf.nn.dropout(fc1_out, keep_prob)
#  輸出層
w_fc2 = weight_var([1024, 10])
b_fc2 = bias_var([10])
fc2_out = tf.matmul(fc1_drop_out, w_fc2)+b_fc2

#  一般步驟為:使用softmax轉換為概率, 再定義交叉熵損失
#  這裡合為一步 This op expects unscaled logits, since it performs a `softmax` on `logits` internally for efficiency
#  logits: Unscaled log probabilities.
cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y_label, logits=fc2_out))
train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)

correct_pred = tf.equal(tf.argmax(fc2_out, 1), tf.argmax(y_label, 1))
accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))

with tf.Session() as sess:
    sess.run(tf.initialize_all_variables())
    for i in range(500):
        batch = mnist.train.next_batch(50)
        sess.run(train_step, {x: batch[0], y_label: batch[1], keep_prob: 0.5})
        if i % 20 == 0:
            train_acc = sess.run(accuracy, {x: batch[0], y_label:batch[1], keep_prob: 0.5})
            print(train_acc)

    print("final error %g" % sess.run(accuracy, {x: mnist.test.images, y_label: mnist.test.labels, keep_prob: 1}))