tensorflow笔记

  • tf.name_scope()

在某个tf.name_scope()指定的区域中定义的所有对象及各种操作,他们的“name”属性上会增加该命名区的区域名,用以区别对象属于哪个区域

ref:tensorflow中的“tf.name_scope()”有什么用?

  • tf.placeholder
tf.placeholder(dtype, shape=None, name=None)

此函数用于定义过程,在执行的时候再赋具体的值。

赋值一般用sess.run(feed_dict = {x:xs, y_:ys}),其中x,y_是用placeholder创建出来的。

为什么要使用tf.placeholder?因为每一个tensor值在graph上都是一个op,当我们将train数据分成一个个minibatch然后传入网络进行训练时,每一个minibatch都将是一个op,这样的话,一副graph上的op未免太多,也会产生巨大的开销;于是就有tf.placeholder,我们每次可以将 一个minibatch传入到x = tf.placeholder(tf.float32,[None,32])上,下一次传入的x都替换掉上一次传入的x,这样就对于所有传入的minibatch x就只会产生一个op,不会产生其他多余的op,进而减少了graph的开销。

  • tf.get_variable()

获取一个已经存在的变量或者创建一个新的变量.

tf.get_variable(name,  shape, initializer): name就是变量的名称,shape是变量的维度,initializer是变量初始化的方式

,初始化的方式有以下几种:

tf.constant_initializer:常量初始化函数

tf.random_normal_initializer:正态分布

tf.truncated_normal_initializer:截取的正态分布

tf.random_uniform_initializer:均匀分布

tf.zeros_initializer:全部是0

tf.ones_initializer:全是1

tf.uniform_unit_scaling_initializer:满足均匀分布,但不影响输出数量级的随机值

import tensorflow as tf;  
import numpy as np;  
import matplotlib.pyplot as plt;  
  
a1 = tf.get_variable(name='a1', shape=[2,3], initializer=tf.random_normal_initializer(mean=0, stddev=1))
a2 = tf.get_variable(name='a2', shape=[1], initializer=tf.constant_initializer(1))
a3 = tf.get_variable(name='a3', shape=[2,3], initializer=tf.ones_initializer())
 
with tf.Session() as sess:
	sess.run(tf.initialize_all_variables())
	print sess.run(a1)
	print sess.run(a2)
	print sess.run(a3)
  • tf.summary.histogram()

在训练神经网络时,当需要查看一个张量在训练过程中值的分布情况时,可通过tf.summary.histogram()将其分布情况以直方图的形式在TensorBoard直方图仪表板上显示.

ref:tf.summary.histogram与直方图

  • tf.nn.embedding_lookup

选取一个张量里面索引对应的元素。tf.nn.embedding_lookup(params, ids):params可以是张量也可以是数组等,id就是对应的索引。

p=tf.Variable(tf.random_normal([10,1]))    #生成10*1的张量
b = tf.nn.embedding_lookup(p, [1, 3])      #查找张量中的序号为1和3的
 
with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    print(sess.run(b))
    print(sess.run(p))
    print(p)
    print(type(p))


输出:

[[0.15791859]
 [0.6468804 ]]
[[-0.2737084 ]
 [ 0.15791859]
 [-0.01315552]
 [ 0.6468804 ]
 [-1.4090979 ]
 [ 2.1583703 ]
 [ 1.4137447 ]
 [ 0.20688428]
 [-0.32815856]
 [-1.0601649 ]]
<tf.Variable 'Variable:0' shape=(10, 1) dtype=float32_ref>
<class 'tensorflow.python.ops.variables.Variable'>
  • tf.reduce_mean

求平均值

import tensorflow as tf
 
x = [[1,2,3],
      [1,2,3]]
 
xx = tf.cast(x,tf.float32)
 
mean_all = tf.reduce_mean(xx, keep_dims=False)
mean_0 = tf.reduce_mean(xx, axis=0, keep_dims=False)
mean_1 = tf.reduce_mean(xx, axis=1, keep_dims=False)
 
 
with tf.Session() as sess:
    m_a,m_0,m_1 = sess.run([mean_all, mean_0, mean_1])
 
print m_a    # output: 2.0
print m_0    # output: [ 1.  2.  3.]
print m_1    #output:  [ 2.  2.]
  • tf.cast()

作用是执行 tensorflow 中张量数据类型转换,比如读入的图片如果是int8类型的,一般在要在训练前把图像的数据格式转换为float32。

import tensorflow as tf
 
t1 = tf.Variable([1,2,3,4,5])
t2 = tf.cast(t1,dtype=tf.float32)
 
print 't1: {}'.format(t1)
print 't2: {}'.format(t2)
 
with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    sess.run(t2)
    print t2.eval()
    # print(sess.run(t2))

t1: <tf.Variable 'Variable:0' shape=(5,) dtype=int32_ref>
t2: Tensor("Cast:0", shape=(5,), dtype=float32)
[ 1.  2.  3.  4.  5.]
  • tf.tile

tile()函数是用来对张量(Tensor)进行扩展的,其特点是对当前张量内的数据进行一定规则的复制。最终的输出张量维度不变。input是待扩展的张量,multiples是扩展方法。
假如input是一个3维的张量。那么mutiples就必须是一个1x3的1维张量。这个张量的三个值依次表示input的第1,第2,第3维数据扩展几倍。
具体举一个例子:

tf.tile(
    input,
    multiples,
    name=None
)

import tensorflow as tf

a = tf.constant([[1, 2], [3, 4], [5, 6]], dtype=tf.float32)
a1 = tf.tile(a, [2, 3])
with tf.Session() as sess:
    print(sess.run(a))
    print(sess.run(tf.shape(a)))
    print(sess.run(a1))
    print(sess.run(tf.shape(a1)))
=======
[[1. 2.]
 [3. 4.]
 [5. 6.]]
[3 2]
[[1. 2. 1. 2. 1. 2.]
 [3. 4. 3. 4. 3. 4.]
 [5. 6. 5. 6. 5. 6.]
 [1. 2. 1. 2. 1. 2.]
 [3. 4. 3. 4. 3. 4.]
 [5. 6. 5. 6. 5. 6.]]
[6 6]
  • tf.AUTO_REUSE

通过get_variable("v")函数获取变量时,如果tf.variable_scope的reuse参数是True, 如果v是已经被创建过了就直接返回,但是如果没有创建会报错。如果设置成False,变量v如果没有被创建过就直接创建,如果创建过就报错。AUTO_REUSE的好处就是实现:如果创建过就返回,没有创建过就创建一个新的变量返回.

  • tf.layers.dense

tf.layers.dense(

    inputs,

    units,

    activation=None,

    use_bias=True,

    kernel_initializer=None,  ##卷积核的初始化器

    bias_initializer=tf.zeros_initializer(),  ##偏置项的初始化器,默认初始化为0

    kernel_regularizer=None,    ##卷积核的正则化,可选

    bias_regularizer=None,    ##偏置项的正则化,可选

    activity_regularizer=None,   ##输出的正则化函数

    kernel_constraint=None,   

    bias_constraint=None,

    trainable=True,

    name=None,  ##层的名字

    reuse=None  ##是否重复使用参数

)

dense1 = tf.layers.dense(inputs=pool3, units=1024, activation=tf.nn.relu)

dense2= tf.layers.dense(inputs=dense1, units=512, activation=tf.nn.relu)

logits= tf.layers.dense(inputs=dense2, units=10, activation=None)

部分参数解释:

inputs:输入该网络层的数据

units:输出的维度大小,改变inputs的最后一维

activation:激活函数,即神经网络的非线性变化

use_bias:使用bias为True(默认使用),不用bias改成False即可,是否使用偏置项

trainable=True:表明该层的参数是否参与训练。如果为真则变量加入到图集合中

tf.where()

1、tf.where(tensor)。tensor 为一个bool 型张量,where函数将返回其中为true的元素的索引。如上图官方注释

2、tf.where(tensor,a,b)。a,b为和tensor相同维度的tensor,将tensor中的true位置元素替换为a中对应位置元素,false的替换为b中对应位置元素。

用法二
import tensorflow as tf
import numpy as np
sess=tf.Session()

a=np.array([[1,0,0],[0,1,1]])
a1=np.array([[3,2,3],[4,5,6]])

print(sess.run(tf.equal(a,1)))
print(sess.run(tf.where(tf.equal(a,1),a1,1-a1)))

>>[[true,false,false],[false,true,true]]

>>[[3,-1,-2],[-3,5,6]]

用法一
tf.where(input, name=None)`
Returns locations of true values in a boolean tensor.

This operation returns the coordinates of true elements in input. The coordinates are returned in a 2-D tensor where the first dimension (rows) represents the number of true elements, and the second dimension (columns) represents the coordinates of the true elements. Keep in mind, the shape of the output tensor can vary depending on how many true values there are in input. Indices are output in row-major order.

For example:
# 'input' tensor is [[True, False]
#                    [True, False]]
# 'input' has two true values, so output has two coordinates.
# 'input' has rank of 2, so coordinates have two indices.
where(input) ==> [[0, 0],
                  [1, 0]]

# `input` tensor is [[[True, False]
#                     [True, False]]
#                    [[False, True]
#                     [False, True]]
#                    [[False, False]
#                     [False, True]]]
# 'input' has 5 true values, so output has 5 coordinates.
# 'input' has rank of 3, so coordinates have three indices.
where(input) ==> [[0, 0, 0],
                  [0, 1, 0],
                  [1, 0, 1],
                  [1, 1, 1],
                  [2, 1, 1]]

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值