
TensorFlow
仁义礼智信达
喜欢学习和分享
展开
-
Tensorflow 计算模型的FLOPs
最近在研究模型的计算量,发现Pytorch有库可以直接计算模型的计算量,所以需要一个一个Keras和Tensorflow可以用的,直接把Model接入到函数中,print一下就可以计算出FLOPs FLOPS:注意全大写,是floating point operations per second的缩写,意指每秒浮点运算次数,理解为计算速度。是一个衡量硬件性能的指标。 FLOPs:注意s小写,是floating point operations的缩写(s表复数),意指浮点运算...原创 2022-03-09 15:28:50 · 5215 阅读 · 0 评论 -
Tensorflow 2.0 GPU的使用与分配
一、获得当前主机上特定运算设备的列表gpus = tf.config.experimental.list_physical_devices(device_type='GPU')cpus = tf.config.experimental.list_physical_devices(device_type='CPU')print(gpus, cpus)二、设置当前程序可见的设备范围默认情况下 TensorFlow 会使用其所能够使用的所有 GPU。tf.config.experimenta原创 2021-04-16 20:04:38 · 995 阅读 · 0 评论 -
自定义交叉熵损失计算出现nan值问题解决
交叉熵损失函数本身的公式比较简单,但是在实际定义的时候需要注意exp(x)函数的溢出问题,exp(x)函数在numpy或者说tensorflow的底层实现上,当x过大的时候会产生溢出,过小的时候直接范围近似值0,所以我们在定义交叉熵损失函数的时候需要注意这一点;1. 当模型返回的值是sigmoid函数映射过后的值,这里假设输入交叉熵的为x,那么我们计算的就是 -(y*np.log(x)+(1-y)*np.log(1-x))# y为标签值,x为预测值,标准的二分类交叉熵损失代码但是log(0..原创 2021-01-07 09:45:25 · 7852 阅读 · 2 评论 -
tf.cond()用法
在TensorFlow中,tf.cond()类似于if...else...,用来控制数据流向,但是仅仅类似而已,其中差别还是挺大的。format:tf.cond(pred, fn1, fn2, name=None)Return :either fn1() or fn2() based on the boolean predicate `pred`. # (注意这里,也就是说'fnq'和‘fn2’是两个函数)arguments:`fn1` and `fn2` both return lis原创 2021-01-07 09:24:52 · 726 阅读 · 0 评论 -
tf.clip_by_value用法
tf.clip_by_value(A, min, max):输入一个张量A,把A中的每一个元素的值都压缩在min和max之间。小于min的让它等于min,大于max的元素的值等于max。例如:import tensorflow as tf;import numpy as np; A = np.array([[1,1,2,4], [3,4,8,5]]) with tf.Session() as sess: print sess.run(tf.clip_by_value(A, 2, 5))原创 2021-01-07 09:19:44 · 285 阅读 · 0 评论 -
tf.reduce_sum用法
计算张量维度上的元素之和。沿给定的“轴”减小“ input_tensor”。 除非“ keepdims”为真,否则对于“轴”中的每个条目,张量的秩都会降低1。 如果`keepdims`为true,则减小的维度保留为长度1。如果`axis`为None,则缩小所有维度,并返回带有单个元素的张量。def reduce_sum_v1(input_tensor, axis=None, keepdims=None, .原创 2020-09-28 19:20:58 · 1095 阅读 · 0 评论 -
tf.one_hot用法
def one_hot(indices, depth, on_value=None, off_value=None, axis=None, dtype=None, name=None): """Returns a one-hot tensor. The locations represented by indices in `indices` take .原创 2020-09-28 16:16:07 · 300 阅读 · 0 评论 -
tf.reshape(t, [-1])用法
reshape(t, [-1])表示将张量t展平为一维def reshape(tensor, shape, name=None): r"""Reshapes a tensor. Given `tensor`, this operation returns a tensor that has the same values as `tensor` with shape `shape`. If one component of `shape` is the special value.原创 2020-09-28 16:07:59 · 1751 阅读 · 0 评论 -
TensorFlow数据读取方式:Dataset用法
在TensorFlow中读取数据一般有两种方法:使用placeholder读内存中的数据 使用queue读硬盘中的数据Dataset API同时支持从内存和硬盘的读取,相比之前的两种方法在语法上更加简洁易懂。此外,如果想要用到TensorFlow新出的Eager模式,就必须要使用Dataset API来读取数据。一、tensorflow读取机制图解首先需要思考的一个问题是,什么是数据读取?以图像数据为例,读取数据的过程可以用下图来表示:假设我们的硬盘中有一个图片数据集0001.jpg原创 2020-09-27 14:54:17 · 3969 阅读 · 1 评论 -
Tensorflow中Placeholder用法
Placeholder的中文意思就是占位符,用于在会话运行时动态提供输入数据。Placeholder相当于定义了一个位置,在这个位置上的数据在程序运行时再指定。在以后的编程中我们可能会遇到这样的情况:在训练神经网络时需要每次提供一个批量的训练样本,如果每次迭代选取的数据要通过常量表示,那么TensorFlow 的计算图会非常大。因为每增加一个常量,TensorFlow 都会在计算图中增加一个结点,所以说拥有几百万次迭代的神经网络会拥有极其庞大的计算图,而占位符却可以解决这一点,它只会拥有占位符这一个结点,原创 2020-09-27 14:33:43 · 1424 阅读 · 0 评论 -
TF读图片数据
import tensorflow as tfimport osos.environ["TF_CPP_MIN_LOGO_LEVEL"] = "2"def readIMG(file_list): """ :param file_list: 文件路径列表 :return: 每张图片的张量 """ # 1.构造文件队列 file_queue = tf.train.string_input_producer(file_list, shuffle=False.原创 2020-09-20 08:07:11 · 244 阅读 · 0 评论 -
tensorflow官方预训练模型下载网址
tensorflow官方预训练模型下载网址:https://github.com/tensorflow/models/tree/master/research/slim原创 2020-09-18 21:25:51 · 1065 阅读 · 0 评论 -
tf.nn.max_pool3d用法
tf.nn.max_pool3d:对输入执行最大池化。在tf 1.x中为tf.compat.v1.nn.max_pool3dtf.nn.max_pool3d( input, ksize, strides, padding, data_format='NDHWC', name=None) Args input 由data_format指定的格式的5-DTensor。 ksize 一个int或列表ints具有长度1,3或5。输入张量的每个维度的窗...原创 2020-09-16 20:01:52 · 1984 阅读 · 0 评论 -
tf.transpose用法
tf.transpose:意为转置转置`a`。 根据`perm`排列尺寸。返回的张量的维度i将对应于输入维`perm [i]`。 如果未给出`perm`,则将其设置为(n-1 ... 0),其中n是输入张量的秩。 因此,默认情况下,此操作会在2D输入张量上执行常规矩阵转置。 如果共轭是True,而a.dtype是complex64或complex128,则将a的值进行共轭和转置。transpose(a, perm=None, name="transpose", conjugate=False):原创 2020-09-16 14:19:40 · 2639 阅读 · 0 评论 -
tf.shape()和x.get_shape().as_list()用法
tf.shape()用法:获取张量的大小打印张量,结果是该张量的类型和形状。import tensorflow as tfimport numpy as npa_array = np.array([[1, 2, 3], [4, 5, 6]])b_list = [[1, 2, 3], [3, 4, 5]]c_tensor = tf.constant([[1, 2, 3], [4, 5, 6]])print(a_array)print(b_list)print(c_tensor)#原创 2020-09-16 08:40:49 · 1214 阅读 · 0 评论 -
tf.train.get_checkpoint_state用法
tf.train.get_checkpoint_state:从“检查点”文件返回CheckpointState原型。tf.train.get_checkpoint_state( checkpoint_dir, latest_filename=None)如果“检查点”文件包含有效的CheckpointState原型,则将其返回。 Args checkpoint_dir 检查点checkpoints的目录。 latest_filename 检查点che..原创 2020-09-14 13:41:41 · 3600 阅读 · 0 评论 -
tf.compat.v1.global_variables用法
tf.compat.v1.global_variables:返回全局变量。tf.compat.v1.global_variables( scope=None)全局变量是在分布式环境中的计算机之间共享的变量。该Variable()构造函数或get_variable()自动添加新的变数图表收集GraphKeys.GLOBAL_VARIABLES。此便捷功能返回该集合的内容。全局变量的替代方法是局部变量。看到tf.compat.v1.local_variables 精氨酸...原创 2020-09-14 10:54:29 · 1066 阅读 · 0 评论 -
tf.compat.v1.train.exponential_decay用法
tf.compat.v1.train.exponential_decay:将指数衰减应用于学习率。tf.compat.v1.train.exponential_decay( learning_rate, global_step, decay_steps, decay_rate, staircase=False, name=None)训练模型时,通常建议随着训练的进行降低学习率。此函数将指数衰减函数应用于提供的初始学习率。它需要一个global_step值来计算衰减的学习率。您只需传递一个原创 2020-09-14 10:17:29 · 1358 阅读 · 0 评论 -
tf.placeholder用法
import tensorflow as tfimport numpy as np# 以下两种shape方法都是可以的[] 和 ()# x = tf.placeholder(tf.float32, shape=[1024, 1024])x = tf.placeholder(tf.float32, shape=(1024, 1024))y = tf.matmul(x, x)with tf.Session() as sess: rand_array = np.random.rand(10.原创 2020-09-11 15:07:34 · 234 阅读 · 0 评论 -
Tensor flow保存与加载模型
Tensor flow模型文件结构: 1.meta文件:*.meta文件保存的是图结构2.ckpt文件:ckpt文件是二进制文件,保存了所有的weights、biases、gradients等变量。3.checkpoint文件:model目录下还有checkpoint文件,该文件是个文本文件,里面记录了保存的最新的checkpoint文件以及其它checkpoint文件列表。在infere...原创 2020-09-11 11:35:16 · 497 阅读 · 0 评论 -
tf.random.set_seed用法
tf.random.set_seed:设置全局随机种子。tf.random.set_seed( seed)依赖随机种子的操作实际上是从两个种子派生的:全局种子和操作级别种子。这设置了全局种子。它与操作级种子的交互如下:如果既未设置全局种子也未设置操作种子:此操作使用随机选择的种子。 如果设置了图级别的种子,但未设置操作种子:系统确定性地选择操作种子和图级别的种子,以便获得唯一的随机序列。在张量流和用户代码的相同版本中,此序列是确定性的。但是,在不同版本中,此顺序可能会更改。如果原创 2020-09-10 13:41:48 · 22397 阅读 · 7 评论 -
tf.nn.dropout用法
计算dropout:将元素随机设置为零以防止过拟合。tf.nn.dropout( x, rate, noise_shape=None, seed=None, name=None)另请参阅:tf.keras.layers.Dropout有关Dropout层的信息。Dropout对于正则化DNN模型很有用。输入元素被随机设置为零(其他元素被重新缩放)。这鼓励每个节点独立使用,因为它不能依赖其他节点的输出。更精确地:将x的概率rate个元素设置为0。其余元素按放大1.0 / (1 -原创 2020-09-10 09:21:34 · 2007 阅读 · 0 评论 -
tf.add_to_collection用法
tf.add_to_collection:使用默认图的Graph.add_to_collection()的包装。tf.compat.v1.add_to_collection( name, value)请参阅tf.Graph.add_to_collection以获取更多详细信息。 Args name 集合的键。例如,GraphKeys类包含许多集合的标准名称。 value 要添加到集合中的值。 Eager Compatibility..原创 2020-09-09 21:01:22 · 1931 阅读 · 0 评论 -
tf.get_variable用法
tf.get_variable:使用这些参数获取现有变量或创建一个新变量。tf.compat.v1.get_variable( name, shape=None, dtype=None, initializer=None, regularizer=None, trainable=None, collections=None, caching_device=None, partitioner=None, validate_shape=True, use_resource=None原创 2020-09-09 19:02:48 · 5477 阅读 · 0 评论 -
Tensorflow实现神经网络搭建
一般来说,神经网络分为模型,训练和测试,则通常可以包含三个文件,即model.py、train.py和test.py。下面以MNIST手写体数字识别的LeNet-5为例,完整搭建该神经网络。1.mnist_inference.pyimport tensorflow as tf# 定义神经网络结构相关的参数INPUT_NODE = 784 # 输入层的节点数。对于MNIST数据集,这个就等于图片的像素OUTPUT_NODE = 10 # 输出层的节点数。这个等于类别的数目。# 因为在M原创 2020-09-09 14:24:37 · 339 阅读 · 0 评论 -
Tensorflow可视化展示
# import modulesimport matplotlib.pyplot as pltimport tensorflow as tffrom tensorflow.examples.tutorials.mnist import input_dataimport osos.environ['CUDA_VISIBLE_DEVICES'] = '0'# 设置按需使用GPUconfig = tf.ConfigProto()config.gpu_options.allow_growth .原创 2020-09-08 21:45:33 · 334 阅读 · 0 评论 -
Tensorflow实现LeNet-5 MNIST手写体数字识别分类
# import modulesimport numpy as npimport matplotlib.pyplot as pltimport tensorflow as tfimport timefrom datetime import timedeltaimport mathfrom tensorflow.examples.tutorials.mnist import input_dataimport osos.environ['CUDA_VISIBLE_DEVICES'] = '.原创 2020-09-08 19:16:30 · 915 阅读 · 0 评论 -
tf.nn.conv3d用法
tf.nn.conv3d:给定 5-Dinput和filters张量,计算 3-D 卷积。tf.nn.conv3d( input, filters, strides, padding, data_format='NDHWC', dilations=None, name=None)在信号处理中,互相关是两个波形的相似性的量度,时滞应用到两个波形之一的函数。这也称为滑动点积或滑动内积。我们的Conv3D实现了一种互相关形式。 Args input ...原创 2020-09-08 15:06:08 · 1574 阅读 · 0 评论 -
MNIST手写数字识别之Tensorflow实现---CNN实现
from __future__ import absolute_importfrom __future__ import divisionfrom __future__ import print_functionimport tensorflow as tffrom tensorflow.examples.tutorials.mnist import input_datafrom tensorflow.examples.tutorials.mnist import mnist# os.en.原创 2020-09-08 14:16:10 · 178 阅读 · 0 评论 -
tensorflow入门实例
import tensorflow as tf# 创建一个整型常量,即 0 阶 Tensort0 = tf.constant(3, dtype=tf.int32)# 创建一个浮点数的一维数组,即 1 阶 Tensort1 = tf.constant([3., 4.1, 5.2], dtype=tf.float32)# 创建一个字符串的2x2数组,即 2 阶 Tensort2 = tf.constant([['Apple', 'Orange'], ['Potato', 'Tomato']].原创 2020-09-08 09:25:40 · 167 阅读 · 0 评论 -
tf.nn.conv2d用法
tf.nn.conv2d:给定input和4Dfilters张量计算2D卷积。tf.nn.conv2d( input, filters, strides, padding, data_format='NHWC', dilations=None, name=None)输入input张量可以具有秩4或更高,其中,形状维度[:-3]被认为是批量维度(batch_shape)。给定shape的输入张量batch_shape + [in_height, in_width, in_chan...原创 2020-09-07 20:06:33 · 3277 阅读 · 1 评论 -
MNIST手写数字识别之Tensorflow实现---全连接实现
import tensorflow as tf# 用tensorflow 导入数据from tensorflow.examples.tutorials.mnist import input_dataimport osos.environ['CUDA_VISIBLE_DEVICES'] = '0'# 设置按需使用GPUconfig = tf.ConfigProto()config.gpu_options.allow_growth = Truesess = tf.InteractiveSe.原创 2020-09-04 16:14:47 · 336 阅读 · 0 评论 -
tf.compat.v1.reduce_mean用法
tf.compat.v1.reduce_mean:计算跨张量维度的元素的均值。tf.compat.v1.reduce_mean( input_tensor, axis=None, keepdims=None, name=None, reduction_indices=None, keep_dims=None)通过计算各个维度axis的元素平均值,沿给定的维度axis减少input_tensor。除非keepdims为true,否则对于axis中的每个条目,张量的等级都会降低1。如...原创 2020-09-04 10:09:56 · 497 阅读 · 0 评论 -
tf.cast用法
tf.cast:将张量转换为新类型tf.cast( x, dtype, name=None)该操作将x(如果是Tensor)或x.values(如果是SparseTensor或IndexedSlices)强制转换为dtype。例子:x = tf.constant([1.8, 2.2], dtype=tf.float32)tf.dtypes.cast(x, tf.int32)操作支持的数据类型(x和dtype的)为:uint8,uint16,uint32,uint6...原创 2020-09-04 09:21:16 · 5061 阅读 · 0 评论 -
tf.argmax用法
tf.argmax():返回跨张量轴的最大值的索引。tf.compat.v1.argmax( input, axis=None, name=None, dimension=None, output_type=tf.dtypes.int64)注意,如果是ties,则不能保证返回值的同一性。用法:import tensorflow as tfa = [1, 10, 26.9, 2.8, 166.32, 62.3]b = tf.math.argmax(input = a)c =原创 2020-09-03 21:24:51 · 795 阅读 · 0 评论 -
tf.Session()用法
tf.Session:创建一个新的TensorFlow会话。tf.Session(self, target='', graph=None, config=None)如果在构造会话时未指定`graph`参数,则默认图将在会话中启动。 如果在同一过程中使用多个图(通过tf.Graph()创建),则每个图必须使用不同的会话,但是每个图可以在多个会话中使用。 在这种情况下,将要显式启动的图传递给会话构造函数通常更为清晰。Args:target:(可选)要连接的执行引擎。 默认为使用进程内引擎。.原创 2020-09-01 16:37:26 · 22958 阅读 · 0 评论 -
tf.compat.v1.summary.FileWriter用法
tf.compat.v1.summary.FileWriter:将Summary协议缓冲区写入事件文件。tf.compat.v1.summary.FileWriter( logdir, graph=None, max_queue=10, flush_secs=120, graph_def=None, filename_suffix=None, session=None)本FileWriter类提供了一个机制来创建指定目录的事件文件,并添加摘要和事件给它。该类异步更新文件内容...原创 2020-09-01 15:07:11 · 2073 阅读 · 0 评论 -
tensorboard入门实例
import tensorflow as tf# 创建节点时设置name,方便在图中识别W = tf.Variable([0], dtype=tf.float32, name='graph_W')b = tf.Variable([0], dtype=tf.float32, name='graph_b')# 创建节点时设置name,方便在图中识别x = tf.placeholder(tf.float32, name='graph_x')y = tf.placeholder(tf.float3.原创 2020-09-01 14:09:54 · 309 阅读 · 1 评论 -
tf.train.ExponentialMovingAverage用法
tf.train.ExponentialMovingAverage:通过采用指数衰减来保持变量的移动平均值。tf.train.ExponentialMovingAverage( decay, num_updates=None, zero_debias=False, name='ExponentialMovingAverage')训练模型时,保持训练参数的移动平均值通常是有益的。 使用平均参数的评估有时会产生比最终训练值明显更好的结果。apply()方法添加训练变量的影子副本,并添加操原创 2020-08-25 09:58:50 · 1262 阅读 · 0 评论 -
tf.control_dependencies()用法
示例程序1:观察下面程序可以发现,每更新一次update_a操作,就会更新a和b的值import tensorflow as tfa = tf.Variable(initial_value=[1.], dtype=tf.float32)b = a + 3update_a = tf.assign(a, b)init = tf.global_variables_initializer()with tf.Session() as sess: sess.run(init)原创 2020-08-24 12:47:52 · 426 阅读 · 0 评论