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

『TensorFlow』简单的数学计算&张量操作

时间:2017-12-10 18:56:59      阅读:1151      评论:0      收藏:0      [点我收藏+]

标签:returns   squeeze   扩展   代码   adc   weight   psi   数学   神经网络   

tf.pow()

tf.sqrt()

tf.add()

tf.add_n()

几种加法


tf.nn.bias_add 是 tf.add 的一个特例
二者均支持 broadcasting(广播机制),也即两个操作数最后一个维度保持一致。
除了支持最后一个维度保持一致的两个操作数相加外,tf.add 还支持第二个操作数是一维的情况

tf.add_n():多项连加 return tf.add_n(tf.get_collection(‘losses‘),name=‘total_loss‘)

tf.subtract()        :减法

tf.matmul()         :矩阵乘法

点乘&矩阵乘

tf.multiply和tf.matmul区别
解析:
(1)tf.multiply是点乘,即Returns x * y element-wise.
(2)tf.matmul是矩阵乘法,即Multiplies matrix a by matrix b, producing a * b.

tf.reduce_sum()  :求和

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.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.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.shape(x)

  tf.shape()中x数据类型可以是tensor,list,array,返回是一个tensor.

  shape=tf.placeholder(tf.float32, shape=[None, 227,227,3] )

  我们经常会这样来feed数据,如果在运行的时候想知道None到底是多少,这时候,只能通过tf.shape(x)[0]这种方式来获得.

tensor.get_shape()

  只有tensor有这个方法, 返回是一个tuple.

张量切片

tf.slice

解析:slice(input_, begin, size, name=None):Extracts a slice from a tensor.

假设input为[[[1, 1, 1], [2, 2, 2]], [[3, 3, 3], [4, 4, 4]], [[5, 5, 5], [6, 6, 6]]],如下所示:

(1)tf.slice(input, [1, 0, 0], [1, 1, 3]) ==> [[[3, 3, 3]]]

(2)tf.slice(input, [1, 0, 0], [1, 2, 3]) ==> [[[3, 3, 3], [4, 4, 4]]]

(3)tf.slice(input, [1, 0, 0], [2, 1, 3]) ==> [[[3, 3, 3]], [[5, 5, 5]]]

 

tf.strided_slice(record_bytes, [0], [label_bytes]), tf.int32)

在看cifar10的例子的时候,必然会看到一个函数,官方给的文档注释长而晦涩,基本等于0.网上也有这个函数,但解释差劲或者基本没有解释,函数的原型是酱紫的.

def strided_slice(input_,
                  begin,
                  end,
                  strides=None,
                  begin_mask=0,
                  end_mask=0,
                  ellipsis_mask=0,
                  new_axis_mask=0,
                  shrink_axis_mask=0,
                  var=None,
                  name=None):
  """Extracts a strided slice from a tensor.
‘input‘= [[[1, 1, 1], [2, 2, 2]],
             [[3, 3, 3], [4, 4, 4]],
             [[5, 5, 5], [6, 6, 6]]]

来把输入变个型,可以看成3维的tensor,从外向为1,2,3维

[[[1, 1, 1], [2, 2, 2]],
 [[3, 3, 3], [4, 4, 4]],
 [[5, 5, 5], [6, 6, 6]]]

以tf.strided_slice(input, [0,0,0], [2,2,2], [1,2,1])调用为例,start = [0,0,0] , end = [2,2,2], stride = [1,2,1],求一个[start, end)的一个片段,注意end为开区间

第1维 start = 0 , end = 2, stride = 1, 所以取 0 , 1行,此时的输出

[[[1, 1, 1], [2, 2, 2]],
 [[3, 3, 3], [4, 4, 4]]]

第2维时, start = 0 , end = 2 , stride = 2, 所以只能取0行,此时的输出

[[[1, 1, 1]],
 [[3, 3, 3]]]

第3维的时候,start = 0, end = 2, stride = 1, 可以取0,1行,此时得到的就是最后的输出

[[[1, 1]],
 [[3, 3]]]

整理之后最终的输出为:

[[[1,1],[3,3]]]

类似代码如下:

import tensorflow as tf   
data = [[[1, 1, 1], [2, 2, 2]],   
     [[3, 3, 3], [4, 4, 4]],   
     [[5, 5, 5], [6, 6, 6]]]   
x = tf.strided_slice(data,[0,0,0],[1,1,1])   
with tf.Session() as sess:   
print(sess.run(x))  

 

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]。

『TensorFlow』简单的数学计算&张量操作

标签:returns   squeeze   扩展   代码   adc   weight   psi   数学   神经网络   

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

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