1.Tensor 张量:
纬度 | 阶 | 名字 | 例子 |
0-D | 0 | 标量 scale | s = 1 2 3 |
1-D | 1 | 向量 vector | v = [1, 2, 3] |
2-D | 2 | 矩阵 matrix | m = [ [1, 2, 3], [4, 5, 6], [7, 8, 9]] |
3-D | 3 | 张量 tensor | t = [ [ [ n个 ] ] ] |
1.1. tensorflow数据类型:
1. tf.int, tf.float
tf.int32, tf.float32, tf.float64
2. tf.bool
tf.constant([True, False])
3. tf.string
tf.constant("Hello world")
1.2. 如何创建一个张量:
import tensorflow as tf
a = tf.constant([1, 5], dtype=tf.int64)
print(a)
print(a.dtype)
print(a.shape)
输出:
tf.Tensor([1 5], shape=(2,), dtype=int64)
<dtype: 'int64'>
(2,)
1.3. 如何把numpy变为tensor:
import tensorflow as tf
import numpy as np
a = np.arange(0, 5)
b = tf.convert_to_tensor( a, dtype=tf.int64)
print(a)
print(b)
输出:
[0 1 2 3 4]
tf.Tensor([0 1 2 3 4], shape=(5,), dtype=int64)
通过convert_to_tensor把numpy数据类型转化为tensor类型。
1.4. 创建一些简单多维的张量:
a.创建全为0的张量:
import tensorflow as tf
a = tf.zeros([2, 3])
print(a)
输出:
tf.Tensor(
[[0. 0. 0.]
[0. 0. 0.]], shape=(2, 3), dtype=float32)
b.创建全为1的张量:
import tensorflow as tf
a = tf.ones([2, 3])
print(a)
输出:
tf.Tensor(
[[1. 1. 1.]
[1. 1. 1.]], shape=(2, 3), dtype=float32)
c.创建为指定项的张量:
import tensorflow as tf
a = tf.fill([2, 3], 9)
print(a)
输出:
tf.Tensor(
[[9 9 9]
[9 9 9]], shape=(2, 3), dtype=int32)
1.5. 创建随机数的张量:
正态分布随机数:
import tensorflow as tf
a = tf.random.normal([2, 2], mean=0.5, stddev=1)
print(a)
输出:
tf.Tensor(
[[0.37068003 1.455114 ]
[1.6106157 1.4800272 ]], shape=(2, 2), dtype=float32)
截断式正态分布随机数:
import tensorflow as tf
a = tf.random.truncated_normal([2, 2], mean=0.5, stddev=1)
print(a)
输出:
tf.Tensor(
[[2.363211 0.97205293]
[1.7942774 1.2452044 ]], shape=(2, 2), dtype=float32)
均匀分布随机数:
import tensorflow as tf
a = tf.random.uniform([2,2], minval=0, maxval=1 )
print(a)
输出:
tf.Tensor(
[[0.49529576 0.77657926]
[0.01204515 0.41324592]], shape=(2, 2), dtype=float32)
2.Tensor常用函数:
2.1. 强转类型:
tf.cast(张量名,dtype=数据类型)强制转换数据类型
tf.reduce_min(张量名)得到张量中的最小值
tf.reduce_max(张量名)得到张量中的最大值
import tensorflow as tf
x1 = tf.constant([1, 2, 3], dtype=tf.float64)
print(x1)
x2 = tf.cast(x1, dtype=tf.int64)
print(x2)
print(tf.reduce_min(x2),
tf.reduce_max(x2))
输出:
tf.Tensor([1. 2. 3.], shape=(3,), dtype=float64)
tf.Tensor([1 2 3], shape=(3,), dtype=int64)
tf.Tensor(1, shape=(), dtype=int64) tf.Tensor(3, shape=(), dtype=int64)
2.2. axis理解:
在矩阵中,列为axis=0 即纬度,而行为axis=1 即经度。
import tensorflow as tf
x1 = tf.constant([[1, 2, 3], [2, 2, 3]])
print(x1)
print(tf.reduce_mean(x1))
print(tf.reduce_sum(x1, axis=1))
输出:
tf.Tensor(
[[1 2 3]
[2 2 3]], shape=(2, 3), dtype=int32)
tf.Tensor(2, shape=(), dtype=int32)
tf.Tensor([6 7], shape=(2,), dtype=int32)
tf.reduce_mean(张量名, axis=维度):求维度中的张量的平均值,如果没有维度就是求全部
tf.reduce_sum(张量名, axis=维度):同理,求的是和
2.3. 标记可训练:
tf.Variable(初始值)
它是将变量标记为“可训练”,被标记的变量会在反向传播中被标记,在神经网络训练中,经常被用于标记待训练参数。
例如: w = tf.Variable(tf.random.normal([2, 2], mean=0, stddev=1)
2.4. 对应元素的四则运算:
只有维度相同的张量才可以进行四则运算。
a.实现两个张量的元素相加:
tf.add(张量1,张量2)
b.实现两个张量的元素相减:
tf.subtract(张量1,张量2)
c.实现两个张量的元素相乘:
tf.multiply(张量1,张量2)
d.实现两个张量的元素相除:
tf.divide(张量1, 张量2)
import tensorflow as tf
a = tf.ones([1, 3], dtype=tf.int32)
b = tf.fill([1, 3], 3)
print(a)
print(b)
print(tf.add(a, b))
print(tf.subtract(a, b))
print(tf.multiply(a, b))
print(tf.divide(a, b))
输出:
tf.Tensor([[1 1 1]], shape=(1, 3), dtype=int32)
tf.Tensor([[3 3 3]], shape=(1, 3), dtype=int32)
tf.Tensor([[4 4 4]], shape=(1, 3), dtype=int32)
tf.Tensor([[-2 -2 -2]], shape=(1, 3), dtype=int32)
tf.Tensor([[3 3 3]], shape=(1, 3), dtype=int32)
tf.Tensor([[0.33333333 0.33333333 0.33333333]], shape=(1, 3), dtype=float64)
2.5. 平方、次方和开方:
tf.square(张量名)求张量的平方
tf.pow(张量名,n次方) 求张量的n次方
tf.sqrt(张量名)求张量的开方
import tensorflow as tf
a = tf.fill([1, 2], 4.)
print(a)
print(tf.square(a))
print(tf.pow(a, 3))
print(tf.sqrt(a))
输出:
tf.Tensor([[4. 4.]], shape=(1, 2), dtype=float32)
tf.Tensor([[16. 16.]], shape=(1, 2), dtype=float32)
tf.Tensor([[64. 64.]], shape=(1, 2), dtype=float32)
tf.Tensor([[2. 2.]], shape=(1, 2), dtype=float32)
2.6. 张量的矩阵乘:
tf.matmul(矩阵1,矩阵2)
import tensorflow as tf
a = tf.ones([3, 2])
b = tf.fill([2, 3], 3.)
print(tf.matmul(a, b))
输出:
tf.Tensor(
[[6. 6. 6.]
[6. 6. 6.]
[6. 6. 6.]], shape=(3, 3), dtype=float32)
2.7. 对张量进行分配:
tf.data.Dataset.from_tensor_slices((输入特征, 标签))
无论是numpy和tensor都可以
import tensorflow as tf
feature = tf.constant([12, 23, 10,17])
labels = tf.constant([0, 1, 1, 0])
dataset = tf.data.Dataset.from_tensor_slices((feature, labels))
print(dataset)
for element in dataset:
print(element)
输出:
<_TensorSliceDataset element_spec=(TensorSpec(shape=(), dtype=tf.int32, name=None), TensorSpec(shape=(), dtype=tf.int32, name=None))>
(<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>)
2.8. 张量梯度计算:
tf.GradientTape 用于计算梯度
写法:
with tf.GradientTape as tape: 若干个计算过程 grad = tape.gradient(函数, 对谁求导)
import tensorflow as tf
with tf.GradientTape() as tape:
w = tf.Variable(tf.constant(3.0))
loss = tf.pow(w, 2)
grad = tape.gradient(loss, w)
print(grad)
输出:
tf.Tensor(6.0, shape=(), dtype=float32)
2.9. 遍历函数:
enumerate 是python的内置函数,它可遍历每个元素,组合:索引,元素,常在for循环中使用。
seq = ['one', 'two', 'three']
for i, element in enumerate(seq):
print(i, element)
输出:
0 one
1 two
2 three
2.10. 独热编码:
tf.one_hot,常用做标签:1表示是,0表示否
比如:猫 1, 狗 2, 羊 3
标签:2
独热码:(0 , 1, 0)
tf.one_hot()将待转换数据,转换为one-hot形式输出。
tf.one_hot(待转数据, depth=几分类)
import tensorflow as tf
classes = 3
labels = tf.constant([1, 0, 2])
output = tf.one_hot(labels, depth=classes)
print(output)
输出:
tf.Tensor(
[[0. 1. 0.]
[1. 0. 0.]
[0. 0. 1.]], shape=(3, 3), dtype=float32)
2.11. softmax概率分布:
tf.nn.softmax
当n分类的n个输出(y0, y1,....., yn-1),通过softmax函数,便得到了符合概率分布了。
且
把数字大小变为概率大小,且概率之和为1。
import tensorflow as tf
y = tf.constant([1.01, 2.01, -0.66])
pro_y = tf.nn.softmax(y)
print("After softmax,pro_y is", pro_y)
输出:
After softmax,pro_y is tf.Tensor([0.25598174 0.69583046 0.04818781], shape=(3,), dtype=float32)
2.12. 更新减法:
assign_sub:
1.赋值操作,更新参数的值并返回
2.在调用assign_sub,之前需要tf.Variable定义变量w为可训练(自动更新)
import tensorflow as tf
w = tf.Variable(4)
w.assign_sub(1)
print(w)
输出:
<tf.Variable 'Variable:0' shape=() dtype=int32, numpy=3>
2.13. 寻找同维度中最大值索引:
tf.argmax(张量名,axis=操作轴)
import tensorflow as tf
import numpy as np
w = np.array([[1, 2, 3], [2, 3, 4], [5, 4, 3], [8, 7, 2]])
print(w)
print(tf.argmax(w, axis=1))
print(tf.argmax(w, axis=0))
输出:
[[1 2 3]
[2 3 4]
[5 4 3]
[8 7 2]]
tf.Tensor([2 2 0 0], shape=(4,), dtype=int64)
tf.Tensor([3 3 1], shape=(3,), dtype=int64)
3.鸢尾花分类:
预备操作:导包
# 导入所需模块
import tensorflow as tf
from sklearn import datasets
from matplotlib import pyplot as plt
import numpy as np
第一步获取数据:使用了sklearn中提供的数据集
# 导入数据,分别为输入特征和标签
x_data = datasets.load_iris().data
y_data = datasets.load_iris().target
第二步数据乱序处理:
# 随机打乱数据(因为原始数据是顺序的,顺序不打乱会影响准确率)
# seed: 随机数种子,是一个整数,当设置之后,每次生成的随机数都一样(为方便教学,以保每位同学结果一致)
np.random.seed(116) # 使用相同的seed,保证输入特征和标签一一对应
np.random.shuffle(x_data)
np.random.seed(116)
np.random.shuffle(y_data)
tf.random.set_seed(116)
第三步对数据进行分类:分为训练集和测试集,并对数据集的数据类型进行修改,方便后面的矩阵相乘。
# 将打乱后的数据集分割为训练集和测试集,训练集为前120行,测试集为后30行
x_train = x_data[:-30]
y_train = y_data[:-30]
x_test = x_data[-30:]
y_test = y_data[-30:]
# 转换x的数据类型,否则后面矩阵相乘时会因数据类型不一致报错
x_train = tf.cast(x_train, tf.float32)
x_test = tf.cast(x_test, tf.float32)
第四步组合:把标签和数据变为一个组合,并设置了batch,一个batch有32组。
# from_tensor_slices函数使输入特征和标签值一一对应。(把数据集分批次,每个批次batch组数据)
train_db = tf.data.Dataset.from_tensor_slices((x_train, y_train)).batch(32)
test_db = tf.data.Dataset.from_tensor_slices((x_test, y_test)).batch(32)
第五步设置参数:设置一系列的参数。
# 生成神经网络的参数,4个输入特征故,输入层为4个输入节点;因为3分类,故输出层为3个神经元
# 用tf.Variable()标记参数可训练
# 使用seed使每次生成的随机数相同(方便教学,使大家结果都一致,在现实使用时不写seed)
w1 = tf.Variable(tf.random.truncated_normal([4, 3], stddev=0.1, seed=1))
b1 = tf.Variable(tf.random.truncated_normal([3], stddev=0.1, seed=1))
lr = 0.1 # 学习率为0.1
train_loss_results = [] # 将每轮的loss记录在此列表中,为后续画loss曲线提供数据
test_acc = [] # 将每轮的acc记录在此列表中,为后续画acc曲线提供数据
epoch = 500 # 循环500轮
loss_all = 0 # 每轮分4个step,loss_all记录四个step生成的4个loss的和
第六步训练数据:对数据进行训练得到合适的数值。
# 训练部分
for epoch in range(epoch): #数据集级别的循环,每个epoch循环一次数据集
for step, (x_train, y_train) in enumerate(train_db): #batch级别的循环 ,每个step循环一个batch
with tf.GradientTape() as tape: # with结构记录梯度信息
y = tf.matmul(x_train, w1) + b1 # 神经网络乘加运算
y = tf.nn.softmax(y) # 使输出y符合概率分布(此操作后与独热码同量级,可相减求loss)
y_ = tf.one_hot(y_train, depth=3) # 将标签值转换为独热码格式,方便计算loss和accuracy
loss = tf.reduce_mean(tf.square(y_ - y)) # 采用均方误差损失函数mse = mean(sum(y-out)^2)
loss_all += loss.numpy() # 将每个step计算出的loss累加,为后续求loss平均值提供数据,这样计算的loss更准确
# 计算loss对各个参数的梯度
grads = tape.gradient(loss, [w1, b1])
# 实现梯度更新 w1 = w1 - lr * w1_grad b = b - lr * b_grad
w1.assign_sub(lr * grads[0]) # 参数w1自更新
b1.assign_sub(lr * grads[1]) # 参数b自更新
# 每个epoch,打印loss信息
print("Epoch {}, loss: {}".format(epoch, loss_all/4))
train_loss_results.append(loss_all / 4) # 将4个step的loss求平均记录在此变量中
loss_all = 0 # loss_all归零,为记录下一个epoch的loss做准备
第七步测试数据:检查数据的准确率以及loss率。
# 测试部分
# total_correct为预测对的样本个数, total_number为测试的总样本数,将这两个变量都初始化为0
total_correct, total_number = 0, 0
for x_test, y_test in test_db:
# 使用更新后的参数进行预测
y = tf.matmul(x_test, w1) + b1
y = tf.nn.softmax(y)
pred = tf.argmax(y, axis=1) # 返回y中最大值的索引,即预测的分类
# 将pred转换为y_test的数据类型
pred = tf.cast(pred, dtype=y_test.dtype)
# 若分类正确,则correct=1,否则为0,将bool型的结果转换为int型
correct = tf.cast(tf.equal(pred, y_test), dtype=tf.int32)
# 将每个batch的correct数加起来
correct = tf.reduce_sum(correct)
# 将所有batch中的correct数加起来
total_correct += int(correct)
# total_number为测试的总样本数,也就是x_test的行数,shape[0]返回变量的行数
total_number += x_test.shape[0]
# 总的准确率等于total_correct/total_number
acc = total_correct / total_number
test_acc.append(acc)
print("Test_acc:", acc)
第八步数据可视化:用matplotlib画图展示acc与loss。
# 绘制 loss 曲线
plt.title('Loss Function Curve') # 图片标题
plt.xlabel('Epoch') # x轴变量名称
plt.ylabel('Loss') # y轴变量名称
plt.plot(train_loss_results, label="$Loss$") # 逐点画出trian_loss_results值并连线,连线图标是Loss
plt.legend() # 画出曲线图标
plt.show() # 画出图像
# 绘制 Accuracy 曲线
plt.title('Acc Curve') # 图片标题
plt.xlabel('Epoch') # x轴变量名称
plt.ylabel('Acc') # y轴变量名称
plt.plot(test_acc, label="$Accuracy$") # 逐点画出test_acc值并连线,连线图标是Accuracy
plt.legend()
plt.show()
完整代码:
# -*- coding: UTF-8 -*-
# 利用鸢尾花数据集,实现前向传播、反向传播,可视化loss曲线
# 导入所需模块
import tensorflow as tf
from sklearn import datasets
from matplotlib import pyplot as plt
import numpy as np
# 导入数据,分别为输入特征和标签
x_data = datasets.load_iris().data
y_data = datasets.load_iris().target
# 随机打乱数据(因为原始数据是顺序的,顺序不打乱会影响准确率)
# seed: 随机数种子,是一个整数,当设置之后,每次生成的随机数都一样(为方便教学,以保每位同学结果一致)
np.random.seed(116) # 使用相同的seed,保证输入特征和标签一一对应
np.random.shuffle(x_data)
np.random.seed(116)
np.random.shuffle(y_data)
tf.random.set_seed(116)
# 将打乱后的数据集分割为训练集和测试集,训练集为前120行,测试集为后30行
x_train = x_data[:-30]
y_train = y_data[:-30]
x_test = x_data[-30:]
y_test = y_data[-30:]
# 转换x的数据类型,否则后面矩阵相乘时会因数据类型不一致报错
x_train = tf.cast(x_train, tf.float32)
x_test = tf.cast(x_test, tf.float32)
# from_tensor_slices函数使输入特征和标签值一一对应。(把数据集分批次,每个批次batch组数据)
train_db = tf.data.Dataset.from_tensor_slices((x_train, y_train)).batch(32)
test_db = tf.data.Dataset.from_tensor_slices((x_test, y_test)).batch(32)
# 生成神经网络的参数,4个输入特征故,输入层为4个输入节点;因为3分类,故输出层为3个神经元
# 用tf.Variable()标记参数可训练
# 使用seed使每次生成的随机数相同(方便教学,使大家结果都一致,在现实使用时不写seed)
w1 = tf.Variable(tf.random.truncated_normal([4, 3], stddev=0.1, seed=1))
b1 = tf.Variable(tf.random.truncated_normal([3], stddev=0.1, seed=1))
lr = 0.1 # 学习率为0.1
train_loss_results = [] # 将每轮的loss记录在此列表中,为后续画loss曲线提供数据
test_acc = [] # 将每轮的acc记录在此列表中,为后续画acc曲线提供数据
epoch = 500 # 循环500轮
loss_all = 0 # 每轮分4个step,loss_all记录四个step生成的4个loss的和
# 训练部分
for epoch in range(epoch): #数据集级别的循环,每个epoch循环一次数据集
for step, (x_train, y_train) in enumerate(train_db): #batch级别的循环 ,每个step循环一个batch
with tf.GradientTape() as tape: # with结构记录梯度信息
y = tf.matmul(x_train, w1) + b1 # 神经网络乘加运算
y = tf.nn.softmax(y) # 使输出y符合概率分布(此操作后与独热码同量级,可相减求loss)
y_ = tf.one_hot(y_train, depth=3) # 将标签值转换为独热码格式,方便计算loss和accuracy
loss = tf.reduce_mean(tf.square(y_ - y)) # 采用均方误差损失函数mse = mean(sum(y-out)^2)
loss_all += loss.numpy() # 将每个step计算出的loss累加,为后续求loss平均值提供数据,这样计算的loss更准确
# 计算loss对各个参数的梯度
grads = tape.gradient(loss, [w1, b1])
# 实现梯度更新 w1 = w1 - lr * w1_grad b = b - lr * b_grad
w1.assign_sub(lr * grads[0]) # 参数w1自更新
b1.assign_sub(lr * grads[1]) # 参数b自更新
# 每个epoch,打印loss信息
print("Epoch {}, loss: {}".format(epoch, loss_all/4))
train_loss_results.append(loss_all / 4) # 将4个step的loss求平均记录在此变量中
loss_all = 0 # loss_all归零,为记录下一个epoch的loss做准备
# 测试部分
# total_correct为预测对的样本个数, total_number为测试的总样本数,将这两个变量都初始化为0
total_correct, total_number = 0, 0
for x_test, y_test in test_db:
# 使用更新后的参数进行预测
y = tf.matmul(x_test, w1) + b1
y = tf.nn.softmax(y)
pred = tf.argmax(y, axis=1) # 返回y中最大值的索引,即预测的分类
# 将pred转换为y_test的数据类型
pred = tf.cast(pred, dtype=y_test.dtype)
# 若分类正确,则correct=1,否则为0,将bool型的结果转换为int型
correct = tf.cast(tf.equal(pred, y_test), dtype=tf.int32)
# 将每个batch的correct数加起来
correct = tf.reduce_sum(correct)
# 将所有batch中的correct数加起来
total_correct += int(correct)
# total_number为测试的总样本数,也就是x_test的行数,shape[0]返回变量的行数
total_number += x_test.shape[0]
# 总的准确率等于total_correct/total_number
acc = total_correct / total_number
test_acc.append(acc)
print("Test_acc:", acc)
print("--------------------------")
# 绘制 loss 曲线
plt.title('Loss Function Curve') # 图片标题
plt.xlabel('Epoch') # x轴变量名称
plt.ylabel('Loss') # y轴变量名称
plt.plot(train_loss_results, label="$Loss$") # 逐点画出trian_loss_results值并连线,连线图标是Loss
plt.legend() # 画出曲线图标
plt.show() # 画出图像
# 绘制 Accuracy 曲线
plt.title('Acc Curve') # 图片标题
plt.xlabel('Epoch') # x轴变量名称
plt.ylabel('Acc') # y轴变量名称
plt.plot(test_acc, label="$Accuracy$") # 逐点画出test_acc值并连线,连线图标是Accuracy
plt.legend()
plt.show()