TensorFlow基础学习笔记
version==2.3.0
参考资料:《简单粗暴TensorFlow》
在Colab上运行
在Colab中使用TensorFlow,免费在线交互Python运行环境,且提供GPU支持。
网址:https://colab.research.google.com
新建笔记本运行python程序
在菜单 “代码执行程序 - 更改运行时类型”可选择GPU加速
ctrl+enter 执行代码 tab弹出代码提示
1+1
属性TensorFlow数据基本单位是张量,概念上等同于多维数组。
张量的属性有:
形状 shape类型 dtype值 numpy() 将张量值转化为数组示例:
# 定义一个随机数(标量) random_float = tf.random.uniform(shape=()) # 定义一个有2个元素的零向量 zero_vector = tf.zeros(shape=(2)) # 定义两个2×2的常量矩阵 A = tf.constant([[1., 2.], [3., 4.]]) B = tf.constant([[5., 6.], [7., 8.]]) # 查看矩阵A的形状、类型和值 print(A.shape) # 输出(2, 2),即矩阵的长和宽均为2 print(A.dtype) # 输出<dtype: 'float32'> print(A.numpy()) # 输出[[1. 2.] # [3. 4.]] 123456789101112 自定义
自定矩阵大小、类型以及值:
A = tf.constant([[1., 2.], [3., 4.]],shape=(2,2),dtype=tf.float32) 1 操作
C = tf.add(A, B) # 计算矩阵A和B的和 D = tf.matmul(A, B) # 计算矩阵A和B的乘积 12
C、D矩阵的计算结果为:
tf.Tensor( [[ 6. 8.] [10. 12.]], shape=(2, 2), dtype=float32) tf.Tensor( [[19. 22.] [43. 50.]], shape=(2, 2), dtype=float32) 12
自动求导
基本使用tf.GradientTape()实现自动求导
示例:
求 y = f ( x ) = x 2 在 x = 3 时 的 导 数 求y=f(x)=x^2 在 x=3 时的导数 求y=f(x)=x2在x=3时的导数
x = tf.Variable(initial_value=3.)# x是变量,同样具有形状、类型和值三个属性。使用initial_value进行变量初始化 with tf.GradientTape() as tape: # 在 tf.GradientTape() 的上下文内,所有计算步骤都会被记录以用于求导 y = tf.square(x) y_grad = tape.gradient(y, x) # 计算y关于x的导数。在上下文环境之外,记录停止,但记录器tape依然可用 print(y, y_grad) 12345
变量默认能够被自动求导机制所求导,往往被用于定义机器学习模型的参数
输出结果:
tf.Tensor(9.0, shape=(), dtype=float32) tf.Tensor(6.0, shape=(), dtype=float32) 1 多元函数求偏导(向量 矩阵)
示例:
计 算 L ( w , b ) = ∣ ∣ X w + b − y ∣ ∣ 2 在 w = ( 1 , 2 ) T , b = 1 时 分 别 对 w , b 的 偏 导 数 X = [ 1 2 3 4 ] , y = [ 1 2 ] 计算L(w,b)=||Xw+b-y||^2在w=(1,2)^T,b=1时分别对w,b的偏导数 \X=[1234]
,y=[12]
计算L(w,b)=∣∣Xw+b−y∣∣2在w=(1,2)T,b=1时分别对w,b的偏导数X=[1324],y=[12]
X = tf.constant([[1., 2.], [3., 4.]]) y = tf.constant([[1.], [2.]]) w = tf.Variable(initial_value=[[1.], [2.]]) b = tf.Variable(initial_value=1.) with tf.GradientTape() as tape: L = tf.reduce_sum(tf.square(tf.matmul(X, w) + b - y))# square()是对张量的每一个元素求平方;reduce_sum()是对张量所有元素求和 w_grad, b_grad = tape.gradient(L, [w, b]) # 计算L(w, b)关于w, b的偏导数 print(L, w_grad, b_grad) 12345678
输出结果:
tf.Tensor(125.0, shape=(), dtype=float32) tf.Tensor( [[ 70.] [100.]], shape=(2, 1), dtype=float32) tf.Tensor(30.0, shape=(), dtype=float32) 123
数学表示为:
L ( ( 1 , 2 ) T , 1 ) = 125 ∂ L ( w , b ) ∂ w ∣ w = ( 1 , 2 ) T , b = 1 = [ 70 100 ] ∂ L ( w , b ) ∂ b ∣ w = ( 1 , 2 ) T , b = 1 = 30 L((1,2)^T,1)=125\frac{partial L(w,b)}{partial w}|_{w=(1,2)^T,b=1}=[70100]
\frac{partial L(w,b)}{partial b}|_{w=(1,2)^T,b=1}=30\ L((1,2)T,1)=125∂w∂L(w,b)∣w=(1,2)T,b=1=[70100]∂b∂L(w,b)∣w=(1,2)T,b=1=30
线性回归
使用Tensorflow利用梯度下降法计算线性回归的解
tf.keras.optimizers.SGD(learning_rate=...)声明梯度下降优化器,并定义学习率(梯度下降一次迈出步子的大小)
优化器的apply_gradients()方法自动根据求导结果更新模型参数,并且需要提供参数grads_and_vars=[(变量的偏导数,变量)],每次迭代计算参数的偏导,然后用python的zip()方法将偏导与参数包裹在一起交给迭代器即可
Python的zip()方法:将对应元素打包成元组,返回元组组成的列表,如a=[1,2],b=[3,4],zip(a,b)=[(1,3),(2,4)]
在Python3中,zip()方法返回的是zip对象,需要调用list()将生成器转化为列表
示例:
用线性模型y=ax+b拟合以下数据:
y20132014201520162017x1200014000150001650017500先用numpy定义数据,归一
import numpy as np import tensorflow as tf X_raw = np.array([2013, 2014, 2015, 2016, 2017], dtype=np.float32) y_raw = np.array([12000, 14000, 15000, 16500, 17500], dtype=np.float32) X = (X_raw - X_raw.min()) / (X_raw.max() - X_raw.min()) y = (y_raw - y_raw.min()) / (y_raw.max() - y_raw.min()) 123456
转化为张量,并定义变量
X = tf.constant(X) y = tf.constant(y) a = tf.Variable(initial_value=0.) b = tf.Variable(initial_value=0.) variables = [a, b] 12345
梯度下降法进行计算:
num_epoch = 10000 #迭代次数 # 声名梯度下降优化器,定义学习率 optimizer = tf.keras.optimizers.SGD(learning_rate=5e-4) for e in range(num_epoch): with tf.GradientTape() as tape: y_pred = a * X + b # 计算损失函数 loss = tf.reduce_sum(tf.square(y_pred - y)) # 计算损失函数关于变量的偏导(梯度) grads = tape.gradient(loss, variables) # 根据偏导值更新参数 optimizer.apply_gradients(grads_and_vars=zip(grads, variables)) 123456789101112
计算结果:
[<tf.Variable 'Variable:0' shape=() dtype=float32, numpy=0.97637>, <tf.Variable 'Variable:0' shape=() dtype=float32, numpy=0.057565063>] 1
相关知识
TensorFlow学习记录(八)
Tensorflow学习笔记——搭建神经网络
深度学习入坑笔记之五
深度学习入门——基于TensorFlow的鸢尾花分类实现(TensorFlow
tensorflow识别花朵
tensorflow笔记之l2正则化
TensorFlow入门
深度学习之基于Tensorflow卷积神经网络花卉识别系统
深度学习应用开发
【实战】tensorflow 花卉识别
网址: TensorFlow基础学习笔记 https://www.huajiangbk.com/newsview1254877.html
上一篇: 矢量网络分析仪学习培训教程 |
下一篇: 学习opencv |
推荐分享

- 1君子兰什么品种最名贵 十大名 4012
- 2世界上最名贵的10种兰花图片 3364
- 3花圈挽联怎么写? 3286
- 4迷信说家里不能放假花 家里摆 1878
- 5香山红叶什么时候红 1493
- 6花的意思,花的解释,花的拼音 1210
- 7教师节送什么花最合适 1167
- 8勿忘我花图片 1103
- 9橄榄枝的象征意义 1093
- 10洛阳的市花 1039