1、tensor的数据类型



1、数据载体

 ① list : list中可以添加多种数据,[1,1.2,‘hello’,(1,2)]
 ② np.array:np数组主要用于解决同种数据的运算,不支持自动求导,不支持GPU运算
 ③ tf.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: 𝑟𝑎𝑛𝑘 > 2

2、TF是一个计算库,跟np非常接近,主要有以下数据类型和属性

(1) int ,float, double,bool,string

 1 #int整型
 2 a = tf.constant(1)  3 print("int型a: ",a)  4 
 5 #float型
 6 b = tf.constant(1.0)  7 print("float型b:",b)  8 
 9 #double型
10 c = tf.constant(1.0, dtype = tf.double)  #指定数据类型
11 print("double型c: ",c) 12 
13 #bool型
14 d = tf.constant([True,False]) 15 print("bool型:",d) 16 
17 #字符串型
18 e = tf.constant('hello,world!') 19 print("字符串型:",e)

输出:

int型a:  tf.Tensor(1, shape=(), dtype=int32) float型b: tf.Tensor(1.0, shape=(), dtype=float32) double型c: tf.Tensor(1.0, shape=(), dtype=float64) bool型: tf.Tensor([ True False], shape=(2,), dtype=bool) 字符串型: tf.Tensor(b'hello,world!', shape=(), dtype=string)

(2)tensor的属性

#新建两个tensor
1
with tf.device("cpu"): 2 a = tf.constant([1]) 3 4 with tf.device("gpu"): 5 b = tf.range(4)

属性主要有

 ① device,查看设备

print(a.device) print(b.device)

输出:

/job:localhost/replica:0/task:0/device:CPU:0 /job:localhost/replica:0/task:0/device:GPU:0

② gpu,cpu对tensor进行数据计算平台转换

1 aa = a.gpu() #a是cpu tensor,转换为gpu
2 print(aa.device) 3 
4 bb = b.cpu() #b是gpu tensor,转换为cpu
5 print(bb.device)

输出:

/job:localhost/replica:0/task:0/device:GPU:0 /job:localhost/replica:0/task:0/device:CPU:0

 ③ ndim,查看tensor的维度

1 d = a.ndim 2 print(d) #1

 ④tensor和numpy的转换tf.convert_to_tensor()和 tf.cast()(万能api)

 #
1
a = np.arange(5) 2 print(a) #[0 1 2 3 4] 3 print(a.dtype) # int32 4 5 aa = tf.convert_to_tensor(a, dtype = tf.float32) #将整型a抓换为浮点型tensoraa 6 print(aa) #tf.Tensor([0. 1. 2. 3. 4.], shape=(5,), dtype=float32) 7 8 bb = tf.cast(aa,dtype = tf.float64) 9 print(bb) # tf.Tensor([0. 1. 2. 3. 4.], shape=(5,), dtype=float64) 10 11 bbb = tf.cast(aa,dtype = tf.double) 12 print(bbb) # tf.Tensor([0. 1. 2. 3. 4.], shape=(5,), dtype=float64)

3、检查tensor的类型

(1)isinstance,is_tensor,dtype

1 a = tf.constant([1.]) 2 print(isinstance(a,tf.Tensor)) 3 print(tf.is_tensor(a)) 4 print(a.dtype)

输出:

True True <dtype: 'float32'>

4、tf.Variable,定义一个可以优化的参数,即变量

1 a = tf.Variable(5) 2 print(a) 3 print(a.dtype)

输出:

<tf.Variable 'Variable:0' shape=() dtype=int32, numpy=5>
<dtype: 'int32'>

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM