Alexkk

1 基本数据类型

数值型,字符串性,布尔类型

1.1 数值型

标量:一般的 实数,shape为[],维度为0

向量: n 个实数的有序集合 ,shape为[n],维度为1

矩阵: n 行 m 列实数的有序集合,shape为[n,m],维度为2

张量:维度>2的数组

一般的:标量,向量,矩阵也统称为张量

1.1.1 标量的创建

a = 1.1
aa = tf.constant(1.2)#(标量)张量的创建方式
type(a),type(aa),tf.is_tensor(aa)
print(aa)
#Out[1]:
(float, tensorflow.python.framework.ops.EagerTensor, True)
x = tf.constant([1,2.,3.3])
print(x)
#out 
<tf.Tensor: id=165, shape=(3,), dtype=float32, numpy=array([1. , 2. , 3.3],
dtype=float32)>
x.numpy()
#out
[1., 2., 3.3]

其中 id 是 TensorFlow 中内部索引对象的编号, shape 表示张量的形状, dtype 表示张量的数
值精度, 张量 numpy()方法可以返回 Numpy.array 类型的数据,方便导出数据到系统的其他
模块:

1.1.2向量的创建方式

只能通过List类型传给tf.constant()

a = tf.constant([1, 2])
print(a)
print(a.shape) #error a.shape()
print(a.dtype)

out:

tf.Tensor([1 2], shape=(2,), dtype=int32)
(2,)
<dtype: \'int32\'>

1.1.2矩阵的创建

矩阵张量的创建如向量,也需要通过列表

a = tf.constant([[1, 2], [2.1,3.4])
print(a)
print(a.shape) #error a.shape()
print(a.dtype)
print(a.numpy())

out

tf.Tensor([[1.  2. ][2.1 3.4]], shape=(2, 2), dtype=float32)
(2, 2)
<dtype: \'float32\'>
[[1.  2. ][2.1 3.4]]

1.1.3高纬张量的创建

一般就是两个函数API,通过将Python 的List和Numpy的array转化为tensor:即tf.constant()和 tf.convert_to_tensor() 其中之一

a = tf.constant([[[1,2],[3,4]],[[5,6],[7,8]]])

1.2 字符串类型

TensorFlow 还支持字符串(String)类型的数据,例如在表示图片数据时,可以先记录图片的路径,再通过预处理函数根据路径读取图片张量。 通过传入字符串对象即可创建字符串类型的张量

a = tf.constant("hello,deep learning!")
print(a)

更多字符串的操作查看 tf.strings 模块

1.3 布尔类型

a = tf.constant(True)  

需要注意的是, TensorFlow 的布尔类型和 Python 语言的布尔类型并不对等,不能通用

a == True
#out
False

2 数值精度

2.1常用精度类型

常用的精度类型有 tf.int16, tf.int32, tf.int64, tf.float16, tf.float32, tf.float64,其中 tf.float64 即为 tf.double

对于大部分深度学习算法,一般使用 tf.int32, tf.float32 可满足运算精度要求,部分对
精度要求较高的算法,如强化学习,可以选择使用 tf.int64, tf.float64 精度保存张量

测试
import numpy as np
np.pi
tf.constant(np.pi, dtype=tf.float32)
#Out
<tf.Tensor: id=29, shape=(), dtype=float32, numpy=3.1415927>
#如果采用 tf.float32 精度保存

分类:

技术点:

相关文章: