TensorFlow的可训练变量和自动求导机制
文章目錄
- 一些概念、函數(shù)、用法
- TensorFlow實(shí)現(xiàn)一元線性回歸
- TensorFlow實(shí)現(xiàn)多元線性回歸
一些概念、函數(shù)、用法
對(duì)象Variable
創(chuàng)建對(duì)象Variable:
利用這個(gè)方法,默認(rèn)整數(shù)為int32,浮點(diǎn)數(shù)為float32,注意Numpy默認(rèn)的浮點(diǎn)數(shù)類型是float64,如果想和Numpy數(shù)據(jù)進(jìn)行對(duì)比,則需要修改與numpy一致,否則在機(jī)器學(xué)習(xí)中float32位夠用了。
將張量封裝為可訓(xùn)練變量
<tf.Variable ‘Variable:0’ shape=(2, 2) dtype=float32, numpy=array([[-1.2848959 , -0.22805293],[-0.79079854, 0.7035335 ]], dtype=float32)>
trainalbe屬性
用來檢查Variable變量是否可訓(xùn)練
可訓(xùn)練變量賦值,注意x是Variable對(duì)象類型,不是tensor類型
x.assign() x.assign_add() x.assign_sub()用isinstance()方法來判斷是tensor還是Variable
自動(dòng)求導(dǎo)
with GradientTape() as tape:
函數(shù)表達(dá)式
grad=tape.gradient(函數(shù),自變量)
tf.Tensor(9.0, shape=(), dtype=float32)
tf.Tensor(6.0, shape=(), dtype=float32)
GradientTape函數(shù)
GradientTape(persistent,watch_accessed_variables)
第一個(gè)參數(shù)默認(rèn)為false,表示梯度帶只使用一次,使用完就銷毀了,若為true則表明梯度帶可以多次使用,但在循環(huán)最后要記得把它銷毀
第二個(gè)參數(shù)默認(rèn)為true,表示自動(dòng)添加監(jiān)視
tape.watch()函數(shù)
用來添加監(jiān)視非可訓(xùn)練變量
多元函數(shù)求一階偏導(dǎo)數(shù)
tf.Tensor(42.0, shape=(), dtype=float32)
tf.Tensor(6.0, shape=(), dtype=float32)
tf.Tensor(16.0, shape=(), dtype=float32)
[<tf.Tensor: id=36, shape=(), dtype=float32, numpy=6.0>, <tf.Tensor: id=41, shape=(), dtype=float32, numpy=16.0>]
多元函數(shù)求二階偏導(dǎo)數(shù)
tf.Tensor(42.0, shape=(), dtype=float32)
[<tf.Tensor: id=27, shape=(), dtype=float32, numpy=6.0>, <tf.Tensor: id=32, shape=(), dtype=float32, numpy=16.0>]
[[<tf.Tensor: id=39, shape=(), dtype=float32, numpy=2.0>, <tf.Tensor: id=41, shape=(), dtype=float32, numpy=4.0>]]
TensorFlow實(shí)現(xiàn)一元線性回歸
import numpy as np import tensorflow as tf import matplotlib.pyplot as plt #設(shè)置字體 plt.rcParams['font.sans-serif'] =['SimHei'] #加載樣本數(shù)據(jù) x=np.array([137.97,104.50,100.00,124.32,79.20,99.00,124.00,114.00,106.69,138.05,53.75,46.91,68.00,63.02,81.26,86.21]) y=np.array([145.00,110.00,93.00,116.00,65.32,104.00,118.00,91.00,62.00,133.00,51.00,45.00,78.50,69.65,75.69,95.30]) #設(shè)置超參數(shù),學(xué)習(xí)率 learn_rate=0.0001 #迭代次數(shù) iter=100 #每10次迭代顯示一下效果 display_step=10 #設(shè)置模型參數(shù)初值 np.random.seed(612) w=tf.Variable(np.random.randn()) b=tf.Variable(np.random.randn()) #訓(xùn)練模型 #存放每次迭代的損失值 mse=[] for i in range(0,iter+1):with tf.GradientTape() as tape:pred=w*x+bLoss=0.5*tf.reduce_mean(tf.square(y-pred))mse.append(Loss)#更新參數(shù)dL_dw,dL_db = tape.gradient(Loss,[w,b])w.assign_sub(learn_rate*dL_dw)b.assign_sub(learn_rate*dL_db)#plt.plot(x,pred)if i%display_step==0:print("i:%i,Loss:%f,w:%f,b:%f"%(i,mse[i],w.numpy(),b.numpy()))TensorFlow實(shí)現(xiàn)多元線性回歸
import numpy as np import tensorflow as tf #=======================【1】加載樣本數(shù)據(jù)=============================================== area=np.array([137.97,104.50,100.00,124.32,79.20,99.00,124.00,114.00,106.69,138.05,53.75,46.91,68.00,63.02,81.26,86.21]) room=np.array([3,2,2,3,1,2,3,2,2,3,1,1,1,1,2,2]) price=np.array([145.00,110.00,93.00,116.00,65.32,104.00,118.00,91.00,62.00,133.00,51.00,45.00,78.50,69.65,75.69,95.30]) num=len(area) #樣本數(shù)量 #=======================【2】數(shù)據(jù)處理=============================================== x0=np.ones(num) #歸一化處理,這里使用線性歸一化 x1=(area-area.min())/(area.max()-area.min()) x2=(room-room.min())/(room.max()-room.min()) #堆疊屬性數(shù)組,構(gòu)造屬性矩陣 #從(16,)到(16,3),因?yàn)樾鲁霈F(xiàn)的軸是第二個(gè)軸所以axis為1 X=np.stack((x0,x1,x2),axis=1) print(X) #得到形狀為一列的數(shù)組 Y=price.reshape(-1,1) print(Y) #=======================【3】設(shè)置超參數(shù)=============================================== learn_rate=0.001 #迭代次數(shù) iter=500 #每10次迭代顯示一下效果 display_step=50 #=======================【4】設(shè)置模型參數(shù)初始值=============================================== np.random.seed(612) W=tf.Variable(np.random.randn(3,1)) #=======================【4】訓(xùn)練模型============================================= mse=[] for i in range(0,iter+1):with tf.GradientTape() as tape:PRED=tf.matmul(X,W)Loss=0.5*tf.reduce_mean(tf.square(Y-PRED))mse.append(Loss)#更新參數(shù)dL_dw = tape.gradient(Loss,W)W.assign_sub(learn_rate*dL_dw)#plt.plot(x,pred)if i % display_step==0:print("i:%i,Loss:%f"%(i,mse[i]))喜歡的話點(diǎn)個(gè)贊和關(guān)注唄! 創(chuàng)作挑戰(zhàn)賽新人創(chuàng)作獎(jiǎng)勵(lì)來咯,堅(jiān)持創(chuàng)作打卡瓜分現(xiàn)金大獎(jiǎng)
總結(jié)
以上是生活随笔為你收集整理的TensorFlow的可训练变量和自动求导机制的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 地生中考没考好怎么办,想上重点高中啊?
- 下一篇: 梯度下降法预测波士顿房价以及简单的模型评