1loss是什么_北⼤曹健Tensorflow2.1课程笔记整理
Tensorflow 2.1 ⼊门⾸推,曹⽼师讲解清晰,知识⾯覆盖齐全,配合视频⾷⽤⼗分舒畅。
课程⽹址:
⼈⼯智能实践:Tensorflow笔记_北京⼤学_中国⼤学MOOC(慕课)w
B站视频教程w ww.bilibili
我对其中⽤的⽐较多的部分做了整理,也参考官⽹⽂档做了⼀些补充。相关代码均为课程内容,仅⽤作学习,侵删。
基本知识
张量
为什么要在TF2中使⽤张量?
tensorflow中的数据类型
np.array :question:
tf.Variable() 将变量标记为“可训练”
array = np.array([1,2,3,4])
constant = tf.constant(a)
c = tf.Variable(array)
d = tf.Variable(constant)
print(array,constant)
print(array == constant)
print(c,d)
print(c == d)
# 打印结果:
# [1 2 3 4] tf.Tensor([1 2 3 4], shape=(4,), dtype=int64)
# tf.Tensor([ True  True  True  True], shape=(4,), dtype=bool)
# <tf.Variable 'Variable:0' shape=(4,) dtype=int64, numpy=array([1, 2, 3, 4])> <tf.Variable 'Variable:0' shape=(4,) dtype=int64, numpy=array([1, 2, 3, 4])> # tf.Tensor([ True  True  True  True], shape=(4,), dtype=bool)
结论:np.array和tf.constant没有区别?
张量的表⽰⽅法
张量的维数判定variable怎么记
等号后⾯有⼏个[,就是⼏维张量。
scalar = 1
vector = [1,2,3]
matrix = [[1,2,3],[4,5,6]]
tensor = [[[...
维度的表⽰
没到知乎的表格输⼊啊...
axis的含义
对于张量x, shape = (n,m,j,k),对应的axis就是(axis=0,axis=1,axis=2,axis=3)
张量的索引
x[m,n,p] # 从最外部的⽅框逐渐缩⼩到固定元素
张量的创建:
指定内容 tf.constant / numpy转化 tf. convert_to_tensor / 特殊结构 tf.zeros等
# tf.constant(张量内容,dtype=数据类型(可选))
import tensorflowas stant([1,5],dtype=tf.int64)
print(a)
print(a.dtype)
print(a.shape)
# tf. convert_to_tensor(数据名,dtype=数据类型(可选))
import tensorflowas tf
import numpyas np
a = np.arange(0, 5)
b = tf.convert_to_tensor( a, dtype=tf.int64 )
# 创建全为0的张量 tf. zeros(维度)
# 创建全为1的张量 tf. ones(维度)
# 创建全为指定值的张量 tf. fill(维度,指定值)
# ⽣成正态分布的随机数 tf. al(维度,mean=均值,stddev=标准差)
# ⽣成均匀分布随机数[ minval, maxval) tf. random. uniform(维度,minval=最⼩值,maxval=最⼤值)
张量的操作函数
# 计算张量维度上元素的最⼩值 tf.reduce_min(张量名, axis=操作轴))
# 计算张量维度上元素的最⼤值 tf.reduce_max(张量名, axis=操作轴))
指定axis的含义:该axis上的元素作为查⽬标/取平均值对象,遍历其他axis上的所有值,最终结果的结构是去除该axis后的值。⽐如a的shape是(2,3,4),对axis = 1运算,最终结果的shape就是(2,4)
# 同理有reduce_mean / reduce_sum
数学运算
对应元素的四则运算:tf.add,tf.subtract,tf.multiply,tf.divide
平⽅、次⽅与开⽅:tf.square,tf.pow,tf.sqrt
矩阵乘:tf.matmul
常⽤操作
梯度计算
with结构记录计算过程,gradient求出张量的梯度
# with tf.GradientTape( ) as tape:
# 若⼲个计算过程
# adient(函数,对谁求导)
with tf.GradientTape( ) as tape:
w = tf.stant(3.0))
loss = tf.pow(w,2) #loss=w2 loss’=2w
grad = adient(loss,w)
print(grad)
梯度计算的注意事项
1. 参与梯度计算的数据类型需要是float
2. 计算梯度的时候可以直接写+-*/,但不能写^
常⽤函数
<_hot(待转换数据, depth=⼏分类)
classes = 3
labels = tf.constant([1,0,2]) #
输⼊的元素值最⼩为0,最⼤为2
output = tf.one_hot( labels, depth=classes )
print(output)
# 运⾏结果:
# [[0. 1. 0.]
# [1. 0. 0.]
# [0. 0. 1.]], shape=(3, 3), dtype=float32)
data = tf.data.Dataset.from_tensor_slices((输⼊特征, 标签)) 切分传⼊张量的第⼀维度,⽣成输⼊特征/标签对,构建数据集train_db = tf.data.Dataset.from_tensor_slices((x_train, y_train)).batch(32)
⾃减函数 assign_sub
w.assign_sub(1)
模块处理
基本流程
import
train / test data
model.sequential
modelpile
model.fit
model.summary
数据导⼊
控制batch
1. 在model.fit中设置batch_size
2. 底层控制
训练
学习率设置
指数衰减学习率 = 初始学习率* 学习率衰减率(当前轮数/ 多少轮衰减⼀次)
正则化缓解过拟合
loss = loss( y与y_ )+ REGULARIZER * loss(w)
模型的保存与载⼊
⾃动进⾏参数的保存与载⼊
checkpoint_save_path = "./checkpoint/mnist.ckpt"
if ists(checkpoint_save_path + '.index'):
print('-------------load the model-----------------')
model.load_weights(checkpoint_save_path) # 如果参数存在则读取参数
# 设置回调函数(也就是保存的选项)
cp_callback = tf.keras.callbacks.ModelCheckpoint(filepath=checkpoint_save_path,
save_weights_only=True,
save_best_only=True)
# 添加callbacks就会进⾏参数保存
history = model.fit(x_train, y_train, batch_size=32, epochs=5, validation_data=(x_test, y_test), validation_freq=1, callbacks=[cp_callback])
⼿动进⾏参数的保存和载⼊
# 保存权重
model.save_weights('./checkpoints/my_checkpoint')
# 创建模型实例
model = create_model()
# Restore the weights
model.load_weights('./checkpoints/my_checkpoint')
# Evaluate the model
loss,acc = model.evaluate(test_images,  test_labels, verbose=2)
print("Restored model, accuracy: {:5.2f}%".format(100*acc))
训练结果的保存
通过history = model.fit记录训练结果
# history=model.fit(训练集数据, 训练集标签,batch_size=, epochs=, validation_split=⽤作测试数据的⽐例,validation_data=测试集, validation_freq=测试频率)
# 显⽰训练集和验证集的acc和loss曲线
acc = history.history['sparse_categorical_accuracy']
val_acc = history.history['val_sparse_categorical_accuracy']
loss = history.history['loss']
val_loss = history.history['val_loss']
history.history内部也就只有这4个list
实例程序
TF底层实现
# 利⽤鸢尾花数据集,实现前向传播、反向传播,可视化loss曲线
# 导⼊所需模块
import tensorflow as tf
from sklearn import datasets
from matplotlib import pyplot as plt
import numpy as np
import time  ##1##
# 导⼊数据,分别为输⼊特征和标签
x_data = datasets.load_iris().data
y_data = datasets.load_iris().target
# 随机打乱数据(因为原始数据是顺序的,顺序不打乱会影响准确率)
# seed: 随机数种⼦,是⼀个整数,当设置之后,每次⽣成的随机数都⼀样(为⽅便教学,以保每位同学结果⼀致)