Tensorflow 数据类型

文章目录[x]
  1. 1:什么是Tensor
  2. 2:创建数据
  3. 3:Tensor常见属性
  4. 3.1:tf.device
  5. 3.2:numpy
  6. 3.3:ndim 和 tf.rank
  7. 3.4:name

什么是Tensor

scalar : 1.1

vector : [1.1],[1.1,2.2,...]

matrix : [[1.1,2.2],[3.3,4.4],[5.5,6.6]]

tensor : rank>2(维度大于2,前面几种在tf中也可称为Tensor)

Tensorflow -> Tensor flow(数据(Tensor) 在网络上的 流动(flow))

Tensor支持int,float,double,bool,string数据类型

创建数据

tf.constant(1)    #在tf1.0版本中使用constant创建的为常量,不可更改,tf2.0中仅沿用了tf1.0中的函数名称,不代表其声明的是个常量
# <tf.Tensor: id=2, shape=(), dtype=int32, numpy=1> 注意dtype,根据所给参数来确定Tensor类型

tf.constant(1.)
# <tf.Tensor: id=4, shape=(), dtype=float32, numpy=1.0> 注意dtype,根据所给参数来确定Tensor类型

tf.constant(2.2, dtype=int32)    #会报错,因为数据格式与dtype不匹配
# TypeError: Cannot convert provided value to EagerTensor
# Provided value: 2.2 Requested dtype: int32

tf.constant(2., dtype=tf.double)
# <tf.Tensor: id=7, shape=(), dtype=float64, numpy=2.0> 注意dtype,在匹配的情况下根据所给dtype参数来确定Tensor类型

tf.constant([True, False])
# <tf.Tensor: id=9, shape=(2,), dtype=bool, numpy=array[[True, False]]> 注意dtype,根据所给参数来确定Tensor类型

tf.constant('hello world.')
# <tf.Tensor: id=14, shape=(), dtype=string, numpy=b'hello world.'> 注意dtype,根据所给参数来确定Tensor类型

Tensor常见属性

tf.device

device属性是一个string值,返回的是目前Tensor所在设备名

# 使用cpu环境创建Tensor
with tf.device("cpu"):
    a=tf.constant([1])
a.device    #'/job:localhost/replica:0/task:0/device:CPU:0'


# 使用gpu环境创建Tensor
with tf.devide("gpu"):
    b=tf.range(4)
b.device    #'/job:localhost/replica:0/task:0/device:GPU:0'

# 对于在cpu上的Tensor(a)可进行设备切换
aa=a.gpu()
aa.device    #'/job:localhost/replica:0/task:0/device:GPU:0'

# 对于在gpu上的Tensor(b)可进行设备切换
bb=b.cpu()
bb.device    #'/job:localhost/replica:0/task:0/device:CPU:0'

Tensor在CPU和GPU上的区别是对于在CPU上的Tensor,只能进行CPU允许的操作,同样,对于在GPU上的Tensor,只能进行GPU允许的操作,tensorflow会自动根据数据属性进行操作选择

numpy

使用numpy可快速得到numpy类型的数据

# 代码接前篇device部分,部分变量在前篇已声明
b.ndim    # 1
# b=1,b.ndim=0
# b=[1],b.ndim=1

 

b.numpy() # array([0, 1, 2, 3], dtype=int32)

ndim 和 tf.rank

可以用ndim获取数据的维度(秩),返回类型为数字

可以用tf.rank获取数据的维度(秩),返回类型为Tensor

# 代码接前篇device部分,部分变量在前篇已声明
b.ndim    #1
# b=1,b.ndim=0
# b=[1],b.ndim=1

tf.rank(b)    # <tf.Tensor: id=20, shape=(), dtype=int32, numpy=1>
tf.rank(tf.ones([3,4,2]))    # <tf.Tensor: id=25, shape=(), dtype=int32, numpy=3>

name

name为tf1.0遗留,在tf2.0中并不需要,因为b.name就是b

b.name
# Tensor.name is meaningless when eager execution is enabled

 

 

 

未完待续,每日更新中...

点赞

发表评论