tensorfow mnist例子中的 mnist_deep.py,代码注释,作为学习记录

!/usr/bin/env python

load MNIST data

coding=UTF-8

-- coding: utf-8 -

import os
os.environ[“CUDA_VISIBLE_DEVICES”] = “1”

import input_data
mnist = input_data.read_data_sets(“Mnist_data/”, one_hot=True)

start tensorflow interactiveSession,

import tensorflow as tf
sess = tf.InteractiveSession()

weight initialization

def weight_variable(shape):
initial = tf.truncated_normal(shape, stddev=0.1)
return tf.Variable(initial)

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

convolution

def conv2d(x, W):
return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding=’SAME’)

pooling

def max_pool_2x2(x):
return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding=’SAME’)

Create the model

placeholder

x = tf.placeholder(“float”, [None, 784])
y_ = tf.placeholder(“float”, [None, 10])

variables

W = tf.Variable(tf.zeros([784,10]))
b = tf.Variable(tf.zeros([10]))

y = tf.nn.softmax(tf.matmul(x,W) + b)

first convolutinal layer

对于输入的2维图片,用5*5*1 ,进行卷积,进行32次

上述函数的初始化,就是,传入参数,函数调用

w_conv1 = weight_variable([5, 5, 1, 32])

偏差对应通道filter数量

b_conv1 = bias_variable([32])

任意数量的样本, 大小28*28 filter维度是1(一个通道)

输入是28*28*1 的图片(*3就是rgb图片了

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_2x2(h_conv1)

second convolutional layer

第二层卷积新的权重和偏差变量 5**5*32 64个

w_conv2 = weight_variable([5, 5, 32, 64])

第二层有64个输出 所以有64个偏差

b_conv2 = bias_variable([64])

然后第二层的reluctant输出,池化

h_conv2 = tf.nn.relu(conv2d(h_pool1, w_conv2) + b_conv2)
h_pool2 = max_pool_2x2(h_conv2)

自己添加一层,保持维度相同。1*1 和

w_conv3 = weight_variable ([1,1,64,64])
b_conv3 = bias_variable([64])
h_conv3 = tf.nn.relu(conv2d(h_pool2, w_conv3) + b_conv3)

densely connected layer

全连接层 输入是7*7*64 ,所以权重的数量7*7*64 ,一次得到一个结果

1024次,得到1024 个结果,所以 全连接层的参数数量很多 7*7*64 再*1024

w_fc1 = weight_variable([7*7*64, 1024])

偏差就是输出多少个,结果,,每个结果加上一个偏差

b_fc1 = bias_variable([1024])

上述只是定义全连接层的数量,下面是运算工程,reshape成一行向量,

然后不是卷积,是矩阵向量相乘,

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)

readout layer

w_fc2 = weight_variable([1024, 10])
b_fc2 = bias_variable([10])

y_conv = tf.nn.softmax(tf.matmul(h_fc1_drop, w_fc2) + b_fc2)

train and evaluate the model

交差熵也就是损失函数,最小化损失函数,找到最小化下的参数是什么

cross_entropy = -tf.reduce_sum(y_*tf.log(y_conv))
train_step = tf.train.GradientDescentOptimizer(1e-3).minimize(cross_entropy)

train_step = tf.train.AdagradOptimizer(1e-5).minimize(cross_entropy)

每张图片得出的十个分类结果 和和实际的标签的结果,如果最大值的位置一样,返回true

correct_prediction = tf.equal(tf.argmax(y_conv, 1), tf.argmax(y_, 1))

然后将所有图片的true false 变成数0 1,进行加平均,就得到了正确率

例如:[True, False, True, True]变为[1,0,1,1],计算出平均值为0.75。

accuracy = tf.reduce_mean(tf.cast(correct_prediction, “float”))

上述图都定义好了,是计算的步骤,以及数据变量,现在sess.run才是开始运行图的计算

batch 中 0表示图像数据 1表示 标签数据

sess.run(tf.initialize_all_variables())
for i in range(20000):
#next_batch函数,返回变量,为了下面储存输入数据
#return self._images[start:end], self._labels[start:end]
# 返回的batch其实是一个列表,0表示图像数据,1表示标签值。【 【】,【】】
# 传入训练数据,得到训练参数,权重值,偏差值。
batch = mnist.train.next_batch(50)
if i%100 == 0:
train_accuracy = accuracy.eval(feed_dict={x:batch[0], y_:batch[1], keep_prob:1.0})
print(“step %d, train accuracy %g” %(i, train_accuracy))
#上面是前向的计算
# 下面这句是训练权值,和偏差的,,梯度下降的反向传播,,
# 这样一轮训练结束,通过新的权值 和偏差值再进行 前向计算,然后通过损失函数,运行梯度下降改变权值偏差,
train_step.run(feed_dict={x:batch[0], y_:batch[1], keep_prob:0.5})

最后是对对测试图片和测试标签值以及给定的keep_prob 进行feed操作,进行计算求出识别率。

就相当于前面训练好的W和bias作为已知参数。

print(“test accuracy %g” % accuracy.eval(feed_dict={x:mnist.test.images, y_:mnist.test.labels, keep_prob:1.0}))

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值