Tensorflow基础
一,数据类型
1.1 数值类型
1.标量:维度为0,shape为[ ]
import tensorflow as tf
a=1.2 #python语言创建标量
b=tf.constant(1.2) #TF方式创建标量
2.向量:维度为1,长度不定,shape为[n](类似一维数组)
c=tf.constant([1.2,2.2])
3.矩阵:n行m列实数的有序集合,维度为2,长度不定,shape为[n,m](类似二维数组)
d=tf.constant([[1,2],[3,4]])
4.张量:所有维度数大于2的数组称为张量,例如:[2,32,32,3]
e=tf.constant([[[1,2],[3,4]],[[5,6],[7,8]]])
注:要使用Tensoflow提供的功能函数,需通过Tensorflow规定的方式去创建张量,而不能用python语言的标准变量的创建方式
1.2 字符串类型
str=tf.constant("hello tensorflow")
lower=tf.strings.lower(str) #小写化
len=tf.strings.length(str) #长度
1.3 布尔类型
a=tf.constant(True)
b=tf.constant([True,False])
print(a is True)
print(a==True)
注:Tensorflow的布尔型与Python的布尔型并不等价,不能通用。
二,数值精度
常用精度:tf.int32,tf.in64,tf.int16,tf.float16,tf.float32,.tf.float64等
通过tf.cast进行类型转换
import tensorflow as tf
import numpy as np
a=tf.constant(np.pi,dtype=tf.float16)
a=tf.cast(a,tf.double)
三,待优化张量
对于计算过程中需要优化的张量,例如:网络层的W和b
利用tf.Variable()将普通张量转换为待优化张量(含有name:用于命名计算图中的变量,trainable:表示当前属性是否需要优化)
四,创建张量
1.从数组,列表对象创建:利用tf.convert_to_tensor()
import tensorflow as tf
import numpy as np
a=[1.2,2]
a=tf.convert_to_tensor(a)
b=tf.convert_to_tensor(np.array([[1,2],[3,4]]))
2.创建全0或全1张量
c=tf.zeros([2,2])
d=tf.ones(3,3)
#与某个张量shape一致
f=tf.zeros_like(c)
h=tf.ones_like(d)
3.创建自定义数值张量:tf.fill(shape,value)
h=tf.fill([2,3],-1)
4.创建已知分布的张量
正态分布:tf.random.normal(shape,mean,stddev) mean:均值 stddev:标准差
均值分布:tf.random.uniform(shape,minval,maxval,dtype=tf.float32) 创建采样自[minval,maxval)区间的均匀分布的张量
m=tf.random.normal([3,4],mean=2,stddev=0.5)
n=tf.random.uniform([3,3],minval=2,maxval=6,dtype=tf.float64)
5.创建序列 :tf.range(limit,delta):创建[0,limit)步长为delta的整数序列
k=tf.range(10,delta=2)
五,维度变换:tf.reshape()
m=tf.random.normal([4,32,32,3])
k=tf.reshape(m,[4,1024,3])
增加维度:tf.expand_dims(x,axis)在指定的axis轴前插入一个新的维度
删除维度:tf.squeeze(x,axis)axis为待删除的维度的索引号
交换维度:tf.transpose(x,perm) perm表示新维度顺序的List
m=tf.random.normal([4,32,32,3])#索引[0,1,2,3] 将高和宽维度互换
tf.transpose(m,perm=[0,2,1,3])