分享

tf.contrib.slim

 雪柳花明 2017-04-12
Tensorflow 的高级库
好像不是官方的,所以,其介绍文档不是十分详细。

引入slim
这里使用mnist的数据集
 
 在文章最后,写出slim的使用。
 
 


用slim.conv2d表示 
 
 

slim是高级库,一些参数已经定义好了,所以使用起来相对方便一些,


slim.arg_scope()
作用:给函数的参数自动赋予某些值


 
 
slim.arg_scope() 会对[slim.conv2d,slim.max_pool2d]的参数自动赋值
stride=1,padding='SAME'这两个参数自动赋值
前提是:[slim.conv2d,slim.max_pool2d]都有
stride=1,padding='SAME'这两个参数



整个代码如下:

# -*- coding:utf-8 -*-
from __future__ import print_function
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
# number 1 to 10 data
mnist = input_data.read_data_sets('MNIST_data', one_hot=True)

slim=tf.contrib.slim
trunc_normal=lambda stddev:tf.truncated_normal_initializer(0.0,stddev)


def compute_accuracy(v_xs, v_ys):
global prediction
y_pre = sess.run(prediction, feed_dict={xs: v_xs, keep_prob: 1})
correct_prediction = tf.equal(tf.argmax(y_pre,1), tf.argmax(v_ys,1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
result = sess.run(accuracy, feed_dict={xs: v_xs, ys: v_ys, keep_prob: 1})
return result

def print_activations(t):
print (t.op.name,' ',t.get_shape().as_list())

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)

# define placeholder for inputs to network
xs = tf.placeholder(tf.float32, [None, 784])/255. # 28x28
ys = tf.placeholder(tf.float32, [None, 10])
keep_prob = tf.placeholder(tf.float32)
x_image = tf.reshape(xs, [-1, 28, 28, 1])

def mnist_base(inputs,scope=None):
with tf.variable_scope(scope,'MNIST',[inputs]):
with slim.arg_scope([slim.conv2d,slim.max_pool2d],stride=1,padding='SAME'):
net=slim.conv2d(inputs,32,[5,5],scope='conv2d_1',activation_fn=tf.nn.relu)
print_activations(net)

net=slim.max_pool2d(net,[2,2],stride=2,scope='h_pool_1')
print_activations(net)

net = slim.conv2d(net, 64, [5, 5],stride=1 ,scope='conv2d_2',activation_fn=tf.nn.relu)
print_activations(net)

net = slim.max_pool2d(net, [2, 2], stride=2, scope='h_pool_2')
print_activations(net)
return net

h_pool2=mnist_base(x_image,scope='mnist_slim')
## fc1 layer ##
W_fc1 = weight_variable([7*7*64, 1024])
b_fc1 = bias_variable([1024])
# [n_samples, 7, 7, 64] ->> [n_samples, 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)
h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)

## fc2 layer ##
W_fc2 = weight_variable([1024, 10])
b_fc2 = bias_variable([10])

prediction = tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2)


# the error between prediction and real data
cross_entropy = tf.reduce_mean(-tf.reduce_sum(ys * tf.log(prediction),
reduction_indices=[1])) # loss
train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)

sess = tf.Session()

init = tf.global_variables_initializer()
sess.run(init)

for i in range(1000):
batch_xs, batch_ys = mnist.train.next_batch(100)
sess.run(train_step, feed_dict={xs: batch_xs, ys: batch_ys, keep_prob: 0.5})
if i % 50 == 0:
print(compute_accuracy(
mnist.test.images, mnist.test.labels))







    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多