1.tf中常量的创建方法:
tf.constant(常量,dtype=数据类型)
2.tf中变量的创建方法:
tf.Variable(变量,dtype=数据类型)
3. tf中几种常见的数据类型:
有符号整型int(4种)
无符号整型uint(2种)
浮点型float(4种)
字符串型string(pytorch 不支持)
布尔型bool(pytorch 不支持)
复数型complex
数据类型 | 说明 |
| 8位整数 |
| 16位整数 |
| 32位整数 |
| 64位整数 |
| 8位无符号整数 |
| 16位无符号整数 |
| 16位浮点数 |
| 32位浮点数 |
| 64位浮点数 |
| 等同于 |
| 字符串 |
| 布尔型 |
| 64位复数 |
| 128位复数 |
4. tf中几种常用的计算函数
操作 | 描述 |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
5.Tensor
5.1 device
with tf.device('cpu'):
a = tf.constant([1])
with tf.device('gpu:0'):
b = tf.constant([2])
a.device # '/job:localhost/replica:0/task:0/device:CPU:0'
b.device # '/job:localhost/replica:0/task:0/device:GPU:0'
aa = a.gpu()
bb = b.cpu()
aa.device # '/job:localhost/replica:0/task:0/device:GPU:0'
bb.device # '/job:localhost/replica:0/task:0/device:CPU:0'
5.2 shape
c = tf.ones([200, 28, 28, 3])
c.shape # TensorShape([200, 28, 28, 3])
c.shape[0] # 200
5.3 ndim == tf.rank(t)
5.4 检查Tensor 的类型
尽量不要用内建的 isinstance
方法,使用 tf.is_tensor()
方法。
isinstance
a = tf.constant(1.)
isinstance(a, tf.Tensor) # True
tf.is_tensor
a = tf.constant(1.)
b = tf.constant([True, False])
c = tf.constant('hello world!')
d = np.arange(4)
tf.is_tensor(b) # True
tf.is_tensor(d) # False
a.dtype, b.dtype, c.dtype # (tf.float32, tf.bool, tf.string)
a.dtype == tf.float32 # Ture
5.5 类型变换
numpy2tensor
a = np.arange(5)
a.dtype # dtype('int32')
aa = tf.convert_to_tensor(a)
aa.dtype # tf.int32
tensor 间类型转换
bb = tf.cast(aa, tf.float32)
bb.dtype # tf.float32
cc = tf.cast(aa, tf.double)
cc.dtype # tf.float64
bool2int
b = tf.constant([0,1])
c = tf.cast(b, dtype=tf.bool)
c # <tf.Tensor: id=2687, shape=(2,), dtype=bool, numpy=array([False, True])>
d = tf.cast(c, dtype=tf.int32)
d # <tf.Tensor: id=2810, shape=(2,), dtype=int32, numpy=array([0, 1])>
Tensor2numpy
a = tf.ones([])
a.numpy() # 1.0
int(a) # 1 # 只能对 scalar tensor 使用
b = tf.ones([1, 3])
b.numpy() # array([[1., 1., 1.]], dtype=float32)
6. Variable
a = tf.range(5)
b = tf.Variable(a)
b.dtype # tf.int32
b.name # 'Variable:0'
b = tf.Variable(a, name='input_data')
b.dtype # tf.int32
b.name # 'input_data:0'
b.trainable # True
isinstance(a, tf.Tensor) # 检查是否为当前类实例
Out[1]: True
isinstance(b, tf.Tensor)
Out[2]: False
isinstance(b, tf.Variable)
Out[3]: True
tf.is_tensor(b)
Out[4]: True
注意: 对 Variable 的类型检查时 用 tf.is_tensor 与 isinstance 的区别。