if __name__ == "__main__":
#输入与输出
x = tf.placeholder("float", shape = [None, 784])#输入占位符(每张手写数字28*28个像素点)
y_ = tf.placeholder("float", shape = [None, 10])#输入占位符(这张手写数字具体代表的值,0-9对应矩阵的10个位置)
#初始化权重,第一层卷积,32的意思代表的是输出32个通道
# 其实,也就是设置32个卷积,每一个卷积都会对图像进行卷积操作
w_conv1 = weight_variable([5,5,1,32])
#初始化偏置项
b_conv1 = bias_variable([32])
#将输入的x转成一个4D向量,第2、3维对应图片的宽高,最后一维代表图片的颜色通道数
# 输入的图像为灰度图,所以通道数为1,如果是RGB图,通道数为3
# tf.reshape(x,[-1,28,28,1])的意思是将x自动转换成28*28*1的数组
# -1的意思是代表不知道x的shape,它会按照后面的设置进行转换
x_image = tf.reshape(x,[-1,28,28,1])
# 卷积并激活
h_conv1 = tf.nn.relu(conv2d(x_image,w_conv1) + b_conv1)
#池化
h_pool1 = max_pool_2_2(h_conv1)
#第二层卷积
#初始权重
w_conv2 = weight_variable([5,5,32,64])
#初始化偏置项
b_conv2 = bias_variable([64])
#将第一层卷积池化后的结果作为第二层卷积的输入
h_conv2 = tf.nn.relu(conv2d(h_pool1,w_conv2) + b_conv2)
#池化
h_pool2 = max_pool_2_2(h_conv2)
# 设置全连接层的权重
w_fc1 = weight_variable([7*7*64,1024])
# 设置全连接层的偏置
b_fc1 = bias_variable([1024])
# 将第二层卷积池化后的结果,转成一个7*7*64的数组
h_pool2_flat = tf.reshape(h_pool2,[-1,7*7*64])
# 通过全连接之后并激活
h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat,w_fc1) + b_fc1)
#dropout层
keep_prob = tf.placeholder("float")
h_fc1_drop = tf.nn.dropout(h_fc1,keep_prob)
#第二个全连接层
w_fc2 = weight_variable([1024,10])
b_fc2 = bias_variable([10])
#最后一层输出
y = tf.matmul(h_fc1_drop,w_fc2) + b_fc2
#网络迭代,交叉熵损失
crossEntropyLoss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels = y_, logits = y))
trainStep = tf.train.AdamOptimizer().minimize(crossEntropyLoss)
correct_prediction = tf.equal(tf.argmax(y,1), tf.argmax(y_,1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction,"float"))
# 初始化变量
init = tf.global_variables_initializer()
sess = tf.Session()
sess.run(init)