TensorFlow深度学习入门笔记四一些基本函数

关注公众号“从机器学习到深度学习那些事”获取更多最新资料

写在前面

学习建议:以下学习过程中有不理解可以简单查找下资料,但不必纠结(比如非得深究某一个函数等),尽量快速的学一遍,不求甚解无妨。多实操代码,不能只复制代码,或者感觉懂了就只看。熟能生巧,我亦无他,唯手熟尔

今天介绍一些基础函数及其用法,基本全是代码,一些解释都放在代码的注释里了。直接看代码吧,记得在你本地跑一下看哦

代码1

#tensor.get_shape() 获取tensor的shape,就是维度这些
#tensor.get_shape().as_list(),把shape转换成列表形式
# 上面这两个函数不常直接用,在理解TensorFlow的用法等有帮助,就先列在这里了
# 
a = tf.constant([[1, 2, 3], [4, 5, 6]], dtype=tf.float32, name='a')
with tf.Session() as sess:
   print(a.eval())
   print("shape: ", a.get_shape(), ",type: ", type(a.get_shape()))
   print("shape: ", a.get_shape().as_list(), ",type: ", type(a.get_shape().as_list()))

'''
输出如下
[[1. 2. 3.]
[4. 5. 6.]]
shape:  (2, 3) ,type:  <class 'tensorflow.python.framework.tensor_shape.TensorShape'>
shape:  [2, 3] ,type:  <class 'list'>
'''

代码2

#tf.argmax
#tf.argmax(input, dimension, name=None) returns the index with the largest value across dimensions of a tensor.
# 上面注释是英文的,翻译下就是,tf.argmax()这个函数输入的张量中,沿着指定维度中最大的一个值的索引,可以这样理解,0就是行,1就是列,3等更大的就是沿着更好维度算,下面的例子理解下。
# 注意,返回的是索引号
a = tf.constant([[1, 6, 5], [2, 3, 4]])
with tf.Session() as sess:
   print(a.eval())
   print("argmax over axis 0")
   print(tf.argmax(a, 0).eval())
   print("argmax over axis 1")
   print(tf.argmax(a, 1).eval())
'''
[[1 6 5]
[2 3 4]]
argmax over axis 0
[1 0 0]
argmax over axis 1
[1 2]
'''

代码3

#tf.reduce_sum
#tf.reduce_sum(input_tensor, reduction_indices=None, keep_dims=False, name=None) computes the sum of elements across dimensions of a tensor. Unless keep_dims is true, the rank of the tensor is reduced by 1 for each entry in reduction_indices. If keep_dims is true, the reduced dimensions are retained with length 1. If reduction_indices has no entries, all dimensions are reduced, and a tensor with a single element is returned
# 大概翻译下,就是求和,计算张量的各维度上的元素的和。还有两个参数, keep_dims和reduction_indices,下面代码执行并理解下
a = tf.constant([[1, 1, 1], [2, 2, 2]])
with tf.Session() as sess:
   print(a.eval())
   print("reduce_sum over entire matrix")
   print(tf.reduce_sum(a).eval())
   print("reduce_sum over axis 0")
   print(tf.reduce_sum(a, 0).eval())
   print("reduce_sum over axis 0 + keep dimensions")
   print(tf.reduce_sum(a, 0, keep_dims=True).eval())
   print("reduce_sum over axis 1")
   print(tf.reduce_sum(a, 1).eval())
   print("reduce_sum over axis 1 + keep dimensions")
   print(tf.reduce_sum(a, 1, keep_dims=True).eval())
'''
输出:
[[1 1 1]
[2 2 2]]
reduce_sum over entire matrix
9
reduce_sum over axis 0
[3 3 3]
reduce_sum over axis 0 + keep dimensions
[[3 3 3]]
reduce_sum over axis 1
[3 6]
reduce_sum over axis 1 + keep dimensions
[[3]
[6]]
'''

代码4

'''
tf.get_variable,是用来获取或者创建一个变量的函数,它需要用一个初始化函数,根据给的shape初始化相同shape的tensor。初始化函数有很多种,前面一篇中也有介绍过,各种随机初始化,常数初始化等,
# 看下面例子
tf.get_variable(name, shape=None, dtype=None, initializer=None, trainable=True) is used to get or create a variable instead of a direct call to tf.Variable. It uses an initializer instead of passing the value directly, as in tf.Variable. An initializer is a function that takes the shape and provides a tensor with that shape. Here are some initializers available in TensorFlow:
•tf.constant_initializer(value) initializes everything to the provided value,
•tf.random_uniform_initializer(a, b) initializes uniformly from [a, b],
•tf.random_normal_initializer(mean, stddev) initializes from the normal distribution with the given mean and standard deviation.
'''

my_initializer = tf.random_normal_initializer(mean=0, stddev=0.1)
v = tf.get_variable('v', shape=[2, 3], initializer=my_initializer)
with tf.Session() as sess:
   tf.initialize_all_variables().run()
   print(v.eval())

"""
[[ 0.14729649 -0.07507571 -0.00038549]
[-0.02985961 -0.01537443  0.14321376]]
"""

代码5

my_initializer = tf.random_normal_initializer(mean=0, stddev=0.1)
v = tf.get_variable('v', shape=[2, 3], initializer=my_initializer)


# tf.variable_scope 这个函数是管理变量的命名空间的,这个也是方便tensorboard中能可视化,使模型逻辑流程等更容易理解等
# tf.variable_scope(scope_name) manages namespaces for names passed to tf.get_variable.
with tf.variable_scope('layer1'):
   w = tf.get_variable('v', shape=[2, 3], initializer=my_initializer)
   print(w.name)

with tf.variable_scope('layer2'):
   w = tf.get_variable('v', shape=[2, 3], initializer=my_initializer)
   print(w.name)
'''
layer1/v:0
layer2/v:0
'''

代码6

'''
reuse_variables
上面的代码只能运行一次,就是因为这个reuse_variables,
用这个scope.reuse_variables()来获取(重用)之前创建的变量,而不是再创建一个新的
Note that you should run the cell above only once. If you run the code above more than once, an error message will be printed out: "ValueError: Variable layer1/v already exists, disallowed.". This is because we used tf.get_variable above, and this function doesn't allow creating variables with the existing names. We can solve this problem by using scope.reuse_variables() to get preivously created variables instead of creating new ones.
'''
my_initializer = tf.random_normal_initializer(mean=0, stddev=0.1)
v = tf.get_variable('v', shape=[2, 3], initializer=my_initializer)

with tf.variable_scope('layer1'):
   w = tf.get_variable('v', shape=[2, 3], initializer=my_initializer)
   # print(w.name)

with tf.variable_scope('layer2'):
   w = tf.get_variable('v', shape=[2, 3], initializer=my_initializer)
   # print(w.name)

with tf.variable_scope('layer1', reuse=True):
   w = tf.get_variable('v')   # Unlike above, we don't need to specify shape and initializer
   print(w.name)

   # or
with tf.variable_scope('layer1') as scope:
   scope.reuse_variables()
   w = tf.get_variable('v')
   print(w.name)

小结

今天主要是贴代码了,没有过多的文字解释,一些解释也尽量放在代码注释中,这样在本地自己电脑上运行也方便理解。初学的话代码还是要自己敲一遍,自己敲的过程中肯定会遇到一些问题,这就是反复学习的过程,还是不要省。
今天代码中的英文依然没有抹去,尽量看一下,顺便学下英语也不错。主要是因为有些英文文档不好翻译过来反而不好理解,相信这种情况以后也会遇到。所以可以先学点。

本篇完

 

原文地址:https://www.cnblogs.com/ziyan09/p/10417921.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


MNIST数据集可以说是深度学习的入门,但是使用模型预测单张MNIST图片得到数字识别结果的文章不多,所以本人查找资料,把代码写下,希望可以帮到大家~1#BudingyourfirstimageclassificationmodelwithMNISTdataset2importtensorflowastf3importnumpyasnp4impor
1、新建tensorflow环境(1)打开anacondaprompt,输入命令行condacreate-ntensorflowpython=3.6注意:尽量不要更起名字,不然环境容易出错在选择是否安装时输入“y”(即为“yes”)。其中tensorflow为新建的虚拟环境名称,可以按喜好自由选择。python=3.6为指定python版本为3
这篇文章主要介绍“张量tensor是什么”,在日常操作中,相信很多人在张量tensor是什么问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大...
tensorflow中model.fit()用法model.fit()方法用于执行训练过程model.fit(训练集的输入特征,训练集的标签,batch_size,#每一个batch的大小epochs,#迭代次数validation_data=(测试集的输入特征,
https://blog.csdn.net/To_be_little/article/details/124438800 目录1、查看GPU的数量2、设置GPU加速3、单GPU模拟多GPU环境1、查看GPU的数量importtensorflowastf#查看gpu和cpu的数量gpus=tf.config.experimental.list_physical_devices(device_type='GPU')cpus=tf.c
根据身高推测体重const$=require('jquery');consttf=require('@tensorflowfjs');consttfvis=require('@tensorflowfjs-vis');/*根据身高推测体重*///把数据处理成符合模型要求的格式functiongetData(){//学习数据constheights=[150,151,160,161,16
#!/usr/bin/envpython2#-*-coding:utf-8-*-"""CreatedonThuSep610:16:372018@author:myhaspl@email:myhaspl@myhaspl.com二分法求解一元多次方程"""importtensorflowastfdeff(x):y=pow(x,3)*3+pow(x,2)*2-19return
 继续上篇的pyspark集成后,我们再来看看当今热的不得了的tensorflow是如何继承进pycharm环境的参考:http://blog.csdn.net/include1224/article/details/53452824思路其实很简单,说下要点吧1.python必须要3.564位版本(上一篇直接装的是64位版本的Anaconda)2.激活3.5版本的
首先要下载python3.6:https://www.python.org/downloadselease/python-361/接着下载:numpy-1.13.0-cp36-none-win_amd64.whl 安装这两个:安装python3.6成功,接着安装numpy.接着安装tensorflow: 最后测试一下: python3.6+tensorflow安装完毕,高深的AI就等着你去
参考书《TensorFlow:实战Google深度学习框架》(第2版)以下TensorFlow程序完成了从图像片段截取,到图像大小调整再到图像翻转及色彩调整的整个图像预处理过程。#!/usr/bin/envpython#-*-coding:UTF-8-*-#coding=utf-8"""@author:LiTian@contact:694317828@qq.com
参考:TensorFlow在windows上安装与简单示例写在开头:刚开始安装的时候,由于自己的Python版本是3.7,安装了好几次都失败了,后来发现原来是tensorflow不支持3.7版本的python,所以后来换成了Python3.6,就成功了。。。。。anconda:5.3.2python版本:3.6.8tensorflow版本:1.12.0安装Anconda
实验介绍数据采用CriteoDisplayAds。这个数据一共11G,有13个integerfeatures,26个categoricalfeatures。Spark由于数据比较大,且只在一个txt文件,处理前用split-l400000train.txt对数据进行切分。连续型数据利用log进行变换,因为从实时训练的角度上来判断,一般的标准化方式,
 1)登录需要一个 invitationcode,申请完等邮件吧,大概要3-5个小时;2)界面3)配置数据集,在右边列设置 
模型文件的保存tensorflow将模型保持到本地会生成4个文件:meta文件:保存了网络的图结构,包含变量、op、集合等信息ckpt文件:二进制文件,保存了网络中所有权重、偏置等变量数值,分为两个文件,一个是.data-00000-of-00001文件,一个是.index文件checkpoint文件:文本文件,记录了最新保持
原文地址:https://blog.csdn.net/jesmine_gu/article/details/81093686这里只是做个收藏,防止原链接失效importosimportnumpyasnpfromPILimportImageimporttensorflowastfimportmatplotlib.pyplotaspltangry=[]label_angry=[]disgusted=[]label_d
 首先声明参考博客:https://blog.csdn.net/beyond_xnsx/article/details/79771690?tdsourcetag=s_pcqq_aiomsg实践过程主线参考这篇博客,相应地方进行了变通。接下来记载我的实践过程。  一、GPU版的TensorFlow的安装准备工作:笔者电脑是Windows10企业版操作系统,在这之前已
1.tensorflow安装  进入AnacondaPrompt(windows10下按windows键可找到)a.切换到创建好的tensorflow36环境下:activatetensorflow36    b.安装tensorflow:pipinstlltensorflow    c.测试环境是否安装好       看到已经打印出了"h
必须走如下步骤:sess=tf.Session()sess.run(result)sess.close()才能执行运算。Withtf.Session()assess:Sess.run()通过会话计算结果:withsess.as_default():print(result.eval())表示输出result的值生成一个权重矩阵:tf.Variable(tf.random_normal([2,3]
tf.zeros函数tf.zeros(shape,dtype=tf.float32,name=None)定义在:tensorflow/python/ops/array_ops.py.创建一个所有元素都设置为零的张量. 该操作返回一个带有形状shape的类型为dtype张量,并且所有元素都设为零.例如:tf.zeros([3,4],tf.int32)#[[0,0,
一、Tensorflow基本概念1、使用图(graphs)来表示计算任务,用于搭建神经网络的计算过程,但其只搭建网络,不计算2、在被称之为会话(Session)的上下文(context)中执行图3、使用张量(tensor)表示数据,用“阶”表示张量的维度。关于这一点需要展开一下       0阶张量称