Tensorflow教程(2)Tensorflow的经常使用函数介绍

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

一、tf.constant

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

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

其中包括5个输入值:dom

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

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

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

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

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

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

指定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)

输出结果:orm

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矩阵)!

二、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相似,这里不用代码作过多演示。

三、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.]]

四、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.]]

五、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

六、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]]

七、tf.subtract

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

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

八、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要求两个输入的张量类型必须彻底的一致。

九、tf.divide

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

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

十、tf.mod

两个张量相除并取余。

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

 十一、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喂到了运算中,计算获得了不一样的结果。

相关文章
相关标签/搜索