码迷,mamicode.com
首页 > 其他好文 > 详细

『TensorFlow』常用函数实践笔记

时间:2017-06-06 18:32:21      阅读:6655      评论:0      收藏:0      [点我收藏+]

标签:经验   htm   mode   cep   cal   scalar   声明   png   cross   

查询列表:

『TensorFlow』函数查询列表_数值计算

『TensorFlow』函数查询列表_张量属性调整

『TensorFlow』函数查询列表_神经网络相关

经验之谈:

节点张量铺设好了之后,只要不加sess.run(),可以运行脚本检查张量节点是否匹配,无需传入实际数据流。

‘conv1‘指节点,‘conv1:0‘指节点输出的第一个张量。

sess上下文环境中的函数调用即使不传入sess句柄,函数体内也存在于默认的sess环境中,可以直接sess.run()。

image_holder = tf.placeholder(tf.float32,[None, None, None, 3]),使用None回避指定大小。

张量相关:

tf.cast():bool->数字

re = tf.cast([True,False],tf.float32)
sess = tf.Session()
sess.run(re)
# Out[6]: 
# array([ 1.,  0.], dtype=float32)

tf.argmax:(list,维度)

re = tf.argmax([[0,0.5]],1)
sess.run(re)
# Out[20]: 
# array([1])

 tf.reduce_mean():求均值,直接给源码定义中的注释

For example:
  ```python
  # ‘x‘ is [[1., 1.]
  #         [2., 2.]]
  tf.reduce_mean(x) ==> 1.5
  tf.reduce_mean(x, 0) ==> [1.5, 1.5]
  tf.reduce_mean(x, 1) ==> [1.,  2.]
  ```
reduction_indices: The old (deprecated) name for axis.

 tf.squeeze():数据降维,只裁剪等于1的维度

不指定维度则裁剪所有长度为1的维度

import tensorflow as tf

arr = tf.Variable(tf.truncated_normal([3,4,1,6,1], stddev=0.1))

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

sess.run(arr).shape
# Out[12]: 
# (3, 4, 1, 6, 1)
sess.run(tf.squeeze(arr,[2,])).shape
# Out[17]: 
# (3, 4, 6, 1)
sess.run(tf.squeeze(arr,[2,4])).shape
# Out[16]: 
# (3, 4, 6)
sess.run(tf.squeeze(arr)).shape
# Out[19]: 
# (3, 4, 6)

tf.nn.softmax()分类器:把数组最后一维转化为概率分布

import  tensorflow as tf  
sess.run(tf.nn.softmax([1.,2.,3.,4.]))
# Out[12]: 
# array([ 0.0320586 ,  0.08714432,  0.23688281,  0.64391422], dtype=float32)
sess.run(tf.nn.softmax([1.,1.,1.,1.]))
# Out[13]: 
# array([ 0.25,  0.25,  0.25,  0.25], dtype=float32)
sess.run(tf.nn.softmax([[1.,1.,1.,1.],[7.,1.,1.,1.]]))
# Out[16]: 
# array([[ 0.25      ,  0.25      ,  0.25      ,  0.25      ],
#        [ 0.99261862,  0.00246046,  0.00246046,  0.00246046]], dtype=float32)

 tf.concat([t1,t2,t3...],dim):矩阵拼接,注意在1.x版本之前和之后dim和[t]的顺序是改变了的

这个函数乍看之下不好理解合成方向,实际把合成张量转化为np数组查看shape后就很好理解了:

import tensorflow as tf
import numpy as np
t1 = np.asarray([[1, 2, 3], [4, 5, 6]])
t2 = np.asarray([[7, 8, 9], [10, 11, 12]])
print(t1.shape)
# (2, 3)
# 第零维度合成就是扩展数字2的大小
re = tf.concat([t1, t2],0) 
sess = tf.Session()
sess.run(re)
# array([[ 1,  2,  3],
#        [ 4,  5,  6],
#        [ 7,  8,  9],
#        [10, 11, 12]])

# 第一维度合成就是扩展数字3的大小
re = tf.concat([t1, t2],1) 
sess = tf.Session()
sess.run(re)
# array([[ 1,  2,  3,  7,  8,  9],
#        [ 4,  5,  6, 10, 11, 12]])

t1 = np.zeros([2,3,3])
t2 = np.ones([2,3,3])
print(t1,‘\n\n‘,t2)
re = tf.concat([t1, t2],2) 
sess = tf.Session()
sess.run(re)

# 第二维度合成就是扩展末尾的数字3的大小
# array([[[ 0.,  0.,  0.,  1.,  1.,  1.],
#         [ 0.,  0.,  0.,  1.,  1.,  1.],
#         [ 0.,  0.,  0.,  1.,  1.,  1.]],

#        [[ 0.,  0.,  0.,  1.,  1.,  1.],
#         [ 0.,  0.,  0.,  1.,  1.,  1.],
#         [ 0.,  0.,  0.,  1.,  1.,  1.]]])

 顺便一提,或者说接下来的其实才是很重要,合成神经网络输出的时候在深度方向(inception_v3)是数字3,[batch,heigh,width,depth]。

 

文件读写:

tf.gfile.FastGFile():读写文件,句柄具有.read()方法,实测凡是使用FastGFile的地方换成open()并不会报错(包括读取普通文件和读取tf模型文件)

‘‘‘
本代码也是加载图pb文件并获取节点张量句柄的标准流程,feed_dict输入节点 & sess.run(输出节点)就可以使用模型了
‘‘‘

#with gfile.FastGFile(os.path.join(MODEL_DIR,MODEL_FILE),‘rb‘) as f:       # 阅读器上下文
with open(os.path.join(MODEL_DIR, MODEL_FILE), ‘rb‘) as f:                 # 阅读器上下文
    graph_def = tf.GraphDef()                                              # 生成图
    graph_def.ParseFromString(f.read())                                    # 图加载模型
bottleneck_tensor,jpeg_data_tensor = tf.import_graph_def(                  # 从图上读取张量,同时把图设为默认图
   graph_def,
   return_elements=[BOTTLENECK_TENSOR_NAME,JPEG_DATA_TENSOR_NAME])


print(gfile.FastGFile(image_path,‘rb‘).read()==open(image_path,‘rb‘).read()) 
# True

 图片操作:

『TensorFlow』迁移学习_他山之石,可以攻玉中有更为详细的介绍

import tensorflow as tf
import matplotlib.pyplot as plt

# 使用‘r‘会出错,无法解码,只能以2进制形式读取
# img_raw = tf.gfile.FastGFile(‘./123.png‘,‘rb‘).read()
img_raw = open(‘./123.png‘,‘rb‘).read()

# 把二进制文件解码为uint8
img_0 = tf.image.decode_png(img_raw) #<------
# img_1 = tf.image.convert_image_dtype(img_0,dtype=tf.float32) #<------
# 绘图不用这句,它转换格式后用于后续图片预处理

sess = tf.Session()
print(sess.run(img_0).shape)
plt.imshow(sess.run(img_0))
plt.show()

 

变量相关:

tf.Variable()                                                                         # 声明变量
tf.get_variable()                                                                     # 声明变量
tf.global_variables_initializer()                                                     # 激活变量

 

可视化相关:

命名空间设置好:添加记录节点 -> 汇总记录节点 -> run汇总节点 -> [书写器生成]书写入文件 [-> 刷新缓冲区]

tf.summary.FileWriter(‘./‘, sess.graph)                                               # 书写器生成,会自动记录指定图
tf.summary.histogram(layer_name+‘/weights‘,Weights)                                   # 张量记录
tf.summary.scalar = (‘loss‘,cross_entropy)                                            # 标量记录
merged = tf.summary.merge_all()                                                       # 记录激活
train_writer = tf.summary.FileWriter(‘logs/train‘,sess.graph)                         # 书写器生成
train_result = sess.run(merged, feed_dict={xs: X_train, ys: y_train, keep_prob:1})    # run记录
train_writer.add_summary(train_result,i)                                              # 书写记录
train_writer.flush()                                                                  # 刷新缓冲区,立即写入文件

 

 域:

上下文内,指定层参数一并赋予

with arg_scope(
          [layers.conv2d, layers_lib.max_pool2d, layers_lib.avg_pool2d],
          stride=1,
          padding=‘SAME‘):
    pass

集合:

集合转换为字典,{节点名:输出张量值}

end_points = slim.utils.convert_collection_to_dict(end_points_collection)

损失函数:

计算softmax之后的交叉熵,方法一只针对单分类问题,据介绍优化更好可加速计算,labels形式batch大小的[条目1类,条目2类...],logits形式为batch大小的[[0,1,0...],[1,0,1,0...]‘...]这样,一般需要tf.argmax()辅助;方法二范用,labels和logits和方法一的logits样式一致:

cross_entropy_mean = tf.reduce_mean(
    tf.nn.sparse_softmax_cross_entropy_with_logits(
        labels=tf.argmax(labels,1), logits=logits), name=‘cross_entropy‘)

cross_entropy_mean = tf.reduce_mean(
    tf.nn.softmax_cross_entropy_with_logits(
        logits=logits, labels=labels), name=‘cross_entropy‘)

 

『TensorFlow』常用函数实践笔记

标签:经验   htm   mode   cep   cal   scalar   声明   png   cross   

原文地址:http://www.cnblogs.com/hellcat/p/6905878.html

(1)
(2)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!