TensorFlow学习笔记1(TensorFlow数据类型)
import tensorflow as tf
import numpy as np
TensorFlow数据类型
python里面有类型:list, np.array, tf.Tensor
list是python自带的类型,可以存储不同类型的data,但是整体不够高效;
np.array包含在numpy库里面,方便数据计算,但是不支持求导;
Tensor是tensorflow里面的类型,可以进行快速计算和求梯度等,tensor是基于向量和矩阵的推广,可以将标量视为0阶张量,向量视为1阶张量,矩阵视为2阶张量。
tensor的数据可以分为以下类型:int, float, double, bool, string
1.1 如何进行创建?
- 创建一个整型的tensor:
tf.constant(1)
- 创建一个浮点型的tensor:
tf.constant(1.)
- 创建一个bool型的tensor:
tf.constant([True, False])
- 创建一个string型的tensor:
tf.constant('hello, world.')
- 创建一个双精度浮点型的tensor:
tf.constant(2., dtype=tf.double)
1.2 Tensor的属性
tensor一般存储在GPU当中,numpy的变量一般存储在CPU当中,有些时候需要将得到的数据进行转换才能进一步进行计算。
#分别在cpu和gpu中创建两个tensor,默认是在gpu中创建
with tf.device("cpu"):
a = tf.constant([1])
with tf.device("gpu"):
b = tf.range(4)
#查看变量是存储在gpu还是cpu中
a.device
b.device
#相互转换
aa=a.gpu()
aa.device #将cpu中的变量a转换为cpu中的aa, 然后查看
bb=b.cpu()
bb.device
gpu上面的操作只能在gpu上面操作,cpu上面的操作只能在cpu上面操作
#将tensor转换为numpy中的数据类型
b.numpy()
#查看数据维度(这两者有区别吗?)
b.ndim #shape属性的长度(length)也是它的ndim.
tf.rank(b) #张量的秩与矩阵的秩不一样.张量的秩是唯一选择张量的每个元素所需的索引的数量.秩也被称为 “order”,“degree” 或 “ndims”.
tf.rank(tf.ones([3,4,2]))
1.3 查看数据类型
a=tf.constant([1.])
b=tf.constant([True, False])
c=tf.constant('hello, world.')
d=np.arange(4)
#判断是否是一个Tensor
isinstance(a, tf.Tensor) #在一种情况会失效,后面会提到
tf.is_tensor(b)
a.dtype, b.dtype, c.dtype
a.dtype==tf.float32
c.dtype==tf.string
1.4 数据类型转化
- 转换数据类型, 将一个numpy转换为一个tensor, 可以用这种方式创建一个tensor
a=np.arange(5)
a.dtype #默认生成int64
aa=tf.convert_to_tensor(a)
aa=tf.convert_to_tensor(a, dtype=tf.int32)
tf.cast(aa, dtype=tf.float32)
aaa=tf.cast(aa, dtype=tf.double)
tf.cast(aaa, dtype=tf.int32) #tf.cast和tf.convert_to_tensor区别?tf.convert_to_tensor是将numpy转化为tensor,
#tf.cast是转换tensor的dtype
- bool型和int型相互转换:
b=tf.constant([0,1])
tf.cast(b, dtype=tf.bool)
bb=tf.cast(b,dtype=tf.bool)
tf.cast(bb, tf.int32)
- tf.Variable是tensorflow中特有的数据类型,表示在训练神经网络时可以优化的参数,也就是不断求梯度进行迭代的变量。将一般的tensor进行转化为tf.Variable之后,具有了两个属性:trainable和name。
a=tf.range(5)
b=tf.Variable(a)
b.dtype
b.name
b=tf.Variable(a, name='input_data') #可对tf.Variable重命名
b.name
b.trainable
isinstance(b, tr.Tensor) #此时函数失效,返回false
isinstance(b, tr.Variable) #True
tf.is_tensor(b) #True
- 转换为numpy数据:
a.numpy()
b.numpy()
a=tf.ones([])
a.numpy() #将tensor转换为numpy
int(a) #具有相同的功效,更常用
float(a)