目录
tf.trainable_variables() error: module 'tensorflow' has no attribute 'trainable_variables'
tf.random_normal() error: module 'tensorflow' has no attribute 'random_normal'
tf.layers.conv1d() error: module 'tensorflow' has no attribute 'layers'
tf.contrib.layers.bias_add() error: module 'tensorflow' has no attribute 'tf.contrib'
tf.nn.sigmoid_cross_entropy_with_logits()函数
tf.nn.softmax_cross_entropy_with_logits()函数
tf.nn.sparse_softmax_cross_entropy_with_logits()函数
乘:tf.sparse_tensor_dense_matmul()函数
tf 降维 dimensionality reduction
tf.placeholder error: module 'tensorflow' has no attribute 'placeholder'
tf.global_variables_initializer()和tf.local_variables_initializer()函数
tf.local_variables_initializer()函数
ConfigProto error: AttributeError: module 'tensorflow' has no attribute 'ConfigProto'
tf.confusion_matrix(labels, preds)混淆矩阵
tf.name_scope(name),用于定义python op的上下文管理器。
此上下文管理器将推送名称范围,这将使其中添加的所有操作的名称带有前缀。
例如,定义一个新的Python op my_op:
- def my_op(a, b, c, name=None):
- with tf.name_scope("MyOp") as scope:
- a = tf.convert_to_tensor(a, name="a")
- b = tf.convert_to_tensor(b, name="b")
- c = tf.convert_to_tensor(c, name="c")
- # Define some computation that uses `a`, `b`, and `c`.
- return foo_op(..., name=scope)
在执行时,张量a,b,c,将有名字MyOp/a,MyOp/b和MyOp/c。
当训练模型时,用变量来存储和更新参数。变量包含张量(Tensor)存放于内存的缓存区。建模时他们需要被明确地初始化,模型训练后它们必须被存储到磁盘。这些变量的值可以在之后模型训练和分析时被加载。
文本档描述两个TensorFlow类:
当创建一个变量时,你将一个张量作为初始值传入构造函数Variable()。TensorFlow提供了一系列操作符来初始化张量,初始值是常量或随机值。
Notice:所有这些操作符都需要你指定张量的shape。
- # Create two variables.
- weights = tf.Variable(tf.random_normal([784, 200], stddev=0.35),
- name="weights")
- biases = tf.Variable(tf.zeros([200]), name="biases")
变量的初始化必须在模型的其他操作运行之前先明确地完成。最简单的方法就是添加一个给所有变量初始化的操作,并在使用模型之前首先运行那个操作。
使用tf.initialize_all_variables()添加一个操作对变量做初始化。该函数便捷地添加一个op来初始化模型的所有变量。
- # Create two variables.
- weights = tf.Variable(tf.random_normal([784, 200], stddev=0.35),
- name="weights")
- biases = tf.Variable(tf.zeros([200]), name="biases")
- ...
- # Add an op to initialize the variables.
- init_op = tf.initialize_all_variables()
-
- # Later, when launching the model
- with tf.Session() as sess:
- # Run the init operation.
- sess.run(init_op)
- ...
- # Use the model
- ...
这个函数可以也仅可以查看可训练的向量。在生成变量variables时,无论是使用tf.Variable()还是tf.get_variable()生成变量,都会涉及到一个参数trainable,其默认为True。
__init__(
initial_value=None,
trainable=True,
collections=None,
validate_shape=True,
...
)
- w1 = tf.Variable(tf.random_normal([256, 2000]), 'w1')
- b1 = tf.get_variable('b1', [2000])
- learning_rate = tf.Variable(0.5, trainable=False)
- global_step = tf.Variable(0, trainable=False)
-
- trainable_params = tf.trainable_variables()
- trainable_params
- -------------------------------------------
- '''
- Variable:0
- b1:0
- '''
tf.compat.v1.trainable_variables
最简单的保存和恢复模型的方法是使用tf.train.Saver对象。构造器给graph的所有变量,添加save和restore opration。
- # Create some variables.
- v1 = tf.Variable(..., name="v1")
- v2 = tf.Variable(..., name="v2")
- ...
- # Add an op to initialize the variables.
- init_op = tf.initialize_all_variables()
-
- # Add ops to save and restore all the variables.
- saver = tf.train.Saver()
-
- # Later, launch the model, initialize the variables, do some work, save the
- # variables to disk.
- with tf.Session() as sess:
- sess.run(init_op)
- # Do some work with the model.
- ..
- # Save the variables to disk.
- save_path = saver.save(sess, "/tmp/model.ckpt")
- print "Model saved in file: ", save_path
Notice,当你从文件中恢复变量时,不需要事先对它们做初始化。
- # Create some variables.
- v1 = tf.Variable(..., name="v1")
- v2 = tf.Variable(..., name="v2")
- ...
- # Add ops to save and restore all the variables.
- saver = tf.train.Saver()
-
- # Later, launch the model, use the saver to restore variables from disk, and
- # do some work with the model.
- with tf.Session() as sess:
- # Restore variables from disk.
- saver.restore(sess, "/tmp/model.ckpt")
- print "Model restored."
- # Do some work with the model
- ...
tf.one_hot()函数返回一个one-hot tensor。
- one_hot(indices, depth, on_value=None, off_value=None, axis=None, dtype=None, name=None)
- '''
- 参数功能如下:
- 1)indices中的元素指示on_value的位置,on_value默认值为1,不指示的地方都为off_value,off_value默认值为0。indices可以是向量、矩阵。
- 2)depth表示输出张量的尺寸,indices中元素默认不超过(depth-1),如果超过,输出为[0,0,···,0]
- 3)on_value默认为1
- 4)off_value默认为0
- 5)dtype默认为tf.float32
- '''
tf.one_hot()函数规定输入的元素indices从0开始,最大的元素值不能超过(depth - 1)
- import tensorflow as tf
-
- indices = [0,2,3,5]
- depth1 = 6 # indices没有元素超过(depth-1)
- a = tf.one_hot(indices,depth1)
- -----------------------------------------
- '''
- a =
- [[1. 0. 0. 0. 0. 0.]
- [0. 0. 1. 0. 0. 0.]
- [0. 0. 0. 1. 0. 0.]
- [0. 0. 0. 0. 0. 1.]] # shape=(4,6)
- '''
TensorFlow表示一个稀疏张量,作为三个独立的稠密张量:indices,values和dense_shape。
- SparseTensor(indices=[[0, 0], [1, 2]], values=[1, 2], dense_shape=[3, 4])
-
- ------------------------------------------------------------------------
- [[1, 0, 0, 0]
- [0, 0, 2, 0]
- [0, 0, 0, 0]]
tf.random_normal()函数用于从“服从指定正态分布的序列”中随机取出指定个数的值。
- tf.random_normal(shape, mean=0.0, stddev=1.0, dtype=tf.float32, seed=None, name=None)
- shape: 一维整数张量或 Python 数组.输出张量的形状.
- mean: dtype 类型的0-D张量或 Python 值.正态分布的均值.
- stddev:dtype 类型的0-D张量或 Python 值.正态分布的标准差.
- dtype: 输出的类型.
- seed: 随机数种子,是一个整数,当设置之后,每次生成的随机数都一样
- name:操作的名称(可选).
- 输入
- a = tf.Variable(tf.random_normal([2,2],seed=1))
- b = tf.Variable(tf.truncated_normal([2,2],seed=2))
- init = tf.global_variables_initializer()
- with tf.Session() as sess:
- sess.run(init)
- print(sess.run(a))
- print(sess.run(b)
-
- 输出:
- [[-0.81131822 1.48459876]
- [ 0.06532937 -2.44270396]]
- [[-0.85811085 -0.19662298]
- [ 0.13895047 -1.22127688]]
- 指定seed之后,a的值不变,b的值也不变
tf.compat.v1.random_normal
生成常量
tf.constant(value, shape, dtype=None, name=None)
释义:生成常量
- value,值
- shape,数据形状
- dtype,数据类型
- name,名称
- import tensorflow as tf
-
- c = tf.constant(-1, shape=[2,3], dtype=tf.float32, name=None)
-
- with tf.Session() as sess:
- print(sess.run(c))
- -----------------------------------------------------
- '''
- [[-1. -1. -1.]
- [-1. -1. -1.]]
- '''
一维卷积一般用于处理文本数据,like序列数据,如自然语言处理领域。
一维卷积则只是在width或者height方向上进行滑动窗口并相乘求和。

- tf.layers.conv1d(
- inputs, 张量数据输入,一般是[batch, width, length]
- filters, 整数,输出空间的维度,可以理解为卷积核(滤波器)的个数
- kernel_size, 单个整数或元组/列表,指定1D(一维,一行或者一列)卷积窗口的长度。
- strides=1, 单个整数或元组/列表,指定卷积的步长,默认为1
- padding='valid', "SAME" or "VALID" (不区分大小写)是否用0填充,SAME用0填充;VALID不使用0填充,舍去不匹配的多余项。
- data_format='channels_last', 一个字符串,一个channels_last(默认)或channels_first。输入中维度的排序。channels_last:对应于形状的输入(batch, length, channels);channels_first:对应于形状输入(batch, channels, length)
- dilation_rate=1,
- activation=None, 激活函数
- use_bias=True, 该层是否使用偏差
- kernel_initializer=None, 卷积核的初始化
- bias_initializer=tf.zeros_initializer(), 偏置向量的初始化器
- kernel_regularizer=None, 卷积核的正则化项
- bias_regularizer=None, 偏置的正则化项
- activity_regularizer=None, 输出的正则化函数
- kernel_constraint=None,
- bias_constraint=None,
- trainable=True, Boolean,如果True,将变量添加到图collection中
- name=None,
- reuse=None Boolean,是否使用相同名称重用前一层的权重
- )
- import tensorflow as tf
-
- x = tf.get_variable(name="x", shape=[32, 512, 1024], initializer=tf.zeros_initializer)
- x = tf.layers.conv1d(
- x,
- filters=1, # 输出的第三个通道是1
- kernel_size=512, # 不用管它是多大,都不影响输出的shape
- strides=1,
- padding='same',
- data_format='channels_last',
- dilation_rate=1,
- use_bias=True,
- bias_initializer=tf.zeros_initializer())
-
- print(x) # Tensor("conv1d/BiasAdd:0", shape=(32, 512, 1), dtype=float32)
1. 输入数据的维度为[batch, data_length, data_width]=[32, 512, 1024],一般输入数据input第一维为batch_size,此处为32,意味着有32个样本,第二维度和第三维度分别表示输入的长和宽(512,1024)
2. 一维卷积核是二维的,也有长和宽,长为卷积核的数量kernel_size=512,因为卷积核的数量只有一个,所以宽为输入数据的宽度data_width=1024,所以一维卷积核的shape为[512,1024]
3. filteres是卷积核的个数,即输出数据的第三维度。filteres=1,第三维度为1
4. 所以卷积后的输出数据大小为[32, 512, 1]
tensorflow版本的问题
UserWarning: `tf.layers.conv1d` is deprecated and will be removed in a future version.
Please Use `tf.compat.v1.layers.conv1d()` instead。
Migrate from TensorFlow 1.x to TensorFlow 2
Remove old tf.contrib.layers and replace them with TF Slim symbols
import tf_slim as slim
用于添加一个全连接层。
tf.layers.dense(
inputs, #层的输入
units, #该层的输出维度
activation=None, #激活函数
use_bias=True, # 是否使用偏置项
kernel_initializer=None, # 卷积核的初始化器
bias_initializer=tf.zeros_initializer(), # 偏置项的初始化器
kernel_regularizer=None, # 卷积核的正则化
bias_regularizer=None, # 偏置项的正则化
activity_regularizer=None,
kernel_constraint=None,
bias_constraint=None,
trainable=True, # 表明该层的参数是否参与训练
name=None, # 层的名字
reuse=None # 是否重复使用参数
)
example:手写体例子,利用两个dense可以构成一个单层网络,在下面例子中,网络的神经元个数为200。
- import numpy as np
- import tensorflow as tf
- from tensorflow.examples.tutorials.mnist import input_data
-
- def compute_accuracy(x_data,y_data):
- global dense2
- y_pre = sess.run(dense2,feed_dict={xs:x_data})
- correct_prediction = tf.equal(tf.arg_max(y_data,1),tf.arg_max(y_pre,1)) #判断是否相等
- accuracy = tf.reduce_mean(tf.cast(correct_prediction,tf.float32)) #赋予float32数据类型,求平均。
- result = sess.run(accuracy,feed_dict = {xs:batch_xs,ys:batch_ys}) #执行
- return result
-
- mnist = input_data.read_data_sets("MNIST_data",one_hot = "true")
-
- xs = tf.placeholder(tf.float32,[None,784])
- ys = tf.placeholder(tf.float32,[None,10])
-
- dense1 = tf.layers.dense(
- xs,
- 200,
- activation = tf.nn.tanh,
- kernel_initializer=tf.random_normal_initializer(mean=0, stddev=0.3),
- bias_initializer=tf.constant_initializer(0.1),
- name='fc1'
- )
-
- dense2 = tf.layers.dense(
- dense1,
- 10,
- activation = tf.nn.softmax,
- kernel_initializer=tf.random_normal_initializer(mean=0, stddev=0.3),
- bias_initializer=tf.constant_initializer(0.1),
- name='fc2'
- )
-
- loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits = dense2, labels = ys),name = 'loss')
- #label是标签,logits是预测值,交叉熵。
-
- train = tf.train.GradientDescentOptimizer(0.5).minimize(loss)
- init = tf.initialize_all_variables()
-
- with tf.Session() as sess:
- sess.run(init)
- for i in range(5001):
- batch_xs,batch_ys = mnist.train.next_batch(100)
- sess.run(train,feed_dict = {xs:batch_xs,ys:batch_ys})
- if i % 1000 == 0:
- print("训练%d次的识别率为:%f。"%((i+1),compute_accuracy(mnist.test.images,mnist.test.labels)))
- 训练1次的识别率为:0.107400。
- 训练1001次的识别率为:0.805200。
- 训练2001次的识别率为:0.822800。
- 训练3001次的识别率为:0.829400。
- 训练4001次的识别率为:0.833100。
- 训练5001次的识别率为:0.835300。
sigmoid函数可以将输出压缩到0-1的范围。



tf.nn.softmax()函数用于归一化。
tf.nn.softmax(logits,axis=None,name=None,dim=None)
logits:一个非空的Tensor。必须是下列类型之一:half, float32,float64
axis:将在其上执行维度softmax。默认值为-1,表示最后一个维度
name:操作的名称(可选)
dim:axis的已弃用的别名
输入: 全连接层(往往是模型的最后一层)的值
输出: 归一化的值,含义是属于该位置的概率;

将softmax应用于批量的N维SparseTensor。
tf.nn.leaky_relu(
features, features:一个Tensor,表示预激活
alpha=0.2, alpha:x<0时激活函数的斜率
name=None) 操作的名称(可选)
参数:
返回值:激活值

优点:
1.能解决深度神经网络(层数非常多)的“梯度消失”问题,浅层神经网络(三五层那种)才用sigmoid 作为激活函数。
2.它能加快收敛速度。
l2正则化目的是为了让权重衰减到更小的值,在一定程度上减少模型过拟合的问题。
l2正则化就是在损失函数后面再加上一个正则化项:

在tensorflow中,tf.nn.l2_loss()函数就是利用l2范数来计算张量的误差值,并且只取l2范数值得一半,即1/2。
tf.nn.l2_loss(
t, #t是一个张量,一般有两个维度。name=None
)
output = sum(t ** 2) / 2w 变小的效果,但是为什么 w 变小可以防止过拟合呢?(1)从模型的复杂度上解释:更小的权值 w,从某种意义上说,表示网络的复杂度更低,对数据的拟合更好(这个法则也叫做奥卡姆剃刀),而在实际应用中,也验证了这一点,L2正则化的效果往往好于未经正则化的效果。
(2)从数学方面的解释:过拟合的时候,拟合函数的系数往往非常大,为什么?如下图所示,过拟合,就是拟合函数需要顾忌每一个点,最终形成的拟合函数波动很大。在某些很小的区间里,函数值的变化很剧烈。这就意味着函数在某些小区间里的导数值(绝对值)非常大,由于自变量值可大可小,所以只有系数足够大,才能保证导数值很大。而正则化是通过约束参数的范数使其不要太大,所以可以在一定程度上减少过拟合情况。
- import tensorflow as tf
- sess = InteractiveSession()
-
- a = tf.constant([1, 2, 3], dtype=tf.float32)
- b = tf.nn.l2_loss(a)
- print(b.eval()) # 7.0
- # tf.nn.l2_loss 运算是每个数的平方和再除以二
- # b = (12+22+33)/2 =7.0
tf.nn.dropout()是tensorflow 将元素随机置零以防止过拟合的函数,它一般用于全连接层。
tf.nn.dropout(
x, rate, noise_shape=None, seed=None, name=None
)
dropout就是在不同的训练过程中随机扔掉一部分神经元。也就是让某个神经元的激活值以一定的概率p,让其停止工作,这次训练过程中不更新权值,也不参加神经网络的计算。但是它的权重得保留下来(只是暂时不更新而已),因为下次样本输入时它可能又得工作了。

但在测试及验证中:每个神经元都要参加运算,但其输出要乘以概率p。
Dropout对于正则化DNN模型很有用。输入元素被随机设置为零(其他元素被重新缩放)。这鼓励每个节点独立使用,因为它不能依赖其他节点的输出。
更精确地:x的元素有rate概率设置为0。
- x = tf.ones([3, 5])
- y = tf.nn.dropout(x, rate=0.5, seed=1)
-
- print(x)
- print(y)
- ------------------------------------
- '''
- tf.Tensor(
- [[1. 1. 1. 1. 1.]
- [1. 1. 1. 1. 1.]
- [1. 1. 1. 1. 1.]], shape=(3, 5), dtype=float32)
- tf.Tensor(
- [[0. 2. 0. 0. 2.]
- [0. 0. 0. 2. 2.]
- [2. 0. 0. 0. 0.]], shape=(3, 5), dtype=float32)
- '''
AdamOptimizer是TensorFlow中实现Adam算法的优化器。Adam即Adaptive Moment Estimation(自适应估计),是一个寻找全局最优点的优化算法,引入了二次梯度矫正。
- __init__(
- learning_rate=0.001,
- beta1=0.9,
- beta2=0.999,
- epsilon=1e-08,
- use_locking=False,
- name='Adam'
- )
- '''
- learning_rate: A Tensor or a floating point value. (学习率)
- beta1: A float value or a constant float tensor. (一阶矩估计的指数衰减率)
- beta2: A float value or a constant float tensor. (二阶矩估计的指数衰减率)
- epsilon: A small constant for numerical stability. (一个非常小的数,防止除以零)
- use_locking: 如果为真,则使用锁进行更新操作。
- name: 使用梯度时创建的操作的可选名称,默认为 “Adam”。
- '''
TensorFlow优化算法 tf.train.AdamOptimizer 简介_叶上初阳1995的博客-CSDN博客
tf.compat.v1.train.AdapOptimizer(learning_rate=lr)
梯度更新
minimize的内部存在两个操作:(1)计算各个变量的梯度 (2)用梯度更新这些变量的值
主要的参数说明:
loss: `Tensor` ,需要优化的损失;
var_list: 需要更新的变量(tf.Varialble)组成的列表或者元组,默认值为`GraphKeys.TRAINABLE_VARIABLES`,即tf.trainable_variables()
注意:1、Optimizer.minimize(loss, var_list)中,计算loss所涉及的变量(假设为var(loss))包含在var_list中,也就是var_list中含有多余的变量,并不 影响程序的运行,而且优化过程中不改变var_list里多出变量的值;
2、若var_list中的变量个数少于var(loss),则优化过程中只会更新var_list中的那些变量的值,var(loss)里多出的变量值 并不会改变,相当于固定了网络的某一部分的参数值。
主要的参数说明:
loss: `Tensor` ,需要优化的损失;
var_list: 需要更新的变量(tf.Varialble)组成的列表或者元组,默认值为`GraphKeys.TRAINABLE_VARIABLES`,即tf.trainable_variables()
梯度下降:
tf优化器:
- opt = tf.compat.v1.train.AdamOptimizer(learning_rate=0.1)
- train_op = opt.minimize(loss)
计算给定logits的sigmoid交叉熵。
该函数主要用于每一个类别都是相不排斥的分类任务,即一个实例(instance)可以划分为多个类别。
不同于softmax系列函数是张量中向量与向量间的运算。sigmoid_cross_entropy_with_logits函数则是张量中标量与标量间的运算
- import numpy as np
- import tensorflow as tf
-
- def sigmoid(x):
- return 1.0/(1+np.exp(-x))
-
- labels=np.array([[1.,0.,0.],[0.,1.,0.],[0.,0.,1.]])
- logits=np.array([[-1.,8.,2.],[-3.,14.,1.],[1.,2.,4.]])
- y_pred=sigmoid(logits)
- prb_error1 = -labels*np.log(y_pred) #计算分类结果在正确类别处的损失,
- prb_error2 = -(1-labels)*np.log(1-y_pred)
- prob_error1= prb_error1 + prb_error2 #属于该类的损失+其他类的损失
- print(prob_error1)
-
-
- with tf.Session() as sess:
- print(sess.run(tf.nn.sigmoid_cross_entropy_with_logits(labels=labels,logits=logits)))
计算分类问题交叉熵损失函数。
这个函数的返回值不是一个数,而是一个向量。如果要求最终的交叉熵损失,我们需要再做一步tf.reduce_sum操作,即对向量中的所有元素求和。
- tf.nn.softmax_cross_entropy_with_logits(logits, labels, name=None)
- '''
- 第一个参数logits:就是神经网络最后一层的输出,如果有batch(批处理)的话,它的大小就是[batchsize,num_classes],单样本的话,大小就是num_classes
- 第二个参数labels:实际的标签,大小同上
- '''
【TensorFlow】tf.nn.softmax_cross_entropy_with_logits中的“logits”到底是个什么意思?
具体执行过程大概分为两步:
(1) 先对网络最后一层的输出做一个softmax(归一化处理)
(2) softmax的输出向量和样本的实际标签,做一个交叉熵。
Notice:
这个函数的返回值:并不是一个数,而是一个
向量,如果要求交叉熵,我们要再做一步
tf.reduce_sum操作,就是对向量里面所有元素求和,最后才得到,如果求loss,则要做一步
tf.reduce_mean操作,对向量求均值!
- import tensorflow as tf
-
- #our NN's output 假设为:神经网络的最后一层输出
- logits=tf.constant([[1.0,2.0,3.0],[1.0,2.0,3.0],[1.0,2.0,3.0]])
- #step1:do softmax 使用softmax进行归一化处理
- y=tf.nn.softmax(logits)
- #true label 监督学习中,数据输入网络前的正确的标签
- y_=tf.constant([[0.0,0.0,1.0],[0.0,0.0,1.0],[0.0,0.0,1.0]])
- #step2:do cross_entropy 求交叉熵损坏的方法一
- cross_entropy = -tf.reduce_sum(y_*tf.log(y))
- #do cross_entropy just one step 求交叉熵损坏的方法二:使用本次讲解的函数
- cross_entropy2=tf.reduce_sum(tf.nn.softmax_cross_entropy_with_logits(logits, y_))#dont forget tf.reduce_sum()!!
-
- with tf.Session() as sess:
- softmax=sess.run(y)
- c_e = sess.run(cross_entropy)
- c_e2 = sess.run(cross_entropy2)
- print("step1:softmax result=")
- print(softmax)
- print("step2:cross_entropy result=")
- print(c_e)
- print("Function(softmax_cross_entropy_with_logits) result=")
- print(c_e2)
- step1:softmax result=
- [[ 0.09003057 0.24472848 0.66524094]
- [ 0.09003057 0.24472848 0.66524094]
- [ 0.09003057 0.24472848 0.66524094]]
- step2:cross_entropy result=
- 1.22282
- Function(softmax_cross_entropy_with_logits) result=
- 1.2228
多分类交叉熵计算函数--进行softmax和loss计算,它适用于每个类别相互独立且排斥的情况,例如一幅图只能属于一类。
- tf.nn.sparse_softmax_cross_entropy_with_logits(labels=None, logits=None, name=None)
- '''
- labels: shape为[batch_size],labels[i]是[0, num_classes]的一个索引,type为int32或int64.
- logits: shape为[batch_size, num_classes],type为float32或float64
- name:
- '''
- import tensorflow as tf
-
- labels_sparse = [0, 2, 1]
- # 索引,即真实的类别
- # 0表示第一个样本的类别属于第1类;
- # 2表示第二个样本的类别属于第3类;
- # 1表示第三个样本的类别属于第2类;
-
- logits = tf.constant(value=[[3, 1, -3], [1, 4, 3], [2, 7, 5]],
- dtype=tf.float32, shape=[3, 3])
-
-
- loss_sparse = tf.nn.sparse_softmax_cross_entropy_with_logits(
- labels=labels_sparse,
- logits=logits)
-
-
- with tf.compat.v1.Session() as sess:
- print("loss_sparse: \n", sess.run(loss_sparse))
- --------------------------------------------------------
- '''
- loss_sparse:
-
- [0.12910892, 1.3490121, 0.13284527]
- '''
tf_slim是Tensorflow中一个轻量级的库,用于定义、训练和评估复杂的模型。tf_slim中的组件可以与Tensorflow中原生的函数一起使用,与其他的框架,比如与tf.contrib.learn也可以一起使用。
在神经网络中,一个卷积层由许多底层操作符组成:
如果只用普通的tensorflow代码,干这个事相当的费劲!--重复
- input = ...
- with tf.name_scope('conv1_1') as scope:
- kernel = tf.Variable(tf.truncated_normal([3, 3, 64, 128], dtype=tf.float32,
- stddev=1e-1), name='weights')
- conv = tf.nn.conv2d(input, kernel, [1, 1, 1, 1], padding='SAME')
- biases = tf.Variable(tf.constant(0.0, shape=[128], dtype=tf.float32),
- trainable=True, name='biases')
- bias = tf.nn.bias_add(conv, biases)
- conv1 = tf.nn.relu(bias, name=scope)
To alleviate the need to duplicate this code repeatedly, tf_slim provides a number of convenient operations at the more abstract level of neural networks layers. For example, compare the code above to an invocation of the corresponding tf_slim code:
为了缓解重复这些代码,tf_slim在更抽象的神经网络层面提供了大量方便使用的操作符。比如,将上面的代码和tf_slim相应的代码调用进行比较。
比如,tf_slim.bias_add()函数,用于加偏置bias。
TF-Slim提供了标准接口用于组建神经网络,包括:
| Layer | TF-Slim |
|---|---|
| BiasAdd | slim.bias_add |
| BatchNorm | slim.batch_norm |
| Conv2d | slim.conv2d |
| Conv2dInPlane | slim.conv2d_in_plane |
| Conv2dTranspose (Deconv) | slim.conv2d_transpose |
| FullyConnected | slim.fully_connected |
| AvgPool2D | slim.avg_pool2d |
| Dropout | slim.dropout |
| Flatten | slim.flatten |
| MaxPool2D | slim.max_pool2d |
| OneHotEncoding | slim.one_hot_encoding |
| SeparableConv2 | slim.separable_conv2d |
| UnitNorm | slim.unit_norm |
参考:tensorflow中slim模块api介绍 - Maddock - 博客园
最常见的情况,将x矩阵加到y矩阵上。
tf.nn.bias_add(value, bias, name=None)
将bias向量加到value矩阵上,是向量与矩阵的每一行进行相加,得到的结果和value矩阵大小相同。
两个稀疏张量相加,其中至少有一个是 SparseTensor.
- sparse_add(
- a,
- b,
- thresh=0 )
实现列表+列表,列表元素可以是向量、矩阵。
- import tensorflow as tf;
- import numpy as np;
-
- input1 = tf.constant([1.0, 2.0, 3.0])
- input2 = tf.Variable(tf.random_uniform([3]))
- output = tf.add_n([input1, input2])
-
- with tf.Session() as sess:
- sess.run(tf.initialize_all_variables())
- print sess.run(input1 + input2)
- print sess.run(output)
- -------------------------------------------
- '''
- [ 1.68921876 2.73008633 3.04061747]
- [ 1.68921876 2.73008633 3.04061747]
- '''
两个矩阵中对应元素各自相乘。
格式: tf.multiply(x, y, name=None)
参数:
x: 一个类型为:half, float32, float64, uint8, int8, uint16, int16, int32, int64, complex64, complex128的张量。
y: 一个类型跟张量x相同的张量。
返回值: x * y element-wise.
- import tensorflow as tf
- a = tf.constant([[3, 2], [5, 1]])
- b = tf.constant([[1, 6], [2, 9]])
- c = tf.multiply(a, b)
- sess = tf.Session()
- print sess.run(c)
- 输出:
- [[ 3 12] 【3*1,2*6】
- [10 9]] 【5*2,1*9】
矩阵a乘以矩阵b,生成a*b
- # 2-D tensor `a`
- a = tf.constant([1, 2, 3, 4, 5, 6], shape=[2, 3]) => [[1. 2. 3.]
- [4. 5. 6.]]
- # 2-D tensor `b`
- b = tf.constant([7, 8, 9, 10, 11, 12], shape=[3, 2]) => [[7. 8.]
- [9. 10.]
- [11. 12.]]
- c = tf.matmul(a, b) => [[58 64]
- [139 154]]
用稠密矩阵B乘以SparseTensor矩阵A
- import tensorflow as tf
-
- '''
- [[1,0],
- [0,1]]
- '''
- st = tf.SparseTensor(values=[1, 2], indices=[[0, 0], [1, 1]], dense_shape=[2, 2])
- dt = tf.ones(shape=[2,2],dtype=tf.int32)
- result = tf.sparse_tensor_dense_matmul(st,dt)
- sess = tf.Session()
- with sess.as_default():
- print(result.eval())
print结果:
[[1 1]
[2 2]]
tf.tensordot()函数是tensorflow中tensor矩阵相乘的api,可以进行任意维度的矩阵相乘。
将张量的值四舍五入为最接近的整数,元素.
- x = tf.constant([0.9, 2.5, 2.3, 1.5, -4.5])
- tf.round(x) # [ 1.0, 2.0, 2.0, 2.0, -4.0 ]
equal(x, y, name=None)
判断x和y是否相等,它的判断不是整体判断,而是逐个元素进行判断,如果相等就是True,否则就是False。
- import tensorflow as tf
- a = [[1,2,3],[4,5,6]]
- b = [[1,0,3],[1,5,1]]
- with tf.Session() as sess:
- print(sess.run(tf.equal(a,b)))
- -----------------------------------------
- '''
- [[ True False True]
- [False True False]]
- '''
计算tensorflow中非零元素的个数
- count_nonzero(
- input_tensor,
- axis=None,
- keep_dims=False,
- dtype=tf.int64,
- name=None,
- reduction_indices=None
- )
如果是两分类的话(0/1),直接使用tf.count_nonzero()函数即可;
如果是多分类,那么就需要使用tf.bincount()或者tf.unique_with_counts()。
返回最大值索引
- argmax(input,
- axis=None, # input:输入Tensor
- name=None, # axis:0表示按列,1表示按行
- dimension=None, # 和axis功能一样,dimension参数已过时,被axis替代
- output_type=dtypes.int64) # 函数返回值类型,返回值可以有int32和int64两种类型,默认为int64
- A = [[1,3,4,5,6]]
- B = [[1,3,4], [2,4,1]]
- C = [[[16,6,3],[4,6,5]], [[8,7,9], [11,12,10]]]
-
-
- with tf.Session() as sess:
- print(sess.run(tf.argmax(A, 0)))
- print(sess.run(tf.argmax(A, 1)))
- print(sess.run(tf.argmax(A, 1, output_type=tf.int32)))
- print(sess.run(tf.argmax(B, 0)))
- print(sess.run(tf.argmax(B, 1)))
- print(sess.run(tf.argmax(C, 0)))
- print(sess.run(tf.argmax(C, 1)))
- print(sess.run(tf.argmax(C, 2)))
- [0 0 0 0 0]
- #(A,0) 在向量列中找最大值的索引,而每个数据在每列中都是最大的(因为只有一个数),故返回[0 0 0 0 0]
-
- [4]
- #(A,1) 在向量行中找最大值的索引,6结果最大,最后返回6的序号[4]
-
- [4]
- #(A,1,output_type=tf.int32) 在向量行中找最大值的索引,6结果最大,最后返回6的序号[4]
-
- [1 1 0]
- #(B,0) 在矩阵列中找最大值的索引, 1 2最大值为2,故返回1; 3 4最大值为4,故返回1; 4 1最大值为4,故返回0, 最后返回[1 1 0]
-
- [2 1]
- #(B,1) 在矩阵行中最大致的索引, 1 3 4最大值为4,故返回2; 2 4 1最大值为4,故返回1, 最后返回[2,1]
-
- [[0 1 1]
- [1 1 1]]
- #(C,0) 在矩阵第0轴找最大值的索引, 16 8最大值为16,故返回0; 6 7最大值为7,故返回1; 相类似,最后5 10最大值为10,故返回1, 最后返回[[0 1 1][1 1 1]]
-
- [[0 0 1]
- [1 1 1]]
- #(C,1) 在矩阵第1轴找最大值的索引, 16 4最大值为16,故返回0; 6 6最大值为6,故返回0,相类似,最后9 10最大值为10,故返回1 最后返回[[0 0 1][1 1 1]]
-
- [[0 1]
- [2 1]]
- #(C,2) 在矩阵第2轴找最大值的索引, 16 6 3中最大值为16,故返回0; 4 6 5最大值为6,故返回1;8 7 9最大值为9,故返回2;11 12 10最大值为12,故返回1; 最后结果为[[0 1][2 1]]
Defined in tensorflow/python/ops/array_ops.py.
- # 'x' is [[1 2 3]
- # [4 5 6]]
- tf.transpose(x) ==> [[1 4]
- [2 5]
- [3 6]]
To take the transpose of the matrices in dimension-0 (such as when you are
transposing matrices where 0 is the batch dimension), you would set
`perm=[0,2,1]`.
- >>> x = tf.constant([[[ 1, 2, 3],
- ... [ 4, 5, 6]],
- ... [[ 7, 8, 9],
- ... [10, 11, 12]]])
-
- >>> tf.transpose(x, perm=[0, 2, 1])
2, 3, 2), dtype=int32, numpy= - array([[[ 1, 4],
- [ 2, 5],
- [ 3, 6]],
- [[ 7, 10],
- [ 8, 11],
- [ 9, 12]]], dtype=int32)>
-
- Note: This has a shorthand `linalg.matrix_transpose`):
tensorflow中,张量具有静态形状和动态形状。
静态形状:创建一个张量或者由操作推导出一个张量时,初始状态的形状。
动态形状:一种描述原始张量在执行过程中的形状(动态变化)
重塑一个SparseTensor以表示新密集形状中的值。
reduce_sum 应该理解为压缩求和,用于降维(是从维度上考虑的)
tf.reduce_sum(input_tensor,axis=None,keepdims=None,name=None,reduction_indices=None,keep_dims=None)

tf.reduce_mean 函数用于计算张量tensor沿着指定的数轴(tensor的某一维度)上的的平均值,主要用作降维或者计算tensor(图像)的平均值。
- reduce_mean(input_tensor, # 输入的待降维的tensor;
- axis=None, # 指定的轴,如果不指定,则计算所有元素的均值;
- keep_dims=False, # 是否降维度,设置为True,输出的结果保持输入tensor的形状,设置为False,输出结果会降低维度;
- name=None, # 操作的名称;
- reduction_indices=None) # 在以前版本中用来指定轴,已弃用;
- 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.]
- ------------------------------------------------
- # if keep_dims=True
- print m_a # output: [[ 2.]]
- print m_0 # output: [[ 1. 2. 3.]]
- print m_1 #output: [[ 2.], [ 2.]]
def squeeze(input, axis=None, name=None, squeeze_dims=None)
tf.squeeze()函数返回一个张量,这个张量是将原始input中所有维度为1的那些维都删掉
- # 't' is a tensor of shape [1, 2, 1, 3, 1, 1]
- tf.shape(tf.squeeze(t)) # [2, 3]
tf.expand_dims(
input, axis=None, name=None, dim=None)
- input:输入,tensor类型
- axis:增加维度的位置,比如:0表示在input的第一维增加一维,shape(a)=[2,3],操作之后数据维度为[1,2,3]。如果是1,shape=[2,1,3]
- name:操作的名称(可选)。
tf.concat([tensor1, tensor2, tensor3,...], axis)
axis=0 代表在shape第0个维度上拼接
axis=1 代表在shape第1个维度上拼接
axis=-1,表示shape倒数第一个维度
- t1 = [[1, 2, 3], [4, 5, 6]]
- t2 = [[7, 8, 9], [10, 11, 12]]
- tf.concat([t1, t2], 0) # [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]
- tf.concat([t1, t2], 1) # [[1, 2, 3, 7, 8, 9], [4, 5, 6, 10, 11, 12]]
-
- # tensor t3 with shape [2, 3]
- # tensor t4 with shape [2, 3]
- tf.shape(tf.concat([t3, t4], 0)) # [4, 3]
- tf.shape(tf.concat([t3, t4], 1)) # [2, 6]
用于改变某个tensor的数据类型。
cast(x, dtype, name=None)
- 第一个参数 x: 待转换的数据(张量)
- 第二个参数 dtype: 目标数据类型
- 第三个参数 name: 可选参数,定义操作的名称
- 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:
- t2: Tensor("Cast:0", shape=(5,), dtype=float32)
- [ 1. 2. 3. 4. 5.]
- '''
TensorFlow是google基于DisBelief进行研发的第二代人工智能学习系统,其命名来源于本身的运行原理。
tf.Graph()表示实例化了一个用于tensorflow计算和表示用的数据流图。代码中的计算作为图上的node、数据作为图上的edge。
as_default()表示将新生成的图作为整个tensorflow运行环境的默认图。虽然tensorflow里面已经存好了一张默认图,但as_default()新图可以在with语句让会话session执行。
数据流图是用于定义计算结构的,在tensorflow中,数据流图本质上是一组链接在一起的函数。
tensorflow是一个通过计算图的形式来表述计算的系统。
tensorflow的计算表示为有向的数据流图(Data Flow Graphs),其中每个节点代表一些函数或计算,而边表示数值、矩阵或张量。
在tensorflow程序中,系统会自动维护一个默认的计算图,通过tf.get_default_graph()函数可以获取当前默认的计算图。
通过a.graph可以查看张量所属的计算图。
- import tensorflow as tf
-
- a = tf.constant([1., 2.], name='a')
- b = tf.constant([2., 3.], name='b')
- result = a + b
-
- a.graph is tf.get_default_graph()
如果你想在一个进程里创建多个图,可能会用到这个方法
如果没有显式创建一个图的话,系统提供了一个全局默认的图,默认把所有的操作都添加到全局默认图中。
配合 with 关键词使用,可以只把 with 块里的操作添加到默认图中。
默认图是当前线程的一个属性,如果你创建了一个新的线程,想使用全局默认图,必须显式调用这个方法
目的是将这个图设置为默认图,session设置成默认会话,这样的话在with语句外面也能让这个会话执行。
- def train():
- with self.graph.as_default():
- with self.sess.as_default():
- trainStep()
- def trainStep():
- self.sess.run(loss)
- #如果没有.as_default()操作就会报错,
- #因为普通的会话只有在with语句里面上下文管理器里面有效,出去的而话默认有sess.close()操作。
- #但是as_default()以后就可以在外面使用。
-
- '''
- tf.Session()创建一个会话,当上下文管理器退出时会话关闭和资源释放自动完成。
- tf.Session().as_default()创建一个默认会话,当上下文管理器退出时会话没有关闭,还可以通过调用会话进行run()和eval()操作
- '''
tensorflow计算图不仅可以用来隔离张量和计算,还提供了管理张量和计算的机制。
计算图可以通过tf.Graph.device函数来指定运行计算的设备。
- g = tf.Graph()
- # 指定计算运行的设备
- with g.device('/gpu:0'):
- result = a + b
- '''
- 有效整理TensorFlow 程序的资源也是计算图的一个重要功能
- '''
TensorFlow的设计理念称之为计算流图。在编写程序时,
优点:
- 避免反复地切换底层程序实际运行的上下文,tensorflow并拟优化整个系统的代码。
- tf.placeholder(
- dtype, # 数据类型。常用的是tf.float32,tf.float64等数值类型
- shape=None, # 数据形状。默认是None,就是一维值,也可以是多维(比如[2,3], [None, 3]表示列是3,行不定)
- name=None # 名称
- )
tf.placeholder()函数,占位符。在神经网络构建graph的时候在模型中占位,此时并没有把要输入的数据传入模型,它只会分配必要的内存。
等建立session,在会话中,运行模型的时候通过feed_dict()函数向占位符喂入数据。
- import tensorflow as tf
- import numpy as np
-
- input1 = tf.placeholder(tf.float32)
- input2 = tf.placeholder(tf.float32)
-
- output = tf.multiply(input1, input2)
-
- with tf.Session() as sess:
- print(sess.run(output, feed_dict = {input1:[3.], input2: [4.]}))
在代码层面,每一个tensor值在graph上都是一个operation,当我们将train数据分成一个个minibatch然后传入网络进行训练时,每一个minibatch都是一个operation,这样的话,graph上的operation未免太多,也会产生巨大开销。
tf.placeholder()函数,我们每次可以将一个minibatch传入到x=tf.placeholder(tf.float32, [None,32])上,下一次传入的x都替换掉上一次传入的x,这样对所有传入的minibatch x就只会产生一个operation,不会产生其他多余的operation,减少开销。
- tf.compat.v1.placeholder()
-
- replace
-
- tf.placeholder()
tf.train.Saver()是一个类,提供了变量、模型(计算图graph)保存和恢复的方法。在tf.train.Saver()类初始化时,用于保存和恢复的save和restore operatior会被加入到Graph中。所以,下列类初始化操作应在搭建Graph时完成。
- saver = tf.train.Saver()
- '''
- 保存和恢复变量
- 保存和恢复模型
- '''
tensorflow会将变量保存在二进制checkpoint文件中,这类文件会将变量名映射到张量值。
- save(
- sess, # 必需参数,Session对象
- save_path, # 必需参数,存储路径
- global_step=None, # 可以是Tensor, Tensor name, 整型数
- latest_filename=None, # 协议缓冲文件名,默认为'checkpoint',不用管
- meta_graph_suffix='meta', # 图文件的后缀,默认为'.meta',不用管
- write_meta_graph=True, # 是否保存Graph
- write_state=True, # 建议选择默认值True
- strip_default_attrs=False # 是否跳过具有默认值的节点
- import tensorflow as tf
- # Create some variables.
- v1 = tf.get_variable("v1_name", shape=[3], initializer = tf.zeros_initializer)
- v2 = tf.get_variable("v2_name", shape=[5], initializer = tf.zeros_initializer)
-
- inc_v1 = v1.assign(v1+1)
- dec_v2 = v2.assign(v2-1)
-
- # Add an op to initialize the variables.
- init_op = tf.global_variables_initializer()
-
- # Add ops to save and restore all the variables.
- saver = tf.train.Saver()
-
- # Later, launch the model, initialize the variables, do some work, and save the
- # variables to disk.
- with tf.Session() as sess:
- sess.run(init_op)
- # Do some work with the model.
- inc_v1.op.run()
- dec_v2.op.run()
- # Save the variables to disk.
- save_path = saver.save(sess, "model/model.ckpt") # 返回一个保存路径的字符串
- print("Model saved in path: %s" % save_path)
-
- '''output
- Model saved in path: model/model.ckpt
- '''
- '''
- 保存路径中的文件为:
- checkpoint:保存当前网络状态的文件
- model.data-00000-of-00001
- model.index
- model.meta:保存Graph结构的文件
- '''
从checkpoint文件中提取变量值赋值给新定义的变量。
- tf.reset_default_graph()
- # Create some variables
- # !!!variable name必须与保存时的name一致
- v1 = tf.get_variable("v1_name", shape=[3])
- v2 = tf.get_variable("v2_name", shape=[5])
-
- saver = tf.train.Saver()
- with tf.Session() as sess:
- # Restore variables from disk
- saver.restore(sess, "model/model.ckpt")
- print("v1: %s" % v1.eval())
- print("v2: %s" % v2.eval())
- '''output
- INFO:tensorflow:Restoring parameters from model/model.ckpt
- v1: [ 1. 1. 1.]
- v2: [-1. -1. -1. -1. -1.]
- '''
variable().eval()
eval(session=None)
In a session computes and returns the value of this variable.
tf.global_variables_initializer()函数添加用于初始化全局变量的节点(GraphKeys.GLOBAL_VARIABLES)。返回一个初始化所有全局变量的操作op。
在你构建完整个模型并在会话中加载模型后,运行这个节点。
通过feed_dict,你可以将指定的列表传递给它,只初始化列表中的变量。
- sess.run(tf.global_variables_initializer(),
- feed_dict={
- learning_rate_dis: learning_rate_val_dis,
- adam_beta1_d_tf: adam_beta1_d,
- learning_rate_proj: learning_rate_val_proj,
- lambda_ratio_tf: lambda_ratio,
- lambda_l2_tf: lambda_l2,
- lambda_latent_tf: lambda_latent,
- lambda_img_tf: lambda_img,
- lambda_de_tf: lambda_de,
- adam_beta1_g_tf: adam_beta1_g,
- })
- # learning_rate_dis为设置的变量,learning_rate_val_dis为我设置的具体的值。后续同理
返回一个初始化所有局部变量的操作op。
- sess.run(tf.local_variables_initializer(),
- feed_dict={
- learning_rate_dis: learning_rate_val_dis,
- adam_beta1_d_tf: adam_beta1_d,
- learning_rate_proj: learning_rate_val_proj,
- lambda_ratio_tf: lambda_ratio,
- lambda_l2_tf: lambda_l2,
- lambda_latent_tf: lambda_latent,
- lambda_img_tf: lambda_img,
- lambda_de_tf: lambda_de,
- adam_beta1_g_tf: adam_beta1_g,
- })
- # learning_rate_dis为设置的变量,learning_rate_val_dis为我设置的具体的值。后续同理
update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS, first_clone_scope)
......
update_op = tf.group(*update_ops)
tf.group()分组函数,就是把update_ops(list) 中的操作合并为一个组(操作)。出了tf.group()函数外,tf.tuple()函数也有类似的功能,也有一些细微差别。
- generator_train_op = tf.train.AdamOptimizer(g_loss, ...)
- discriminator_train_op = tf.train.AdamOptimizer(d_loss,...)
- train_ops = tf.groups(generator_train_op ,discriminator_train_op)
-
- with tf.Session() as sess:
- sess.run(train_ops)
- # 一旦运行了train_ops,那么里面的generator_train_op和discriminator_train_op都将被调用
- os.environ['CUDA_VISIBLE_DEVICES'] = '0' #使用 GPU 0
- os.environ['CUDA_VISIBLE_DEVICES'] = '0,1' # 使用 GPU 0,1
CUDA_VISIBLE_DEVICES=0,1 python yourcode.py
tf.ConfigProto()函数用在创建session的时候,用来对session进行参数配置。
- config = tf.ConfigProto(allow_soft_placement=True, allow_soft_placement=True)
- config.gpu_options.per_process_gpu_memory_fraction = 0.4 #占用40%显存
- sess = tf.Session(config=config)
1. 记录设备指派情况 : tf.ConfigProto(log_device_placement=True)
设置tf.ConfigProto()中参数log_device_placement = True ,可以获取到 operations 和 Tensor 被指派到哪个设备(几号CPU或几号GPU)上运行,会在终端打印出各项操作是在哪个设备上运行的。2. 自动选择运行设备 : tf.ConfigProto(allow_soft_placement=True)
在tf中,通过命令 "with tf.device('/cpu:0'):",允许手动设置操作运行的设备。如果手动设置的设备不存在或者不可用,就会导致tf程序等待或异常,为了防止这种情况,可以设置tf.ConfigProto()中参数allow_soft_placement=True,允许tf自动选择一个存在并且可用的设备来运行操作。
3. 限制GPU资源使用:
为了加快运行效率,TensorFlow在初始化时会尝试分配所有可用的GPU显存资源给自己,这在多人使用的服务器上工作就会导致GPU占用,别人无法使用GPU工作的情况。
tf提供了两种控制GPU资源使用的方法,一是让TensorFlow在运行过程中动态申请显存,需要多少就申请多少;第二种方式就是限制GPU的使用率。
- config = tf.ConfigProto()
- config.gpu_options.allow_growth = True
- session = tf.Session(config=config)
- config = tf.ConfigProto()
- config.gpu_options.per_process_gpu_memory_fraction = 0.4 #占用40%显存
- session = tf.Session(config=config)
-
- ------------------------------------------------------------------
-
- gpu_options=tf.GPUOptions(per_process_gpu_memory_fraction=0.4)
- config=tf.ConfigProto(gpu_options=gpu_options)
- session = tf.Session(config=config)
原因:ConfigProto disappeared in tf 2.0, so an elegant solution is:
replace tf.ConfigProtobytf.compat.v1.ConfigProto
In fact, the compatibility built in 2.0 to get tf 1.XX: tf.compat.v1 is really helpful.

tensorflow通过计算图的方式来控制神经网络流程,其声明的变量和函数都在with.tf.Graph().as_default(): 之下。
tensorflow搭建神经网络,主要有4步:
1) 数据集准备
2) 前向传播过程设计
3) 损失函数及反向传播过程设计
above 3 steps,提前用placeholder占位符声明好变量和函数
4) 调用 tf.Session().run() 执行代码。
with tf.Session() as sess:
sess.run()
-----------------------------------------
run(fetches, feed_dict=None, options=None, run_metadata=None)
# Session对fetches list中的张量tensor进行评估和计算
- fetches,必选参数。需要执行的具体函数/变量,e.g. sess.run([train_op, loss, accuracy, att_val], feed_dict=..); sess.run([loss, accuracy], feed_dict=..)
- feed_dict,可选参数。feed_dict允许调用者覆盖tensor的值:tf.Tensor, tf.placeholder, tf.SparseTensor, tf.SparseTensorValue。传入字典数据
- return: run()返回值与fetches具有相同的形状。
tf.Session.close(),关闭会话后,调用的资源机器关联的内存将会被释放。