import tensorflow as tf
from datetime import datetime
import math
import time
batch_size = 12
num_batches = 100
def myprint(conv):
# print(conv.op.name, ' ', conv.get_shape().as_list())
str1 = str(conv.op.name) + ' ' + str(conv.get_shape().as_list()) + "\n"
f = open('test.txt', 'a') # 若是'wb'就表示写二进制文件
f.write(str1)
f.close()
def conv_op(input, name, kernel_h, kernel_w, num_out, step_h, step_w, para):
# 获取输入图像的通道
init = tf.contrib.layers.xavier_initializer_conv2d()
num_in = input.get_shape()[-1].value
with tf.name_scope(name) as scope:
kernel = tf.get_variable(scope + "w" , shape=[kernel_h, kernel_w, num_in, num_out], dtype=tf.float32, initializer=init)
conv = tf.nn.conv2d(input, kernel, (1, step_h, step_w,1),padding="SAME")
biases = tf.Variable(tf.constant(0.0, shape=[num_out], dtype=tf.float32), trainable=True, name="b")
avtivation = tf.nn.relu(tf.nn.bias_add(conv, biases), name = scope)
para += [kernel, biases]
return avtivation
def fc_op(input, name, num_out, para):
init = tf.contrib.layers.xavier_initializer_conv2d()
num_in = input.get_shape()[-1].value
with tf.name_scope(name) as scope:
weights = tf.get_variable(scope + "w", shape=[num_in, num_out], dtype= tf.float32, initializer=init)
biases = tf.Variable(tf.constant(0.1, shape=[num_out], dtype=tf.float32), name="b")
avtivation = tf.nn.relu_layer(input, weights, biases)
para += [weights, biases]
return avtivation
# 图像的数据输入是224 * 224 * 3
def inference_op(input, keep_prob):
parameters = []
# 第一段卷积, 输出的大小是112 * 112 * 64
conv1_1 = conv_op(input, name="conv1_1", kernel_h=3, kernel_w=3, num_out=4, step_h=1, step_w=1, para=parameters)
myprint(conv1_1)
conv1_2 = conv_op(conv1_1, name="conv1_2", kernel_h=3, kernel_w=3, num_out=64, step_h=1, step_w=1, para=parameters)
myprint(conv1_2)
pool1 = tf.nn.max_pool(conv1_2, ksize=[1,2,2,1], strides=[1,2,2,1], padding="SAME", name="pool1")
myprint(pool1)
# 第二段卷积,输出的大小是56*56*128
conv2_1 = conv_op(pool1, name = "conv2_1", kernel_h=3, kernel_w=3, num_out=128,step_h=1, step_w=1, para=parameters)
myprint(conv2_1)
conv2_2 = conv_op(conv2_1, name = "conv2_2", kernel_h=3, kernel_w=3, num_out=128,step_h=1, step_w=1, para=parameters)
myprint(conv2_2)
pool2 = tf.nn.max_pool(conv2_2, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding="SAME", name="pool2")
myprint(pool2)
# 第三段卷积, 输出的大小是28*28*256
conv3_1 = conv_op(pool2, name="conv3_1", kernel_h=3, kernel_w=3, num_out=256, step_h=1, step_w=1, para=parameters)
myprint(conv3_1)
conv3_2 = conv_op(conv3_1, name="conv3_2", kernel_h=3, kernel_w=3, num_out=256, step_h=1, step_w=1, para=parameters)
myprint(conv3_2)
conv3_3 = conv_op(conv3_2, name="conv3_3", kernel_h=3, kernel_w=3, num_out=256, step_h=1, step_w=1, para=parameters)
myprint(conv3_3)
pool3 = tf.nn.max_pool(conv3_3, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding="SAME", name="pool3")
myprint(pool3)
# 第四段卷积, 输出的大小是14*14*512
conv4_1 = conv_op(pool3, name="conv4_1", kernel_h=3, kernel_w=3, num_out=512, step_h=1, step_w=1, para=parameters)
myprint(conv4_1)
conv4_2 = conv_op(conv4_1, name="conv4_2", kernel_h=3, kernel_w=3, num_out=512, step_h=1, step_w=1, para=parameters)
myprint(conv4_2)
conv4_3 = conv_op(conv4_2, name="conv4_3", kernel_h=3, kernel_w=3, num_out=512, step_h=1, step_w=1, para=parameters)
myprint(conv4_3)
pool4 = tf.nn.max_pool(conv4_3, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding="SAME", name="pool4")
myprint(pool4)
# 第五段卷积, 输出的大小是7*7*512
conv5_1 = conv_op(pool4, name="conv5_1", kernel_h=3, kernel_w=3, num_out=512, step_h=1, step_w=1, para=parameters)
myprint(conv5_1)
conv5_2 = conv_op(conv5_1, name="conv5_2", kernel_h=3, kernel_w=3, num_out=512, step_h=1, step_w=1, para=parameters)
myprint(conv5_2)
conv5_3 = conv_op(conv5_2, name="conv5_3", kernel_h=3, kernel_w=3, num_out=512, step_h=1, step_w=1, para=parameters)
myprint(conv5_3)
pool5 = tf.nn.max_pool(conv5_3, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding="SAME", name="pool5")
myprint(pool5)
pool_shape = pool5.get_shape().as_list()
flattened_shape = pool_shape[1]*pool_shape[2]*pool_shape[3]
reshaped = tf.reshape(pool5, [-1, flattened_shape], name="reshped")
myprint(reshaped)
# 创建第一个全连层
fc_6 = fc_op(reshaped, name="fc6", num_out=4096, para=parameters)
fc_6_drop = tf.nn.dropout(fc_6, keep_prob, name="fc_6_drop")
myprint(fc_6_drop)
# 创建第二个全连层
fc_7 = fc_op(fc_6_drop, name="fc7", num_out=4096, para=parameters)
fc_7_drop = tf.nn.dropout(fc_7, keep_prob, name="fc_7_drop")
myprint(fc_7_drop)
# 创建第三个全连层
fc_8 = fc_op(fc_7_drop, name="fc8", num_out=1000, para=parameters)
softmax = tf.nn.softmax(fc_8)
myprint(fc_8)
myprint(softmax)
# 得到结果
predictions = tf.argmax(softmax, 1)
return predictions, softmax, fc_8, parameters
with tf.Graph().as_default():
image_size = 224
images = tf.Variable(tf.random_normal([batch_size, image_size, image_size, 3], dtype=tf.float32, stddev=1e-1))
keep_prob = tf.placeholder(tf.float32)
predictions, softmax, fc_8, parameters = inference_op(images, keep_prob)
init_op = tf.global_variables_initializer()
# 使用BFC算法确定GPU内存最佳分配策略
config = tf.ConfigProto()
config.gpu_options.allocator_type = "BFC"
with tf.Session(config=config) as sess:
sess.run(init_op)
num_steps_burn_in = 10
total_dura = 0.0
total_dura_squared = 0.0
back_total_dura = 0.0
back_total_dura_squared = 0.0
for i in range(num_batches + num_steps_burn_in):
start_time = time.time()
_ = sess.run(predictions, feed_dict={keep_prob: 1.0})
duration = time.time() - start_time
if i >= num_steps_burn_in:
if i % 10 == 0:
print("%s: step %d, duration = %.3f" %
(datetime.now(), i - num_steps_burn_in, duration))
total_dura += duration
total_dura_squared += duration * duration
average_time = total_dura / num_batches
print("%s: Forward across %d steps, %.3f +/- %.3f sec / batch" %
(datetime.now(), num_batches, average_time,
math.sqrt(total_dura_squared / num_batches - average_time * average_time)))
# 定义求解梯度的操作
grad = tf.gradients(tf.nn.l2_loss(fc_8), parameters)
# 运行反向传播测试过程
for i in range(num_batches + num_steps_burn_in):
start_time = time.time()
_ = sess.run(grad, feed_dict={keep_prob: 0.5})
duration = time.time() - start_time
if i >= num_steps_burn_in:
if i % 10 == 0:
print("%s: step %d, duration = %.3f" %
(datetime.now(), i - num_steps_burn_in, duration))
back_total_dura += duration
back_total_dura_squared += duration * duration
back_avg_t = back_total_dura / num_batches
# 打印反向传播的运算时间信息
print("%s: Forward-backward across %d steps, %.3f +/- %.3f sec / batch" %
(datetime.now(), num_batches, back_avg_t,
math.sqrt(back_total_dura_squared / num_batches - back_avg_t * back_avg_t)))