日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 编程资源 > 编程问答 >内容正文

编程问答

TensorFlow的可训练变量和自动求导机制

發(fā)布時(shí)間:2023/12/1 编程问答 44 豆豆
生活随笔 收集整理的這篇文章主要介紹了 TensorFlow的可训练变量和自动求导机制 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

文章目錄

  • 一些概念、函數(shù)、用法
  • TensorFlow實(shí)現(xiàn)一元線性回歸
  • TensorFlow實(shí)現(xiàn)多元線性回歸


一些概念、函數(shù)、用法

對(duì)象Variable

創(chuàng)建對(duì)象Variable:

tf.Variable(initial_value,dtype)

利用這個(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)練變量

print(tf.Variable(tf.random. normal([2,2])))

<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.trainalbe

可訓(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ù),自變量)

x=tf.Variable(3.) with tf.GradientTape() as tape:y=tf.square(x) dy_dx = tape.gradient(y,x) print(y) print(dy_dx)

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ù)

x=tf.Variable(3.) y=tf.Variable(4.) with tf.GradientTape(persistent=True) as tape:f=tf.square(x)+2*tf.square(y)+1 df_dx,df_dy = tape.gradient(f,[x,y]) first_grade = tape.gradient(f,[x,y]) print(f) print(df_dx) print(df_dy) print(first_grade) del tape

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ù)

x=tf.Variable(3.) y=tf.Variable(4.) with tf.GradientTape(persistent=True) as tape2:with tf.GradientTape(persistent=True) as tape1:f=tf.square(x)+2*tf.square(y)+1first_grade = tape1.gradient(f,[x,y]) second_grade = [tape2.gradient(first_grade,[x,y])] print(f) print(first_grade) print(second_grade) del tape1 del tape2

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的可训练变量和自动求导机制的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。