【转】tensorflow学习使用路线

版权声明:本文为博主hjimce的原创文章,原文地址为http://blog.csdn.net/hjimce/article/details/51899683。

一、学习路线

个人感觉对于任何一个深度学习库,如mxnet、tensorflow、theano、caffe等,基本上我都采用同样的一个学习流程,大体流程如下:

(1)训练阶段:数据打包-》网络构建、训练-》模型保存-》可视化查看损失函数、验证精度

(2)测试阶段:模型加载-》测试图片读取-》预测显示结果

(3)移植阶段:量化、压缩加速-》微调-》C++移植打包-》上线

这边我就以tensorflow为例子,讲解整个流程的大体架构,完成一个深度学习项目所需要熟悉的过程代码。

二、训练、测试阶段

1、tensorflow打包数据

这一步对于tensorflow来说,也可以直接自己在线读取:.jpg图片、标签文件等,然后通过phaceholder变量,把数据送入网络中,进行计算。

不过这种效率比较低,对于大规模训练数据来说,我们需要一个比较高效的方式,tensorflow建议我们采用tfrecoder进行高效数据读取。学习tensorflow一定要学会tfrecoder文件写入、读取,具体示例代码如下:

[python]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. #coding=utf-8  
  2. #tensorflow高效数据读取训练  
  3. import tensorflow as tf  
  4. import cv2  
  5.   
  6. #把train.txt文件格式,每一行:图片路径名   类别标签  
  7. #奖数据打包,转换成tfrecords格式,以便后续高效读取  
  8. def encode_to_tfrecords(lable_file,data_root,new_name='data.tfrecords',resize=None):  
  9.     writer=tf.python_io.TFRecordWriter(data_root+'/'+new_name)  
  10.     num_example=0  
  11.     with open(lable_file,'r') as f:  
  12.         for l in f.readlines():  
  13.             l=l.split()  
  14.             image=cv2.imread(data_root+"/"+l[0])  
  15.             if resize is not None:  
  16.                 image=cv2.resize(image,resize)#为了  
  17.             height,width,nchannel=image.shape  
  18.   
  19.             label=int(l[1])  
  20.   
  21.             example=tf.train.Example(features=tf.train.Features(feature={  
  22.                 'height':tf.train.Feature(int64_list=tf.train.Int64List(value=[height])),  
  23.                 'width':tf.train.Feature(int64_list=tf.train.Int64List(value=[width])),  
  24.                 'nchannel':tf.train.Feature(int64_list=tf.train.Int64List(value=[nchannel])),  
  25.                 'image':tf.train.Feature(bytes_list=tf.train.BytesList(value=[image.tobytes()])),  
  26.                 'label':tf.train.Feature(int64_list=tf.train.Int64List(value=[label]))  
  27.             }))  
  28.             serialized=example.SerializeToString()  
  29.             writer.write(serialized)  
  30.             num_example+=1  
  31.     print lable_file,"样本数据量:",num_example  
  32.     writer.close()  
  33. #读取tfrecords文件  
  34. def decode_from_tfrecords(filename,num_epoch=None):  
  35.     filename_queue=tf.train.string_input_producer([filename],num_epochs=num_epoch)#因为有的训练数据过于庞大,被分成了很多个文件,所以第一个参数就是文件列表名参数  
  36.     reader=tf.TFRecordReader()  
  37.     _,serialized=reader.read(filename_queue)  
  38.     example=tf.parse_single_example(serialized,features={  
  39.         'height':tf.FixedLenFeature([],tf.int64),  
  40.         'width':tf.FixedLenFeature([],tf.int64),  
  41.         'nchannel':tf.FixedLenFeature([],tf.int64),  
  42.         'image':tf.FixedLenFeature([],tf.string),  
  43.         'label':tf.FixedLenFeature([],tf.int64)  
  44.     })  
  45.     label=tf.cast(example['label'], tf.int32)  
  46.     image=tf.decode_raw(example['image'],tf.uint8)  
  47.     image=tf.reshape(image,tf.pack([  
  48.         tf.cast(example['height'], tf.int32),  
  49.         tf.cast(example['width'], tf.int32),  
  50.         tf.cast(example['nchannel'], tf.int32)]))  
  51.     #label=example['label']  
  52.     return image,label  
  53. #根据队列流数据格式,解压出一张图片后,输入一张图片,对其做预处理、及样本随机扩充  
  54. def get_batch(image, label, batch_size,crop_size):  
  55.         #数据扩充变换  
  56.     distorted_image = tf.random_crop(image, [crop_size, crop_size, 3])#随机裁剪  
  57.     distorted_image = tf.image.random_flip_up_down(distorted_image)#上下随机翻转  
  58.     #distorted_image = tf.image.random_brightness(distorted_image,max_delta=63)#亮度变化  
  59.     #distorted_image = tf.image.random_contrast(distorted_image,lower=0.2, upper=1.8)#对比度变化  
  60.   
  61.     #生成batch  
  62.     #shuffle_batch的参数:capacity用于定义shuttle的范围,如果是对整个训练数据集,获取batch,那么capacity就应该够大  
  63.     #保证数据打的足够乱  
  64.     images, label_batch = tf.train.shuffle_batch([distorted_image, label],batch_size=batch_size,  
  65.                                                  num_threads=16,capacity=50000,min_after_dequeue=10000)  
  66.     #images, label_batch=tf.train.batch([distorted_image, label],batch_size=batch_size)  
  67.   
  68.   
  69.   
  70.     # 调试显示  
  71.     #tf.image_summary('images', images)  
  72.     return images, tf.reshape(label_batch, [batch_size])  
  73. #这个是用于测试阶段,使用的get_batch函数  
  74. def get_test_batch(image, label, batch_size,crop_size):  
  75.         #数据扩充变换  
  76.     distorted_image=tf.image.central_crop(image,39./45.)  
  77.     distorted_image = tf.random_crop(distorted_image, [crop_size, crop_size, 3])#随机裁剪  
  78.     images, label_batch=tf.train.batch([distorted_image, label],batch_size=batch_size)  
  79.     return images, tf.reshape(label_batch, [batch_size])  
  80. #测试上面的压缩、解压代码  
  81. def test():  
  82.     encode_to_tfrecords("data/train.txt","data",(100,100))  
  83.     image,label=decode_from_tfrecords('data/data.tfrecords')  
  84.     batch_image,batch_label=get_batch(image,label,3)#batch 生成测试  
  85.     init=tf.initialize_all_variables()  
  86.     with tf.Session() as session:  
  87.         session.run(init)  
  88.         coord = tf.train.Coordinator()  
  89.         threads = tf.train.start_queue_runners(coord=coord)  
  90.         for l in range(100000):#每run一次,就会指向下一个样本,一直循环  
  91.             #image_np,label_np=session.run([image,label])#每调用run一次,那么  
  92.             '''''cv2.imshow("temp",image_np) 
  93.             cv2.waitKey()'''  
  94.             #print label_np  
  95.             #print image_np.shape  
  96.   
  97.   
  98.             batch_image_np,batch_label_np=session.run([batch_image,batch_label])  
  99.             print batch_image_np.shape  
  100.             print batch_label_np.shape  
  101.   
  102.   
  103.   
  104.         coord.request_stop()#queue需要关闭,否则报错  
  105.         coord.join(threads)  
  106. #test()  

2、网络架构与训练

经过上面的数据格式处理,接着我们只要写一写网络结构、网络优化方法,把数据搞进网络中就可以了,具体示例代码如下:

[python]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. #coding=utf-8  
  2. import  tensorflow as tf  
  3. from  data_encoder_decoeder import  encode_to_tfrecords,decode_from_tfrecords,get_batch,get_test_batch  
  4. import  cv2  
  5. import  os  
  6.   
  7. class network(object):  
  8.     def __init__(self):  
  9.         with tf.variable_scope("weights"):  
  10.             self.weights={  
  11.                 #39*39*3->36*36*20->18*18*20  
  12.                 'conv1':tf.get_variable('conv1',[4,4,3,20],initializer=tf.contrib.layers.xavier_initializer_conv2d()),  
  13.                 #18*18*20->16*16*40->8*8*40  
  14.                 'conv2':tf.get_variable('conv2',[3,3,20,40],initializer=tf.contrib.layers.xavier_initializer_conv2d()),  
  15.                 #8*8*40->6*6*60->3*3*60  
  16.                 'conv3':tf.get_variable('conv3',[3,3,40,60],initializer=tf.contrib.layers.xavier_initializer_conv2d()),  
  17.                 #3*3*60->120  
  18.                 'fc1':tf.get_variable('fc1',[3*3*60,120],initializer=tf.contrib.layers.xavier_initializer()),  
  19.                 #120->6  
  20.                 'fc2':tf.get_variable('fc2',[120,6],initializer=tf.contrib.layers.xavier_initializer()),  
  21.                 }  
  22.         with tf.variable_scope("biases"):  
  23.             self.biases={  
  24.                 'conv1':tf.get_variable('conv1',[20,],initializer=tf.constant_initializer(value=0.0, dtype=tf.float32)),  
  25.                 'conv2':tf.get_variable('conv2',[40,],initializer=tf.constant_initializer(value=0.0, dtype=tf.float32)),  
  26.                 'conv3':tf.get_variable('conv3',[60,],initializer=tf.constant_initializer(value=0.0, dtype=tf.float32)),  
  27.                 'fc1':tf.get_variable('fc1',[120,],initializer=tf.constant_initializer(value=0.0, dtype=tf.float32)),  
  28.                 'fc2':tf.get_variable('fc2',[6,],initializer=tf.constant_initializer(value=0.0, dtype=tf.float32))  
  29.   
  30.             }  
  31.   
  32.     def inference(self,images):  
  33.         # 向量转为矩阵  
  34.         images = tf.reshape(images, shape=[-139,393])# [batch, in_height, in_width, in_channels]  
  35.         images=(tf.cast(images,tf.float32)/255.-0.5)*2#归一化处理  
  36.   
  37.   
  38.   
  39.         #第一层  
  40.         conv1=tf.nn.bias_add(tf.nn.conv2d(images, self.weights['conv1'], strides=[1111], padding='VALID'),  
  41.                              self.biases['conv1'])  
  42.   
  43.         relu1= tf.nn.relu(conv1)  
  44.         pool1=tf.nn.max_pool(relu1, ksize=[1221], strides=[1221], padding='VALID')  
  45.   
  46.   
  47.         #第二层  
  48.         conv2=tf.nn.bias_add(tf.nn.conv2d(pool1, self.weights['conv2'], strides=[1111], padding='VALID'),  
  49.                              self.biases['conv2'])  
  50.         relu2= tf.nn.relu(conv2)  
  51.         pool2=tf.nn.max_pool(relu2, ksize=[1221], strides=[1221], padding='VALID')  
  52.   
  53.   
  54.         # 第三层  
  55.         conv3=tf.nn.bias_add(tf.nn.conv2d(pool2, self.weights['conv3'], strides=[1111], padding='VALID'),  
  56.                              self.biases['conv3'])  
  57.         relu3= tf.nn.relu(conv3)  
  58.         pool3=tf.nn.max_pool(relu3, ksize=[1221], strides=[1221], padding='VALID')  
  59.   
  60.   
  61.         # 全连接层1,先把特征图转为向量  
  62.         flatten = tf.reshape(pool3, [-1self.weights['fc1'].get_shape().as_list()[0]])  
  63.   
  64.         drop1=tf.nn.dropout(flatten,0.5)  
  65.         fc1=tf.matmul(drop1, self.weights['fc1'])+self.biases['fc1']  
  66.   
  67.         fc_relu1=tf.nn.relu(fc1)  
  68.   
  69.         fc2=tf.matmul(fc_relu1, self.weights['fc2'])+self.biases['fc2']  
  70.   
  71.         return  fc2  
  72.     def inference_test(self,images):  
  73.                 # 向量转为矩阵  
  74.         images = tf.reshape(images, shape=[-139,393])# [batch, in_height, in_width, in_channels]  
  75.         images=(tf.cast(images,tf.float32)/255.-0.5)*2#归一化处理  
  76.   
  77.   
  78.   
  79.         #第一层  
  80.         conv1=tf.nn.bias_add(tf.nn.conv2d(images, self.weights['conv1'], strides=[1111], padding='VALID'),  
  81.                              self.biases['conv1'])  
  82.   
  83.         relu1= tf.nn.relu(conv1)  
  84.         pool1=tf.nn.max_pool(relu1, ksize=[1221], strides=[1221], padding='VALID')  
  85.   
  86.   
  87.         #第二层  
  88.         conv2=tf.nn.bias_add(tf.nn.conv2d(pool1, self.weights['conv2'], strides=[1111], padding='VALID'),  
  89.                              self.biases['conv2'])  
  90.         relu2= tf.nn.relu(conv2)  
  91.         pool2=tf.nn.max_pool(relu2, ksize=[1221], strides=[1221], padding='VALID')  
  92.   
  93.   
  94.         # 第三层  
  95.         conv3=tf.nn.bias_add(tf.nn.conv2d(pool2, self.weights['conv3'], strides=[1111], padding='VALID'),  
  96.                              self.biases['conv3'])  
  97.         relu3= tf.nn.relu(conv3)  
  98.         pool3=tf.nn.max_pool(relu3, ksize=[1221], strides=[1221], padding='VALID')  
  99.   
  100.   
  101.         # 全连接层1,先把特征图转为向量  
  102.         flatten = tf.reshape(pool3, [-1self.weights['fc1'].get_shape().as_list()[0]])  
  103.   
  104.         fc1=tf.matmul(flatten, self.weights['fc1'])+self.biases['fc1']  
  105.         fc_relu1=tf.nn.relu(fc1)  
  106.   
  107.         fc2=tf.matmul(fc_relu1, self.weights['fc2'])+self.biases['fc2']  
  108.   
  109.         return  fc2  
  110.   
  111.     #计算softmax交叉熵损失函数  
  112.     def sorfmax_loss(self,predicts,labels):  
  113.         predicts=tf.nn.softmax(predicts)  
  114.         labels=tf.one_hot(labels,self.weights['fc2'].get_shape().as_list()[1])  
  115.         loss =-tf.reduce_mean(labels * tf.log(predicts))# tf.nn.softmax_cross_entropy_with_logits(predicts, labels)  
  116.         self.cost= loss  
  117.         return self.cost  
  118.     #梯度下降  
  119.     def optimer(self,loss,lr=0.001):  
  120.         train_optimizer = tf.train.GradientDescentOptimizer(lr).minimize(loss)  
  121.   
  122.         return train_optimizer  
  123.   
  124.   
  125. def train():  
  126.     encode_to_tfrecords("data/train.txt","data",'train.tfrecords',(45,45))  
  127.     image,label=decode_from_tfrecords('data/train.tfrecords')  
  128.     batch_image,batch_label=get_batch(image,label,batch_size=50,crop_size=39)#batch 生成测试  
  129.   
  130.   
  131.   
  132.   
  133.   
  134.   
  135.   
  136.    #网络链接,训练所用  
  137.     net=network()  
  138.     inf=net.inference(batch_image)  
  139.     loss=net.sorfmax_loss(inf,batch_label)  
  140.     opti=net.optimer(loss)  
  141.   
  142.   
  143.     #验证集所用  
  144.     encode_to_tfrecords("data/val.txt","data",'val.tfrecords',(45,45))  
  145.     test_image,test_label=decode_from_tfrecords('data/val.tfrecords',num_epoch=None)  
  146.     test_images,test_labels=get_test_batch(test_image,test_label,batch_size=120,crop_size=39)#batch 生成测试  
  147.     test_inf=net.inference_test(test_images)  
  148.     correct_prediction = tf.equal(tf.cast(tf.argmax(test_inf,1),tf.int32), test_labels)  
  149.     accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))  
  150.   
  151.   
  152.   
  153.   
  154.   
  155.     init=tf.initialize_all_variables()  
  156.     with tf.Session() as session:  
  157.         session.run(init)  
  158.         coord = tf.train.Coordinator()  
  159.         threads = tf.train.start_queue_runners(coord=coord)  
  160.         max_iter=100000  
  161.         iter=0  
  162.         if os.path.exists(os.path.join("model",'model.ckpt')) is True:  
  163.             tf.train.Saver(max_to_keep=None).restore(session, os.path.join("model",'model.ckpt'))  
  164.         while iter<max_iter:  
  165.             loss_np,_,label_np,image_np,inf_np=session.run([loss,opti,batch_label,batch_image,inf])  
  166.             #print image_np.shape  
  167.             #cv2.imshow(str(label_np[0]),image_np[0])  
  168.             #print label_np[0]  
  169.             #cv2.waitKey()  
  170.             #print label_np  
  171.             if iter%50==0:  
  172.                 print 'trainloss:',loss_np  
  173.             if iter%500==0:  
  174.                 accuracy_np=session.run([accuracy])  
  175.                 print '***************test accruacy:',accuracy_np,'*******************'  
  176.                 tf.train.Saver(max_to_keep=None).save(session, os.path.join('model','model.ckpt'))  
  177.             iter+=1  
  178.   
  179.   
  180.   
  181.   
  182.   
  183.         coord.request_stop()#queue需要关闭,否则报错  
  184.         coord.join(threads)  
  185.   
  186. train()  

3、可视化显示

(1)首先再源码中加入需要跟踪的变量:

[python]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. <span style="font-size:18px;">tf.scalar_summary("cost_function", loss)#损失函数值</span>  
(2)然后定义执行操作:

[python]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. <span style="font-size:18px;">merged_summary_op = tf.merge_all_summaries()</span>  
(3)再session中定义保存路径:
[python]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. <span style="font-size:18px;">summary_writer = tf.train.SummaryWriter('log', session.graph)</span>  
(4)然后再session执行的时候,保存:
[python]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. <span style="font-size:18px;">            summary_str,loss_np,_=session.run([merged_summary_op,loss,opti])  
  2.             summary_writer.add_summary(summary_str, iter)</span>  
(5)最后只要训练完毕后,直接再终端输入命令:
[python]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. <span style="font-size:18px;">python /usr/local/lib/python2.7/dist-packages/tensorflow/tensorboard/tensorboard.py --logdir=log</span>  
然后打开浏览器网址:
[python]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. <span style="font-size:18px;">http://0.0.0.0:6006</span>  

即可观训练曲线。

4\、测试阶段

测试阶段主要是直接通过加载图模型、读取参数等,然后直接通过tensorflow的相关函数,进行调用,而不需要网络架构相关的代码;通过内存feed_dict的方式,对相关的输入节点赋予相关的数据,进行前向传导,并获取相关的节点数值。

[python]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. #coding=utf-8  
  2. import  tensorflow  as tf  
  3. import  os  
  4. import  cv2  
  5.   
  6. def load_model(session,netmodel_path,param_path):  
  7.     new_saver = tf.train.import_meta_graph(netmodel_path)  
  8.     new_saver.restore(session, param_path)  
  9.     x= tf.get_collection('test_images')[0]#在训练阶段需要调用tf.add_to_collection('test_images',test_images),保存之  
  10.     y = tf.get_collection("test_inf")[0]  
  11.     batch_size = tf.get_collection("batch_size")[0]  
  12.     return  x,y,batch_size  
  13.   
  14. def load_images(data_root):  
  15.     filename_queue = tf.train.string_input_producer(data_root)  
  16.     image_reader = tf.WholeFileReader()  
  17.     key,image_file = image_reader.read(filename_queue)  
  18.     image = tf.image.decode_jpeg(image_file)  
  19.     return image, key  
  20.   
  21. def test(data_root="data/race/cropbrown"):  
  22.     image_filenames=os.listdir(data_root)  
  23.     image_filenames=[(data_root+'/'+i) for i in image_filenames]  
  24.   
  25.   
  26.     #print cv2.imread(image_filenames[0]).shape  
  27.     #image,key=load_images(image_filenames)  
  28.     race_listsrc=['black','brown','white','yellow']  
  29.     with tf.Session() as session:  
  30.         coord = tf.train.Coordinator()  
  31.         threads = tf.train.start_queue_runners(coord=coord)  
  32.   
  33.   
  34.   
  35.         x,y,batch_size=load_model(session,os.path.join("model",'model_ori_race.ckpt.meta'),  
  36.                        os.path.join("model",'model_ori_race.ckpt'))  
  37.         predict_label=tf.cast(tf.argmax(y,1),tf.int32)  
  38.         print x.get_shape()  
  39.         for imgf in image_filenames:  
  40.             image=cv2.imread(imgf)  
  41.             image=cv2.resize(image,(76,76)).reshape((1,76,76,3))  
  42.             print "cv shape:",image.shape  
  43.   
  44.   
  45.             #cv2.imshow("t",image_np[:,:,::-1])  
  46.             y_np=session.run(predict_label,feed_dict = {x:image, batch_size:1})  
  47.             print race_listsrc[y_np]  
  48.   
  49.   
  50.         coord.request_stop()#queue需要关闭,否则报错  
  51.         coord.join(threads)  



4、移植阶段

(1)一个算法经过实验阶段后,接着就要进入移植商用,因此接着需要采用tensorflow的c api函数,直接进行预测推理,首先我们先把tensorflow编译成链接库,然后编写cmake,调用tensorflow链接库:

[cpp]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. <span style="font-size:18px;">bazel build -c opt //tensorflow:libtensorflow.so  
  2. </span>  

bazel-bin/tensorflow目录下会生成libtensorflow.so文件


(2)调用api函数


tf.contrib.layers.batch_norm(x, decay=0.9, updates_collections=None, epsilon=self.epsilon, scale=True, scope=self.name)

5、量化移植阶段



[python]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. <span style="font-size:18px;">import  tensorflow as tf  
  2. with tf.variable_scope('foo'):#在没有启用reuse的情况下,如果该变量还未被创建,那么就创建该变量,如果已经创建过了,那么就获取该共享变量  
  3.     v=tf.get_variable('v',[1])  
  4. with tf.variable_scope('foo',reuse=True):#如果启用了reuse,那么编译的时候,如果get_variable没有遇到一个已经创建的变量,是会出错的  
  5.     v1=tf.get_variable('v1',[1])</span>  






[python]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. <span style="font-size:18px;">import  tensorflow.nn.rnn_cell  
  2.   
  3. lstm = rnn_cell.BasicLSTMCell(lstm_size)#创建一个lstm cell单元类,隐藏层神经元个数为lstm_size  
  4.   
  5. state = tf.zeros([batch_size, lstm.state_size])#一个序列隐藏层的状态值  
  6.   
  7. loss = 0.0  
  8. for current_batch_of_words in words_in_dataset:  
  9.     output, state = lstm(current_batch_of_words, state)#返回值为隐藏层神经元的输出  
  10.     logits = tf.matmul(output, softmax_w) + softmax_b#matmul矩阵点乘  
  11.     probabilities = tf.nn.softmax(logits)#softmax输出  
  12.     loss += loss_function(probabilities, target_words)</span>  


1、one-hot函数:

[python]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. <span style="font-size:18px;">#ont hot 可以把训练数据的标签,直接转换成one_hot向量,用于交叉熵损失函数  
  2. import tensorflow as tf  
  3. a=tf.convert_to_tensor([[1],[2],[4]])  
  4. b=tf.one_hot(a,5)</span>  

>>b的值为
[python]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. <span style="font-size:18px;">[[[ 0.  1.  0.  0.  0.]]  
  2.   
  3.  [[ 0.  0.  1.  0.  0.]]  
  4.   
  5.  [[ 0.  0.  0.  0.  1.]]]</span>  

2、assign_sub

[python]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. <span style="font-size:18px;">import tensorflow as tf  
  2.   
  3. x = tf.Variable(10, name="x")  
  4. sub=x.assign_sub(3)#如果直接采用x.assign_sub,那么可以看到x的值也会发生变化  
  5. init_op=tf.initialize_all_variables()  
  6. with tf.Session() as sess:  
  7.     sess.run(init_op)  
  8.     print sub.eval()  
  9.     print x.eval()</span>  
可以看到输入sub=x=7

[python]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. <span style="font-size:18px;">state_ops.assign_sub</span>  
采用state_ops的assign_sub也是同样sub=x=7

也就是说assign函数返回结果值的同时,变量本身的值也会被改变
3、变量查看

[python]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. <span style="font-size:18px;">    #查看所有的变量  
  2.     for l in tf.all_variables():  
  3.         print l.name</span>  

4、slice函数:

[python]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. <span style="font-size:18px;">import cv2  
  2. import  tensorflow as tf  
  3. #slice 函数可以用于切割子矩形图片,参数矩形框的rect,begin=(minx,miny),size=(width,height)  
  4. minx=20  
  5. miny=30  
  6. height=100  
  7. width=200  
  8.   
  9. image=tf.placeholder(dtype=tf.uint8,shape=(386,386,3))  
  10. rect_image=tf.slice(image,(miny,minx,0),(height,width,-1))  
  11.   
  12.   
  13. cvimage=cv2.imread("1.jpg")  
  14. cv2.imshow("cv2",cvimage[miny:(miny+height),minx:(minx+width),:])  
  15.   
  16.   
  17. with tf.Session() as sess:  
  18.     tfimage=sess.run([rect_image],{image:cvimage})  
  19.     cv2.imshow('tf',tfimage[0])  
  20. cv2.waitKey()</span>  

5、正太分布:

tf.truncated_normal


一、学习路线

个人感觉对于任何一个深度学习库,如mxnet、tensorflow、theano、caffe等,基本上我都采用同样的一个学习流程,大体流程如下:

(1)训练阶段:数据打包-》网络构建、训练-》模型保存-》可视化查看损失函数、验证精度

(2)测试阶段:模型加载-》测试图片读取-》预测显示结果

(3)移植阶段:量化、压缩加速-》微调-》C++移植打包-》上线

这边我就以tensorflow为例子,讲解整个流程的大体架构,完成一个深度学习项目所需要熟悉的过程代码。

二、训练、测试阶段

1、tensorflow打包数据

这一步对于tensorflow来说,也可以直接自己在线读取:.jpg图片、标签文件等,然后通过phaceholder变量,把数据送入网络中,进行计算。

不过这种效率比较低,对于大规模训练数据来说,我们需要一个比较高效的方式,tensorflow建议我们采用tfrecoder进行高效数据读取。学习tensorflow一定要学会tfrecoder文件写入、读取,具体示例代码如下:

[python]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. #coding=utf-8  
  2. #tensorflow高效数据读取训练  
  3. import tensorflow as tf  
  4. import cv2  
  5.   
  6. #把train.txt文件格式,每一行:图片路径名   类别标签  
  7. #奖数据打包,转换成tfrecords格式,以便后续高效读取  
  8. def encode_to_tfrecords(lable_file,data_root,new_name='data.tfrecords',resize=None):  
  9.     writer=tf.python_io.TFRecordWriter(data_root+'/'+new_name)  
  10.     num_example=0  
  11.     with open(lable_file,'r') as f:  
  12.         for l in f.readlines():  
  13.             l=l.split()  
  14.             image=cv2.imread(data_root+"/"+l[0])  
  15.             if resize is not None:  
  16.                 image=cv2.resize(image,resize)#为了  
  17.             height,width,nchannel=image.shape  
  18.   
  19.             label=int(l[1])  
  20.   
  21.             example=tf.train.Example(features=tf.train.Features(feature={  
  22.                 'height':tf.train.Feature(int64_list=tf.train.Int64List(value=[height])),  
  23.                 'width':tf.train.Feature(int64_list=tf.train.Int64List(value=[width])),  
  24.                 'nchannel':tf.train.Feature(int64_list=tf.train.Int64List(value=[nchannel])),  
  25.                 'image':tf.train.Feature(bytes_list=tf.train.BytesList(value=[image.tobytes()])),  
  26.                 'label':tf.train.Feature(int64_list=tf.train.Int64List(value=[label]))  
  27.             }))  
  28.             serialized=example.SerializeToString()  
  29.             writer.write(serialized)  
  30.             num_example+=1  
  31.     print lable_file,"样本数据量:",num_example  
  32.     writer.close()  
  33. #读取tfrecords文件  
  34. def decode_from_tfrecords(filename,num_epoch=None):  
  35.     filename_queue=tf.train.string_input_producer([filename],num_epochs=num_epoch)#因为有的训练数据过于庞大,被分成了很多个文件,所以第一个参数就是文件列表名参数  
  36.     reader=tf.TFRecordReader()  
  37.     _,serialized=reader.read(filename_queue)  
  38.     example=tf.parse_single_example(serialized,features={  
  39.         'height':tf.FixedLenFeature([],tf.int64),  
  40.         'width':tf.FixedLenFeature([],tf.int64),  
  41.         'nchannel':tf.FixedLenFeature([],tf.int64),  
  42.         'image':tf.FixedLenFeature([],tf.string),  
  43.         'label':tf.FixedLenFeature([],tf.int64)  
  44.     })  
  45.     label=tf.cast(example['label'], tf.int32)  
  46.     image=tf.decode_raw(example['image'],tf.uint8)  
  47.     image=tf.reshape(image,tf.pack([  
  48.         tf.cast(example['height'], tf.int32),  
  49.         tf.cast(example['width'], tf.int32),  
  50.         tf.cast(example['nchannel'], tf.int32)]))  
  51.     #label=example['label']  
  52.     return image,label  
  53. #根据队列流数据格式,解压出一张图片后,输入一张图片,对其做预处理、及样本随机扩充  
  54. def get_batch(image, label, batch_size,crop_size):  
  55.         #数据扩充变换  
  56.     distorted_image = tf.random_crop(image, [crop_size, crop_size, 3])#随机裁剪  
  57.     distorted_image = tf.image.random_flip_up_down(distorted_image)#上下随机翻转  
  58.     #distorted_image = tf.image.random_brightness(distorted_image,max_delta=63)#亮度变化  
  59.     #distorted_image = tf.image.random_contrast(distorted_image,lower=0.2, upper=1.8)#对比度变化  
  60.   
  61.     #生成batch  
  62.     #shuffle_batch的参数:capacity用于定义shuttle的范围,如果是对整个训练数据集,获取batch,那么capacity就应该够大  
  63.     #保证数据打的足够乱  
  64.     images, label_batch = tf.train.shuffle_batch([distorted_image, label],batch_size=batch_size,  
  65.                                                  num_threads=16,capacity=50000,min_after_dequeue=10000)  
  66.     #images, label_batch=tf.train.batch([distorted_image, label],batch_size=batch_size)  
  67.   
  68.   
  69.   
  70.     # 调试显示  
  71.     #tf.image_summary('images', images)  
  72.     return images, tf.reshape(label_batch, [batch_size])  
  73. #这个是用于测试阶段,使用的get_batch函数  
  74. def get_test_batch(image, label, batch_size,crop_size):  
  75.         #数据扩充变换  
  76.     distorted_image=tf.image.central_crop(image,39./45.)  
  77.     distorted_image = tf.random_crop(distorted_image, [crop_size, crop_size, 3])#随机裁剪  
  78.     images, label_batch=tf.train.batch([distorted_image, label],batch_size=batch_size)  
  79.     return images, tf.reshape(label_batch, [batch_size])  
  80. #测试上面的压缩、解压代码  
  81. def test():  
  82.     encode_to_tfrecords("data/train.txt","data",(100,100))  
  83.     image,label=decode_from_tfrecords('data/data.tfrecords')  
  84.     batch_image,batch_label=get_batch(image,label,3)#batch 生成测试  
  85.     init=tf.initialize_all_variables()  
  86.     with tf.Session() as session:  
  87.         session.run(init)  
  88.         coord = tf.train.Coordinator()  
  89.         threads = tf.train.start_queue_runners(coord=coord)  
  90.         for l in range(100000):#每run一次,就会指向下一个样本,一直循环  
  91.             #image_np,label_np=session.run([image,label])#每调用run一次,那么  
  92.             '''''cv2.imshow("temp",image_np) 
  93.             cv2.waitKey()'''  
  94.             #print label_np  
  95.             #print image_np.shape  
  96.   
  97.   
  98.             batch_image_np,batch_label_np=session.run([batch_image,batch_label])  
  99.             print batch_image_np.shape  
  100.             print batch_label_np.shape  
  101.   
  102.   
  103.   
  104.         coord.request_stop()#queue需要关闭,否则报错  
  105.         coord.join(threads)  
  106. #test()  

2、网络架构与训练

经过上面的数据格式处理,接着我们只要写一写网络结构、网络优化方法,把数据搞进网络中就可以了,具体示例代码如下:

[python]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. #coding=utf-8  
  2. import  tensorflow as tf  
  3. from  data_encoder_decoeder import  encode_to_tfrecords,decode_from_tfrecords,get_batch,get_test_batch  
  4. import  cv2  
  5. import  os  
  6.   
  7. class network(object):  
  8.     def __init__(self):  
  9.         with tf.variable_scope("weights"):  
  10.             self.weights={  
  11.                 #39*39*3->36*36*20->18*18*20  
  12.                 'conv1':tf.get_variable('conv1',[4,4,3,20],initializer=tf.contrib.layers.xavier_initializer_conv2d()),  
  13.                 #18*18*20->16*16*40->8*8*40  
  14.                 'conv2':tf.get_variable('conv2',[3,3,20,40],initializer=tf.contrib.layers.xavier_initializer_conv2d()),  
  15.                 #8*8*40->6*6*60->3*3*60  
  16.                 'conv3':tf.get_variable('conv3',[3,3,40,60],initializer=tf.contrib.layers.xavier_initializer_conv2d()),  
  17.                 #3*3*60->120  
  18.                 'fc1':tf.get_variable('fc1',[3*3*60,120],initializer=tf.contrib.layers.xavier_initializer()),  
  19.                 #120->6  
  20.                 'fc2':tf.get_variable('fc2',[120,6],initializer=tf.contrib.layers.xavier_initializer()),  
  21.                 }  
  22.         with tf.variable_scope("biases"):  
  23.             self.biases={  
  24.                 'conv1':tf.get_variable('conv1',[20,],initializer=tf.constant_initializer(value=0.0, dtype=tf.float32)),  
  25.                 'conv2':tf.get_variable('conv2',[40,],initializer=tf.constant_initializer(value=0.0, dtype=tf.float32)),  
  26.                 'conv3':tf.get_variable('conv3',[60,],initializer=tf.constant_initializer(value=0.0, dtype=tf.float32)),  
  27.                 'fc1':tf.get_variable('fc1',[120,],initializer=tf.constant_initializer(value=0.0, dtype=tf.float32)),  
  28.                 'fc2':tf.get_variable('fc2',[6,],initializer=tf.constant_initializer(value=0.0, dtype=tf.float32))  
  29.   
  30.             }  
  31.   
  32.     def inference(self,images):  
  33.         # 向量转为矩阵  
  34.         images = tf.reshape(images, shape=[-139,393])# [batch, in_height, in_width, in_channels]  
  35.         images=(tf.cast(images,tf.float32)/255.-0.5)*2#归一化处理  
  36.   
  37.   
  38.   
  39.         #第一层  
  40.         conv1=tf.nn.bias_add(tf.nn.conv2d(images, self.weights['conv1'], strides=[1111], padding='VALID'),  
  41.                              self.biases['conv1'])  
  42.   
  43.         relu1= tf.nn.relu(conv1)  
  44.         pool1=tf.nn.max_pool(relu1, ksize=[1221], strides=[1221], padding='VALID')  
  45.   
  46.   
  47.         #第二层  
  48.         conv2=tf.nn.bias_add(tf.nn.conv2d(pool1, self.weights['conv2'], strides=[1111], padding='VALID'),  
  49.                              self.biases['conv2'])  
  50.         relu2= tf.nn.relu(conv2)  
  51.         pool2=tf.nn.max_pool(relu2, ksize=[1221], strides=[1221], padding='VALID')  
  52.   
  53.   
  54.         # 第三层  
  55.         conv3=tf.nn.bias_add(tf.nn.conv2d(pool2, self.weights['conv3'], strides=[1111], padding='VALID'),  
  56.                              self.biases['conv3'])  
  57.         relu3= tf.nn.relu(conv3)  
  58.         pool3=tf.nn.max_pool(relu3, ksize=[1221], strides=[1221], padding='VALID')  
  59.   
  60.   
  61.         # 全连接层1,先把特征图转为向量  
  62.         flatten = tf.reshape(pool3, [-1self.weights['fc1'].get_shape().as_list()[0]])  
  63.   
  64.         drop1=tf.nn.dropout(flatten,0.5)  
  65.         fc1=tf.matmul(drop1, self.weights['fc1'])+self.biases['fc1']  
  66.   
  67.         fc_relu1=tf.nn.relu(fc1)  
  68.   
  69.         fc2=tf.matmul(fc_relu1, self.weights['fc2'])+self.biases['fc2']  
  70.   
  71.         return  fc2  
  72.     def inference_test(self,images):  
  73.                 # 向量转为矩阵  
  74.         images = tf.reshape(images, shape=[-139,393])# [batch, in_height, in_width, in_channels]  
  75.         images=(tf.cast(images,tf.float32)/255.-0.5)*2#归一化处理  
  76.   
  77.   
  78.   
  79.         #第一层  
  80.         conv1=tf.nn.bias_add(tf.nn.conv2d(images, self.weights['conv1'], strides=[1111], padding='VALID'),  
  81.                              self.biases['conv1'])  
  82.   
  83.         relu1= tf.nn.relu(conv1)  
  84.         pool1=tf.nn.max_pool(relu1, ksize=[1221], strides=[1221], padding='VALID')  
  85.   
  86.   
  87.         #第二层  
  88.         conv2=tf.nn.bias_add(tf.nn.conv2d(pool1, self.weights['conv2'], strides=[1111], padding='VALID'),  
  89.                              self.biases['conv2'])  
  90.         relu2= tf.nn.relu(conv2)  
  91.         pool2=tf.nn.max_pool(relu2, ksize=[1221], strides=[1221], padding='VALID')  
  92.   
  93.   
  94.         # 第三层  
  95.         conv3=tf.nn.bias_add(tf.nn.conv2d(pool2, self.weights['conv3'], strides=[1111], padding='VALID'),  
  96.                              self.biases['conv3'])  
  97.         relu3= tf.nn.relu(conv3)  
  98.         pool3=tf.nn.max_pool(relu3, ksize=[1221], strides=[1221], padding='VALID')  
  99.   
  100.   
  101.         # 全连接层1,先把特征图转为向量  
  102.         flatten = tf.reshape(pool3, [-1self.weights['fc1'].get_shape().as_list()[0]])  
  103.   
  104.         fc1=tf.matmul(flatten, self.weights['fc1'])+self.biases['fc1']  
  105.         fc_relu1=tf.nn.relu(fc1)  
  106.   
  107.         fc2=tf.matmul(fc_relu1, self.weights['fc2'])+self.biases['fc2']  
  108.   
  109.         return  fc2  
  110.   
  111.     #计算softmax交叉熵损失函数  
  112.     def sorfmax_loss(self,predicts,labels):  
  113.         predicts=tf.nn.softmax(predicts)  
  114.         labels=tf.one_hot(labels,self.weights['fc2'].get_shape().as_list()[1])  
  115.         loss =-tf.reduce_mean(labels * tf.log(predicts))# tf.nn.softmax_cross_entropy_with_logits(predicts, labels)  
  116.         self.cost= loss  
  117.         return self.cost  
  118.     #梯度下降  
  119.     def optimer(self,loss,lr=0.001):  
  120.         train_optimizer = tf.train.GradientDescentOptimizer(lr).minimize(loss)  
  121.   
  122.         return train_optimizer  
  123.   
  124.   
  125. def train():  
  126.     encode_to_tfrecords("data/train.txt","data",'train.tfrecords',(45,45))  
  127.     image,label=decode_from_tfrecords('data/train.tfrecords')  
  128.     batch_image,batch_label=get_batch(image,label,batch_size=50,crop_size=39)#batch 生成测试  
  129.   
  130.   
  131.   
  132.   
  133.   
  134.   
  135.   
  136.    #网络链接,训练所用  
  137.     net=network()  
  138.     inf=net.inference(batch_image)  
  139.     loss=net.sorfmax_loss(inf,batch_label)  
  140.     opti=net.optimer(loss)  
  141.   
  142.   
  143.     #验证集所用  
  144.     encode_to_tfrecords("data/val.txt","data",'val.tfrecords',(45,45))  
  145.     test_image,test_label=decode_from_tfrecords('data/val.tfrecords',num_epoch=None)  
  146.     test_images,test_labels=get_test_batch(test_image,test_label,batch_size=120,crop_size=39)#batch 生成测试  
  147.     test_inf=net.inference_test(test_images)  
  148.     correct_prediction = tf.equal(tf.cast(tf.argmax(test_inf,1),tf.int32), test_labels)  
  149.     accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))  
  150.   
  151.   
  152.   
  153.   
  154.   
  155.     init=tf.initialize_all_variables()  
  156.     with tf.Session() as session:  
  157.         session.run(init)  
  158.         coord = tf.train.Coordinator()  
  159.         threads = tf.train.start_queue_runners(coord=coord)  
  160.         max_iter=100000  
  161.         iter=0  
  162.         if os.path.exists(os.path.join("model",'model.ckpt')) is True:  
  163.             tf.train.Saver(max_to_keep=None).restore(session, os.path.join("model",'model.ckpt'))  
  164.         while iter<max_iter:  
  165.             loss_np,_,label_np,image_np,inf_np=session.run([loss,opti,batch_label,batch_image,inf])  
  166.             #print image_np.shape  
  167.             #cv2.imshow(str(label_np[0]),image_np[0])  
  168.             #print label_np[0]  
  169.             #cv2.waitKey()  
  170.             #print label_np  
  171.             if iter%50==0:  
  172.                 print 'trainloss:',loss_np  
  173.             if iter%500==0:  
  174.                 accuracy_np=session.run([accuracy])  
  175.                 print '***************test accruacy:',accuracy_np,'*******************'  
  176.                 tf.train.Saver(max_to_keep=None).save(session, os.path.join('model','model.ckpt'))  
  177.             iter+=1  
  178.   
  179.   
  180.   
  181.   
  182.   
  183.         coord.request_stop()#queue需要关闭,否则报错  
  184.         coord.join(threads)  
  185.   
  186. train()  

3、可视化显示

(1)首先再源码中加入需要跟踪的变量:

[python]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. <span style="font-size:18px;">tf.scalar_summary("cost_function", loss)#损失函数值</span>  
(2)然后定义执行操作:

[python]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. <span style="font-size:18px;">merged_summary_op = tf.merge_all_summaries()</span>  
(3)再session中定义保存路径:
[python]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. <span style="font-size:18px;">summary_writer = tf.train.SummaryWriter('log', session.graph)</span>  
(4)然后再session执行的时候,保存:
[python]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. <span style="font-size:18px;">            summary_str,loss_np,_=session.run([merged_summary_op,loss,opti])  
  2.             summary_writer.add_summary(summary_str, iter)</span>  
(5)最后只要训练完毕后,直接再终端输入命令:
[python]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. <span style="font-size:18px;">python /usr/local/lib/python2.7/dist-packages/tensorflow/tensorboard/tensorboard.py --logdir=log</span>  
然后打开浏览器网址:
[python]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. <span style="font-size:18px;">http://0.0.0.0:6006</span>  

即可观训练曲线。

4\、测试阶段

测试阶段主要是直接通过加载图模型、读取参数等,然后直接通过tensorflow的相关函数,进行调用,而不需要网络架构相关的代码;通过内存feed_dict的方式,对相关的输入节点赋予相关的数据,进行前向传导,并获取相关的节点数值。

[python]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. #coding=utf-8  
  2. import  tensorflow  as tf  
  3. import  os  
  4. import  cv2  
  5.   
  6. def load_model(session,netmodel_path,param_path):  
  7.     new_saver = tf.train.import_meta_graph(netmodel_path)  
  8.     new_saver.restore(session, param_path)  
  9.     x= tf.get_collection('test_images')[0]#在训练阶段需要调用tf.add_to_collection('test_images',test_images),保存之  
  10.     y = tf.get_collection("test_inf")[0]  
  11.     batch_size = tf.get_collection("batch_size")[0]  
  12.     return  x,y,batch_size  
  13.   
  14. def load_images(data_root):  
  15.     filename_queue = tf.train.string_input_producer(data_root)  
  16.     image_reader = tf.WholeFileReader()  
  17.     key,image_file = image_reader.read(filename_queue)  
  18.     image = tf.image.decode_jpeg(image_file)  
  19.     return image, key  
  20.   
  21. def test(data_root="data/race/cropbrown"):  
  22.     image_filenames=os.listdir(data_root)  
  23.     image_filenames=[(data_root+'/'+i) for i in image_filenames]  
  24.   
  25.   
  26.     #print cv2.imread(image_filenames[0]).shape  
  27.     #image,key=load_images(image_filenames)  
  28.     race_listsrc=['black','brown','white','yellow']  
  29.     with tf.Session() as session:  
  30.         coord = tf.train.Coordinator()  
  31.         threads = tf.train.start_queue_runners(coord=coord)  
  32.   
  33.   
  34.   
  35.         x,y,batch_size=load_model(session,os.path.join("model",'model_ori_race.ckpt.meta'),  
  36.                        os.path.join("model",'model_ori_race.ckpt'))  
  37.         predict_label=tf.cast(tf.argmax(y,1),tf.int32)  
  38.         print x.get_shape()  
  39.         for imgf in image_filenames:  
  40.             image=cv2.imread(imgf)  
  41.             image=cv2.resize(image,(76,76)).reshape((1,76,76,3))  
  42.             print "cv shape:",image.shape  
  43.   
  44.   
  45.             #cv2.imshow("t",image_np[:,:,::-1])  
  46.             y_np=session.run(predict_label,feed_dict = {x:image, batch_size:1})  
  47.             print race_listsrc[y_np]  
  48.   
  49.   
  50.         coord.request_stop()#queue需要关闭,否则报错  
  51.         coord.join(threads)  



4、移植阶段

(1)一个算法经过实验阶段后,接着就要进入移植商用,因此接着需要采用tensorflow的c api函数,直接进行预测推理,首先我们先把tensorflow编译成链接库,然后编写cmake,调用tensorflow链接库:

[cpp]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. <span style="font-size:18px;">bazel build -c opt //tensorflow:libtensorflow.so  
  2. </span>  

bazel-bin/tensorflow目录下会生成libtensorflow.so文件


(2)调用api函数


tf.contrib.layers.batch_norm(x, decay=0.9, updates_collections=None, epsilon=self.epsilon, scale=True, scope=self.name)

5、量化移植阶段



[python]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. <span style="font-size:18px;">import  tensorflow as tf  
  2. with tf.variable_scope('foo'):#在没有启用reuse的情况下,如果该变量还未被创建,那么就创建该变量,如果已经创建过了,那么就获取该共享变量  
  3.     v=tf.get_variable('v',[1])  
  4. with tf.variable_scope('foo',reuse=True):#如果启用了reuse,那么编译的时候,如果get_variable没有遇到一个已经创建的变量,是会出错的  
  5.     v1=tf.get_variable('v1',[1])</span>  






[python]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. <span style="font-size:18px;">import  tensorflow.nn.rnn_cell  
  2.   
  3. lstm = rnn_cell.BasicLSTMCell(lstm_size)#创建一个lstm cell单元类,隐藏层神经元个数为lstm_size  
  4.   
  5. state = tf.zeros([batch_size, lstm.state_size])#一个序列隐藏层的状态值  
  6.   
  7. loss = 0.0  
  8. for current_batch_of_words in words_in_dataset:  
  9.     output, state = lstm(current_batch_of_words, state)#返回值为隐藏层神经元的输出  
  10.     logits = tf.matmul(output, softmax_w) + softmax_b#matmul矩阵点乘  
  11.     probabilities = tf.nn.softmax(logits)#softmax输出  
  12.     loss += loss_function(probabilities, target_words)</span>  


1、one-hot函数:

[python]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. <span style="font-size:18px;">#ont hot 可以把训练数据的标签,直接转换成one_hot向量,用于交叉熵损失函数  
  2. import tensorflow as tf  
  3. a=tf.convert_to_tensor([[1],[2],[4]])  
  4. b=tf.one_hot(a,5)</span>  

>>b的值为
[python]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. <span style="font-size:18px;">[[[ 0.  1.  0.  0.  0.]]  
  2.   
  3.  [[ 0.  0.  1.  0.  0.]]  
  4.   
  5.  [[ 0.  0.  0.  0.  1.]]]</span>  

2、assign_sub

[python]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. <span style="font-size:18px;">import tensorflow as tf  
  2.   
  3. x = tf.Variable(10, name="x")  
  4. sub=x.assign_sub(3)#如果直接采用x.assign_sub,那么可以看到x的值也会发生变化  
  5. init_op=tf.initialize_all_variables()  
  6. with tf.Session() as sess:  
  7.     sess.run(init_op)  
  8.     print sub.eval()  
  9.     print x.eval()</span>  
可以看到输入sub=x=7

[python]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. <span style="font-size:18px;">state_ops.assign_sub</span>  
采用state_ops的assign_sub也是同样sub=x=7

也就是说assign函数返回结果值的同时,变量本身的值也会被改变
3、变量查看

[python]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. <span style="font-size:18px;">    #查看所有的变量  
  2.     for l in tf.all_variables():  
  3.         print l.name</span>  

4、slice函数:

[python]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. <span style="font-size:18px;">import cv2  
  2. import  tensorflow as tf  
  3. #slice 函数可以用于切割子矩形图片,参数矩形框的rect,begin=(minx,miny),size=(width,height)  
  4. minx=20  
  5. miny=30  
  6. height=100  
  7. width=200  
  8.   
  9. image=tf.placeholder(dtype=tf.uint8,shape=(386,386,3))  
  10. rect_image=tf.slice(image,(miny,minx,0),(height,width,-1))  
  11.   
  12.   
  13. cvimage=cv2.imread("1.jpg")  
  14. cv2.imshow("cv2",cvimage[miny:(miny+height),minx:(minx+width),:])  
  15.   
  16.   
  17. with tf.Session() as sess:  
  18.     tfimage=sess.run([rect_image],{image:cvimage})  
  19.     cv2.imshow('tf',tfimage[0])  
  20. cv2.waitKey()</span>  

5、正太分布:

tf.truncated_normal

猜你喜欢

转载自blog.csdn.net/Callon_H/article/details/60343633
今日推荐