# -*- coding: utf-8 -*-
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
# 獲取mnist數據
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
# 注冊默認session 后面操作無需指定session 不同sesson之間的數據是獨立的
sess = tf.InteractiveSession()
# 構造參數W函數 給一些偏差0.1防止死亡節點
def weight_variable(shape):
??? initial = tf.truncated_normal(shape, stddev=0.1)
??? return tf.Variable(initial)
# 構造偏差b函數
def bias_variable(shape):
??? initial = tf.constant(0.1, shape=shape)
??? return tf.Variable(initial)
# x是輸入,W為卷積參數 如[5,5,1,30] 前兩個表示卷積核的尺寸
# 第三個表示通道channel 第四個表示提取多少類特征
# strides 表示卷積模板移動的步長都是 1代表不遺漏的劃過圖片每一個點
# padding 表示邊界處理方式這里的SAME代表給邊界加上padding讓輸出和輸入保持相同尺寸
def conv2d(x, W):
??? return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')
# ksize 使用2x2最大池化即將一個2x2像素塊變為1x1 最大池化保持像素最高的點
# stride也橫豎兩個方向為2歩長,如果步長為1 得到尺寸不變的圖片
def max_pool_2x2(x):
??? return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')
# 定義張量流輸入格式
# reshape變換張量shape 2維張量變4維 [None, 784] to [-1,28,28,1]
# -1表示樣本數量不固定 28 28為尺寸 1為通道
x = tf.placeholder(tf.float32, [None, 784])
y_ = tf.placeholder(tf.float32, [None, 10])
x_image = tf.reshape(x, [-1, 28, 28, 1])
# 第一次卷積池化 卷積層用ReLU激活函數
W_conv1 = weight_variable([5, 5, 1, 32])
b_conv1 = bias_variable([32])
h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1)