首页 技术 正文
技术 2022年11月18日
0 收藏 728 点赞 4,804 浏览 6913 个字

以下函数的用法基于Tensorflow1.4版本。

1、tf.constant

tf.constant方法用来定义一个常量,所谓常量,就是“不变化的量”。我们先看下官方Api是如何对constant函数来定义的:

tf.constant(
value,
dtype=None,
shape=None,
name='Const',
verify_shape=False
)

其中包括5个输入值:

value(必填):常量值,可以是一个数,也可以是一个向量或矩阵。

dtype(非必填):用来指定数据类型,例如tf.float32类型或tf.float64。

shape(非必填):用来指定数据的维度。

name(非必填):为常量定义名称,默认为Const。

verify_shape(非必填):默认值为False,如果值为True时,在定义常量时会自动检测value和shape维度是否相同,不同则报错,例如value定义为1,而shape定义为一行两列的矩阵(1,2),那么肯定会报错。

了解了参数的具体含义,我们用代码来验证一下吧!

指定value的值:

#定义一个整数
a = tf.constant(1)
#定义一个向量
b = tf.constant([1,2])
#定义一个2行3列的矩阵
c = tf.constant([[1,2,3],[4,5,6]])
print(a)
print(b)
print(c)

输出结果:

Tensor("Const:0", shape=(), dtype=int32)
Tensor("Const_1:0", shape=(2,), dtype=int32)
Tensor("Const_2:0", shape=(2, 3), dtype=int32)

变量a的shape为空,0个纬度,也就是一个数值;

变量b的shape是(2,),只有一个维度,是一个长度为2向量;

变量c的shape是(2,3),有两个维度,是一个2X3的矩阵。

当指定dtype参数时:

#定义一个整数
a = tf.constant(1,dtype=tf.float32)
#定义一个向量
b = tf.constant([1,2],dtype=tf.float32)
#定义一个2行3列的矩阵
c = tf.constant([[1,2,3],[4,5,6]],dtype=tf.float32)
print(a)
print(b)
print(c)

输出结果:

Tensor("Const:0", shape=(), dtype=float32)
Tensor("Const_1:0", shape=(2,), dtype=float32)
Tensor("Const_2:0", shape=(2, 3), dtype=float32)

可见数值的类型都变为float32类型。

当指定shape参数时:

#定义一个整数
a = tf.constant(2.,shape=())
b = tf.constant(2.,shape=(3,))
c = tf.constant(2.,shape=(3,4))
with tf.Session() as sess:
print(a.eval())
print(b.eval())
print(c.eval())

输出结果:

2.0
[2. 2. 2.]
[[2. 2. 2. 2.]
 [2. 2. 2. 2.]
 [2. 2. 2. 2.]]

此时constant会根据shape指定的维度使用value值来进行填充,例如参数a指定维度为0,也就是一个整数;参数b指定维度为1长度为3,也就是一个向量;参数b指定维度为2长度为3X4,也就是定义一个3X4的矩阵,全部都使用value值2.0来进行填充。

当指定name参数时:

#不指定name
a = tf.constant(2.)
#指定name
b = tf.constant(2.,name="b")
print(a)
print(b)

输出结果:

Tensor("Const:0", shape=(), dtype=float32)
Tensor("b:0", shape=(), dtype=float32)

常量的默认名称为Const,建议大家创建常量时最好定义一下name,只要是字符串就没有问题。

当指定verify_shape=True时:

a = tf.constant(2.,shape=(2,3),verify_shape=True)

输出结果报错:

TypeError: Expected Tensor's shape: (2,3), got ().

错误原因是value的值和指定的shape维度不同,value是一个数值,而我们指定的shape为2X3的矩阵,所以报错!当我们去掉verify_shape参数时错误即消失。那么问题来了,此时这个常量到底是整数还是一个矩阵呢?当然是矩阵啦(一个被value值填充的2X3矩阵)!

2、tf.Variable

tf.Variable方法用来定义一个变量,所谓变量,就是“变化的量”。我们看一下函数的定义:

tf.Variable(
initial_value=None,
trainable=True,
collections=None,
validate_shape=True,
caching_device=None,
name=None,
variable_def=None,
dtype=None,
expected_shape=None,
import_scope=None,
constraint=None
)

是不是参数多到令人发指!目前感觉最常用的也就是initial_value、name、dtype,用法和tf.constant类似,这里不用代码做过多演示。

3、tf.zeros

tf.zeros用来定义一个全部元素都为0的张量,例如一个全为0的矩阵或向量,看一下函数的定义:

tf.zeros(
shape,
dtype=tf.float32,
name=None
)

shape:数据的维度。

dtype:数据得类型。

name:命名。

#长度为1的1维向量
a = tf.zeros([1])
#长度为2的1维向量
b = tf.zeros([2])
#2维矩阵,矩阵大小3X4
c = tf.zeros([3,4])
with tf.Session() as sess:
print(sess.run(a))
print(sess.run(b))
print(sess.run(c))

输出结果:

[0.]
[0. 0.]
[[0. 0. 0. 0.]
[0. 0. 0. 0.]
[0. 0. 0. 0.]]

4、tf.ones

和tf.zeros功能相似,tf.ones用来定义一个全部元素都为1的张量,例如一个全为1的矩阵或向量,看一下函数的定义:

tf.ones(
shape,
dtype=tf.float32,
name=None
)

测试代码:

#长度为1的1维向量
a = tf.ones([1],name="n1",dtype=tf.float32)
#长度为2的1维向量
b = tf.ones([2])
#2维矩阵,矩阵大小3X4
c = tf.ones([3,4])
with tf.Session() as sess:
print(sess.run(a))
print(sess.run(b))
print(sess.run(c))

输出结果:

[1.]
[1. 1.]
[[1. 1. 1. 1.]
[1. 1. 1. 1.]
[1. 1. 1. 1.]]

5、tf.random_uniform

tf.random_uniform可用来生成一个被随机数填充的张量,可以是向量或矩阵,函数定义为:

tf.random_uniform(
shape,
minval=0,
maxval=None,
dtype=tf.float32,
seed=None,
name=None
)

参数说明:

shape:定义形状

minval:随机数最小值,默认是0

maxval:随机数最大值,默认是1

dtype:数据得类型,默认是float32类型

seed:随机数种子

name:定义返回值名称

#定义一个由最小值为0,最大值为0.5填充的向量
a = tf.random_uniform([3],0,0.5,name="a")
#定义一个由最小值为-1,最大值为1填充的4X3的矩阵
b = tf.random_uniform([4,3],-1,1,name="b")
#定义一个最小值为10,最大值为100的随机数
c = tf.random_uniform([],10,100,name="c")
#定义seed为1
d = tf.random_uniform([],10,100,seed=1)
e = tf.random_uniform([],10,100,seed=1)
#定义seed为2
f = tf.random_uniform([],10,100,seed=2)with tf.Session() as sess:
print(sess.run(a))
print(sess.run(b))
print(sess.run(c))
print(sess.run(d))
print(sess.run(e))
print(sess.run(f))

输出结果:

[0.37117624 0.28079355 0.12813371]
[[ 0.50496936 0.2632537 -0.30630517]
[ 0.16871548 0.7529404 -0.6158774 ]
[-0.9147036 0.35593843 -0.50358105]
[-0.4618771 -0.26037788 0.7437594 ]]
40.39641
31.513365
31.513365
71.08719

从结果中我们会发现,值d和e在设置相同seed的情况下,随机数值的相同的,这就意味着,如果最小值、最大值以及种子定义完全相同的话,随机数值也是相同的。如果想在相同范围内得到不同的随机数值,请修改seed

6、tf.add

tf.add方法计算两个张量之和,先看函数格式:

tf.add(
x,
y,
name=None
)

x:张量1

y:张量2

name:计算结果命名

注:输入的x,y两个张量的类型必须一致

#数值加法
a = tf.constant(3)
b = tf.constant(4)
c = tf.add(a,b)#向量加法
a1 = tf.constant([1,2])
b1 = tf.constant([3,4])
c1 = tf.add(a1,b1)#矩阵加法
a2 = tf.constant([[1,1],[2,2]])
b2 = tf.constant([[3,3],[4,4]])
c2 = tf.add(a2,b2)with tf.Session() as sess:
print("数值加法")
print(sess.run(c))
print("向量加法")
print(sess.run(c1))
print("矩阵加法")
print(sess.run(c2))

输出结果:

数值加法
7
向量加法
[4 6]
矩阵加法
[[4 4]
[6 6]]

7、tf.subtract

tf.subtract方法计算两个张量之差,与tf.add结构相同。同样需要注意的是,传入的两个张量的类型必须保持一致。

tf.subtract(
x,
y,
name=None
)

8、tf.matmul和tf.multiply

之所以把matmul和multipy放在一起讨论,因为好多人会把这两个函数搞混。

tf.matmul是矩阵乘法,tf.multiply是元素乘法。

#定义一个被数值2填充的2X3矩阵
a = tf.constant(2,shape=(2,3),name="a")
#定义一个被数值3填充的2X3矩阵
b = tf.constant(3,shape=(2,3),name="b")
#定义一个被数
c = tf.constant(5,name="c")
#multiply
d = tf.multiply(a,b)
#multiply
e = tf.multiply(a,c)
init = tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init)
print('a的值')
print(sess.run(a))
print('b的值')
print(sess.run(b))
print('c的值')
print(sess.run(c))
print('matmul(a,b)')
print(sess.run(d))
print('matmul(a,c)')
print(sess.run(e))

输出结果:

a的值
[[2 2 2]
[2 2 2]]
b的值
[[3 3 3]
[3 3 3]]
c的值
5
matmul(a,b)
[[6 6 6]
[6 6 6]]
matmul(a,c)
[[10 10 10]
[10 10 10]]

a、b是两个矩阵,ca和b类型一致,可以multiply,结果依然是一个2X3的矩阵;

a是一个矩阵,c是一个数值,虽类型不同,但依然可以multiply,结果和a的类型保持一致。

所以multiply的两个输入的张量类型可以不一致。

#定义一个被数值2填充的2X3矩阵
a = tf.constant(2,shape=(2,3),name="a")
#定义一个被数值3填充的2X3矩阵
b = tf.constant(3,shape=(3,3),name="b")
#multiply
c = tf.matmul(a,b)
init = tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init)
print('a的值')
print(sess.run(a))
print('b的值')
print(sess.run(b))
print('matmul后')
print(sess.run(c))

输出结果:

a的值
[[2 2 2]
[2 2 2]]
b的值
[[3 3 3]
[3 3 3]
[3 3 3]]
matmul后
[[18 18 18]
[18 18 18]]

a、b两个矩阵被函数matmul处理后,依然是一个2X3的矩阵,matmul要求两个输入的张量类型必须完全的一致。

9、tf.divide

浮点数除法,两个输入的张量类型可以不一致。

tf.divide(
x,
y,
name=None
)

10、tf.mod

两个张量相除并取余。

tf.mod(
x,
y,
name=None
)

11、tf.placeholder

之前我们了解了如何用tf.constant定义常量,用tf.Variable定义变量,那加入我想在运算过程中动态的修改传入的值呢?我们可以考虑使用placeholder,也就是占位符。我们先看一下它的结构:

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

结构很简单,那我们为什么要用占位符呢?这其实就设计到了Tensorflow的设计理念,作为入门教程的第二篇,我们先不讲其设计理念和计算流图,我们只要记住,在未创建Tensorflow的session会话之前,定义的所有变量、常量其实都还没有进行计算,我们使用placeholder可以先为一个变量预留出一份内存,等Tensorflow启动session会话以后,就可以将数据喂到这个预留的内存中去,实现Tensorflow运算过程中的动态赋值,文字不好理解,直接上代码:

import tensorflow as tf
import numpy as np
#定义一个数值
a = tf.constant(2.,name="a")
#定义一个数值类型的placeholder
b = tf.placeholder(tf.float32,[],name="b")
#定义一个矩阵类型的placeholder
c = tf.placeholder(tf.float32,[2,3],name="c")
#d为a*b
d = tf.multiply(a,b)
#e为a*c
e = tf.multiply(a,c)
#一个随机数组
rand_value = np.random.rand(2,3)
init = tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init)#初始化变量
print("从0循环到9,分别乘2")
for i in range(10):
print(sess.run(d,feed_dict={b:i}))
print("传入随机生成的一个数组")
print(sess.run(e,feed_dict={c:rand_value}))

输出结果:

从0循环到9,分别乘2
0.0
2.0
4.0
6.0
8.0
10.0
12.0
14.0
16.0
18.0
传入随机生成的一个数组
[[0.7041698 1.0414026 1.973911 ]
[1.952334 0.46541974 1.1905501 ]]

d的值等于a乘b,a的值为2.0,b为一个占位符,在运算过程中,通过feed_dict动态的修改了b的值,得到了不同的计算结果。

e的值等于a乘c,a的值为2.0,c为一个2X3的矩阵占位符,运算过程中,使用feed_dict动态的把随机矩阵rand_value喂到了运算中,计算得到了不同的结果。

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,088
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,564
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,412
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,185
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,822
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,905