(tensorflow笔记)张量和常见函数

目录标题

  • 张量生成
    • 1.张量定义
    • 2.创建一个张量
      • tf.constant(张量内容,dtype=数据类型)
      • tf.convert_to_tensor(数据名,dtype=数据类型)
      • tf.zeros(维度) 、tf.ones(维度) 、tf.fill(维度,指定值)
      • tf.random.normal(维度,mean=均值,stddev=标准差)
      • tf.random.truncated_normal(维度,mean=均值,stddev=标准差)
      • tf.random.uniform(维度,minval=最小值,maxval=最大值)
  • 常见函数1
    • tf.cast(张量名,dtype=数据类型)
    • tf.reduce_min(张量名)、tf.reduce_max(张量名)
    • tf.reduce_mean(张量名,axis=操作轴)
    • tf.reduce_sum(张量名,axis=操作轴)
    • tf.Variable(初始值)
    • tensorflow中的数学运算
      • 四则运算:
      • 平方、次方和开方:
      • 矩阵乘:
    • tf.data.Dataset.from_tensor_slices()
    • tf.GradientTape()
    • enumerate()
    • tf.one_hot()
    • tf.nn.softmax()
    • assign_sub()
    • tf.argmax()
  • 常见函数2
    • tf.where()
    • np.random.RandomState.rand()
    • np.vstack()
    • np.mgrid[]、.ravel()、np.c_[]

张量生成

1.张量定义

张量(tensor):多维数组(列表)。张量的维数叫做阶,判断张量是几阶的,就看方括号的个数有几个。
0阶张量叫做标量,表示一个单独的数
1阶张量叫做向量,表示一个一维数组
2阶张量叫做矩阵,表示一个二维数组
张量可以表示0阶到n阶的数组
(tensorflow笔记)张量和常见函数_第1张图片

2.创建一个张量

tf.constant(张量内容,dtype=数据类型)

创建一个1阶张量,里面有两个元素1。

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

张量的形状(shape),看shape的括号中有逗号隔开了几个数字,这里隔开了一个数字,说明是一维张量,这个数字为2,说明这个张量里有两个元素

tf.convert_to_tensor(数据名,dtype=数据类型)

将numpy的数据类型转换为tensor数据类型

a = np.arange(0, 5)
b = tf.convert_to_tensor(a, dtype=tf.int64)
print("a:", a)	#a: [0 1 2 3 4]
print("b:", b)	#b: tf.Tensor([0 1 2 3 4], shape=(5,), dtype=int64)

tf.zeros(维度) 、tf.ones(维度) 、tf.fill(维度,指定值)

tf.zeros(维度):创建全为0的张量
tf.ones(维度):创建全为1的张量
tf.fill(维度,指定值):创建全为指定值的张量
关于维度:
一维:直接写个数
二维:用[行,列]
多为:用[n , m , j , k , … ]

a = tf.zeros([2, 3])	#二维,2行3列
b = tf.ones(4)		#一维,4个元素
c = tf.fill([2, 2], 9)	
print("a:", a)
print("b:", b)
print("c:", c)

a: tf.Tensor(
[[0. 0. 0.]
 [0. 0. 0.]], shape=(2, 3), dtype=float32)
b: tf.Tensor([1. 1. 1. 1.], shape=(4,), dtype=float32)
c: tf.Tensor(
[[9 9]
 [9 9]], shape=(2, 2), dtype=int32)

tf.random.normal(维度,mean=均值,stddev=标准差)

生成正态分布的随机数,默认均值为0,标准差为1。这种用的多,常常需要随机生成初始化参数

d = tf.random.normal([2, 2], mean=0.5, stddev=1)
print("d:", d)
d: tf.Tensor(
[[-0.723891   1.1346488]
 [ 1.4194794 -0.5963521]], shape=(2, 2), dtype=float32)

tf.random.truncated_normal(维度,mean=均值,stddev=标准差)

希望生成的随机数更集中一些,此函数可以保证生成的随机数在μ ± 2σ之内,其中μ为均值,σ为标准差

e = tf.random.truncated_normal([2, 2], mean=0.5, stddev=1)	#相对于上面,这里生成的随机数更向0.5集中
print("e:", e)
e: tf.Tensor(
[[-1.309091   0.8296644]
 [ 0.991609   1.3771394]], shape=(2, 2), dtype=float32)

tf.random.uniform(维度,minval=最小值,maxval=最大值)

生成指定维度的,均匀分布的随机数,minval指定随机数的最小值,maxval指定随机数的最大值,注意是前闭后开区间

f = tf.random.uniform([2, 2], minval=0, maxval=1)
print("f:", f)
f: tf.Tensor(
[[0.76728106 0.69621456]
 [0.9056256  0.99485946]], shape=(2, 2), dtype=float32)

常见函数1

tf.cast(张量名,dtype=数据类型)

强制tensor转换为该数据类型

import tensorflow as tf

x1 = tf.constant([1., 2., 3.], dtype=tf.float64)
print("x1:", x1)	#x1: tf.Tensor([1. 2. 3.], shape=(3,), dtype=float64)
x2 = tf.cast(x1, tf.int32)
print("x2:", x2)	#x2: tf.Tensor([1 2 3], shape=(3,), dtype=int32)

tf.reduce_min(张量名)、tf.reduce_max(张量名)

计算张量维度上元素的最小值和最大值

#接着上面的x2
print("minimum of x2:", tf.reduce_min(x2))	#minimum of x2: tf.Tensor(1, shape=(), dtype=int32)
print("maxmum of x2:", tf.reduce_max(x2))	#maxmum of x2: tf.Tensor(3, shape=(), dtype=int32)

关于axis
不解释,因为解释不清,就记住axis=1对列进行操纵,axis=0对行进行操作

tf.reduce_mean(张量名,axis=操作轴)

tf.reduce_sum(张量名,axis=操作轴)

x = tf.constant([[1, 2, 3], [2, 2, 3]])
print("x:", x)
print("mean of x:", tf.reduce_mean(x))  # 求x中所有数的均值
print("sum of x:", tf.reduce_sum(x, axis=1))  # 求每一行的和

x: tf.Tensor(
[[1 2 3]
 [2 2 3]], shape=(2, 3), dtype=int32)
mean of x: tf.Tensor(2, shape=(), dtype=int32)
sum of x: tf.Tensor([6 7], shape=(2,), dtype=int32)

tf.Variable(初始值)

tf.Variable()将变量标记为“可训练”,被标记的变量会在反向传播中记录梯度信息。神经网络训练中,常用该函数标记带训练参数

w = tf.Variable(tf.random.normal([2,2] , mean=0 , stddev=1))
print(w)
<tf.Variable 'Variable:0' shape=(2, 2) dtype=float32, numpy=
array([[-0.14149614, -0.07182086],
       [-0.5841409 ,  1.3798182 ]], dtype=float32)>

tensorflow中的数学运算

对应元素的四则运算:tf.add , tf.subtract , tf.multiply , tf.divide 注意,只有维度相同的张量才可以做四则运算。
平方、次方和开方:tf,square , tf.pow , tf.sqrt
矩阵乘:tf.matmul

四则运算:

a = tf.ones([1, 3])
b = tf.fill([1, 3], 3.)
print("a:", a)
print("b:", b)
print("a+b:", tf.add(a, b))			#实现两个张量的对应元素相加
print("a-b:", tf.subtract(a, b))	#实现两个张量的对应元素相减
print("a*b:", tf.multiply(a, b))	#实现两个张量的对应元素相乘
print("b/a:", tf.divide(b, a))		#实现两个张量的对应元素相除

a: tf.Tensor([[1. 1. 1.]], shape=(1, 3), dtype=float32)
b: tf.Tensor([[3. 3. 3.]], shape=(1, 3), dtype=float32)
a+b: tf.Tensor([[4. 4. 4.]], shape=(1, 3), dtype=float32)
a-b: tf.Tensor([[-2. -2. -2.]], shape=(1, 3), dtype=float32)
a*b: tf.Tensor([[3. 3. 3.]], shape=(1, 3), dtype=float32)
b/a: tf.Tensor([[3. 3. 3.]], shape=(1, 3), dtype=float32)

平方、次方和开方:

a = tf.fill([1, 2], 3.)
print("a:", a)
print("a的3次方:", tf.pow(a, 3))
print("a的平方:", tf.square(a))
print("a的开方:", tf.sqrt(a))

a: tf.Tensor([[3. 3.]], shape=(1, 2), dtype=float32)
a的3次方: tf.Tensor([[27. 27.]], shape=(1, 2), dtype=float32)
a的平方: tf.Tensor([[9. 9.]], shape=(1, 2), dtype=float32)
a的开方: tf.Tensor([[1.7320508 1.7320508]], shape=(1, 2), dtype=float32)

矩阵乘:

import tensorflow as tf

a = tf.ones([3, 2])
b = tf.fill([2, 3], 3.)
print("a:", a)
print("b:", b)
print("a*b:", tf.matmul(a, b))
a: tf.Tensor(
[[1. 1.]
 [1. 1.]
 [1. 1.]], shape=(3, 2), dtype=float32)
b: tf.Tensor(
[[3. 3. 3.]
 [3. 3. 3.]], shape=(2, 3), dtype=float32)
 a*b: tf.Tensor(
[[6. 6. 6.]
 [6. 6. 6.]
 [6. 6. 6.]], shape=(3, 3), dtype=float32)

tf.data.Dataset.from_tensor_slices()

切分传入张量的第一维度,生成输入特征/标签对,构建数据集
data = tf.data.Dataset.from_tensor_slices((输入特征,标签))
神经网络在训练时,是把输入特征和标签配对后喂入网络的。tensorflow给出了把特征和标签配对的函数from_tensor_slices(),此函数对numpy和tensor格式都适用。

features = tf.constant([12, 23, 10, 17])
labels = tf.constant([0, 1, 1, 0])
dataset = tf.data.Dataset.from_tensor_slices((features, labels))
for element in dataset:
    print(element)

(<tf.Tensor: shape=(), dtype=int32, numpy=12>, <tf.Tensor: shape=(), dtype=int32, numpy=0>)
(<tf.Tensor: shape=(), dtype=int32, numpy=23>, <tf.Tensor: shape=(), dtype=int32, numpy=1>)
(<tf.Tensor: shape=(), dtype=int32, numpy=10>, <tf.Tensor: shape=(), dtype=int32, numpy=1>)
(<tf.Tensor: shape=(), dtype=int32, numpy=17>, <tf.Tensor: shape=(), dtype=int32, numpy=0>)

tf.GradientTape()

在with结构中,使用tf.GradientTape()实现某个函数对指定参数的求导运算,配合variable函数,可实现损失函数loss对参数w的求导数运算

with tf.GradientTape() as tape : 
	若干个计算过程
grad = tape.gradient(函数,对谁求导)
with tf.GradientTape() as tape:
    x = tf.Variable(tf.constant(3.0))
    y = tf.pow(x, 2)
grad = tape.gradient(y, x)
print(grad)	#tf.Tensor(6.0, shape=(), dtype=float32)

enumerate()

enumerate是枚举的意思,它是python的内建函数,可枚举出每一个元素(如列表、元组或字符串),并在元素前配上对应的索引号,组合为索引元素,常在for循环中使用

seq = ['one', 'two', 'three']
for i, element in enumerate(seq):
    print(i, element)
0 one
1 two
2 three

tf.one_hot()

tf.one_hot()函数将待转换数据,转换为one-hot形式的数据输出
tf.one_hot(待转换数据,depth=几分类)
独热编码(one-hot encoding):在实现分类问题时,常常用独热码表示标签,标记类别:1表示是,0表示非
(tensorflow笔记)张量和常见函数_第2张图片
这样可以表示每个分类的概率,也就是百分之0的可能是狗尾草鸢尾和弗吉尼亚鸢尾,百分之百的可能是杂色鸢尾

classes = 3
labels = tf.constant([1, 0, 2])  # 输入的元素值最小为0,最大为2
output = tf.one_hot(labels, depth=classes)
print("result of labels1:", output)
result of labels1: tf.Tensor(
[[0. 1. 0.]
 [1. 0. 0.]
 [0. 0. 1.]], shape=(3, 3), dtype=float32)

再看一例

#这是y_train
[1 1 1 0 0 2 2 2 1 0 0 2 0 1 0 1 0 1 2 2 1 0 0 0 0 1 1 1 0 2 0 2 1 2 2 2 0
 2 2 1 0 2 2 2 2 0 0 0 0 0 0 0 0 0 1 2 2 1 1 0 0 1 0 1 1 1 2 0 0 0 2 0 1 0
 1 1 2 2 2 2 2 0 1 1 2 0 1 1 0 2 2 2 1 1 2 2 2 1 2 2 0 1 1 2 2 2 1 2 1 0 2
 2 2 2 2 0 1 0 1 2]

#这是独热码形式
 tf.Tensor(
[[0. 1. 0.]
 [0. 1. 0.]
 [0. 1. 0.]

	...

 [1. 0. 0.]
 [0. 1. 0.]
 [0. 0. 1.]], shape=(120, 3), dtype=float32)

tf.nn.softmax()

对于分类问题,神经网络完成前向传播,计算出了每种类型的可能性大小,1.01,2.01,-0.66,这些数字只有符合概率分布后,才可以与独热码的标签作比较,于是我们使用这个公式,使输出符合概率分布,结果是0.256,0.695,0.048,它们的和为1。tensorflow中可以使用softmax函数实现此公式的计算,softmax函数可以使n分类的n个输出通过softmax函数,便符合概率分布了
(tensorflow笔记)张量和常见函数_第3张图片

import tensorflow as tf

y = tf.constant([1.01, 2.01, -0.66])
y_pro = tf.nn.softmax(y)
print("After softmax, y_pro is:", y_pro)  # y_pro 符合概率分布
print("The sum of y_pro:", tf.reduce_sum(y_pro))  # 通过softmax后,所有概率加起来和为1

After softmax, y_pro is: tf.Tensor([0.25598174 0.69583046 0.0481878 ], shape=(3,), dtype=float32)
The sum of y_pro: tf.Tensor(1.0, shape=(), dtype=float32)

assign_sub()

w.assign_sub(w要自减的内容)
assign_sub函数用于参数的自更新,等待自更新的参数w要先被指定为可更新可训练,即Variable类型,才可以实现自更新

x = tf.Variable(4)
x.assign_sub(1)	#实现w = w-1的操作
print("x:", x)  # 4-1=3
x: <tf.Variable 'Variable:0' shape=() dtype=int32, numpy=3>

tf.argmax()

返回张量沿指定维度最大值的索引,注意是索引,不是值,值的话是tf.reduce_min()tf.reduce_max()这两个函数。tf.argmax(张量名,axis=操作轴)

test = np.array([[1, 2, 3], [2, 3, 4], [5, 4, 3], [8, 7, 2]])
print("test:\n", test)
print("每一列的最大值的索引:", tf.argmax(test, axis=0))  # 返回每一列最大值的索引
print("每一行的最大值的索引", tf.argmax(test, axis=1))  # 返回每一行最大值的索引

test:
[[1 2 3]
[2 3 4]
[5 4 3]
[8 7 2]]
每一列的最大值的索引: tf.Tensor([3 3 1], shape=(3,), dtype=int64)
每一行的最大值的索引 tf.Tensor([2 2 0 0], shape=(4,), dtype=int64)

常见函数2

tf.where()

tf.where(条件语句,真返回A,假返回B)条件语句真返回A,条件语句假返回B

a = tf.constant([1, 2, 3, 1, 1])
b = tf.constant([0, 1, 3, 4, 5])
c = tf.where(tf.greater(a, b), a, b)  # 若a>b,返回a对应位置的元素,否则返回b对应位置的元素
print("c:", c)
c: tf.Tensor([1 2 3 4 5], shape=(5,), dtype=int32)

np.random.RandomState.rand()

返回一个[0,1)之间的随机数
np.random.RandomState.rand(维度) #维度为空,返回标量

rdm = np.random.RandomState(seed=1)
a = rdm.rand()	#返回一个随机标量
b = rdm.rand(2, 3)	#返回维度为2行3列随机数矩阵
print("a:", a)	#a: 0.417022004702574
print("b:", b)	#b: [[7.20324493e-01 1.14374817e-04 3.02332573e-01]
 				#    [1.46755891e-01 9.23385948e-02 1.86260211e-01]]

np.vstack()

将两个数组按垂直方向叠加
np.vstack(数组1,数组2)

a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
c = np.vstack((a, b))
print("c:\n", c)
c:
 [[1 2 3]
 [4 5 6]]

np.mgrid[]、.ravel()、np.c_[]

这三个函数一起经常一起使用,生成网格点
np.mgrid[]

np.mgrid[起始值:结束值:步长,起始值:结束值:步长,...]

返回若干组维度相同的等差数组,每一组在[]里写起始值、结束值和步长,多组起始值、结束值和步长中间用逗号隔开,起始值和结束值是前闭后开区间,即[起始值,结束值),
.ravel()

x.ravel()

将x(多维数组)变成一维数组,相当于将“.”前的变量给拉直了
np.c_[]

np.c_[数组1,数组2...]

使返回的间隔数值点配对,即将[]里的数组配对后输出

# 生成等间隔数值点,为了保持两个返回值的维度相同,都是两行四列。
#至于为什么是2行4列,x是第一维,会沿着第二维的方向扩展,y则会沿着第一维的方向扩展,遵循numpy的广播机制。或者直接记,第一个数组x的取值为1,2,只有两个,所以是2行,第二个数组y的取值为2,2.5,3,3.5,有4个,所以是4列
x, y = np.mgrid[1:3:1, 2:4:0.5]
# 将x, y拉直,并合并配对为二维张量,生成二维坐标点
grid = np.c_[x.ravel(), y.ravel()]
print("x:\n", x)
x:
 [[1. 1. 1. 1.]
  [2. 2. 2. 2.]]
print("y:\n", y)
y:
 [[2.  2.5   3.  3.5]
  [2.  2.5   3.  3.5]]
print("x.ravel():\n", x.ravel())
x.ravel():
 [1. 1. 1. 1. 2. 2. 2. 2.]
print("y.ravel():\n", y.ravel())
y.ravel():
 [2.  2.5 3.  3.5 2.  2.5 3.  3.5]
print('grid:\n', grid)
grid:
 [[1.  2. ]
  [1.  2.5]
  [1.  3. ]
  [1.  3.5]
  [2.  2. ]
  [2.  2.5]
  [2.  3. ]
  [2.  3.5]]

你可能感兴趣的:(tensorflow,深度学习,python,tensorflow,深度学习,神经网络)