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

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

50题真 • 一文入门TensorFlow2.x

發布時間:2025/3/8 编程问答 23 豆豆
生活随笔 收集整理的這篇文章主要介紹了 50题真 • 一文入门TensorFlow2.x 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
這個教程是使用tensorflow低階api做的,想學keras的高階api可以直接看keras教程40題刷爆Keras,人生苦短我選Keras TensorFlow是谷歌基于DistBelief進行研發的第二代人工智能學習系統,其命名來源于本身的運行原理。Tensor(張量)意味著N維數組,Flow(流)意味著基于數據流圖的計算,TensorFlow為張量從流圖的一端流動到另一端計算過程。TensorFlow是將復雜的數據結構傳輸至人工智能神經網中進行分析和處理過程的系統。TensorFlow可被用于語音識別或圖像識別等多項機器學習和深度學習領域,對2011年開發的深度學習基礎架構DistBelief進行了各方面的改進,它可在小到一部智能手機、大到數千臺數據中心服務器的各種設備上運行。TensorFlow將完全開源,任何人都可以用。(抄的) 另外,我自己感覺TensorFlow挺難裝的,所以建議大家可以用線上環境先學起來,點擊下方在線運行???? https://www.kesci.com/home/project/5e28030eb8c462002d64c517 # 導入一些必要的庫 import numpy as np import matplotlib.pyplot as plt import os import pickle

1.導入tensorflow庫簡寫為tf,并輸出版本

import tensorflow as tftf.__version__

一、Tensor張量

常量

2.創建一個3x3的0常量張量

c = tf.zeros([3, 3])

3.根據上題張量的形狀,創建一個一樣形狀的1常量張量

tf.ones_like(c)

4.創建一個2x3,數值全為6的常量張量

tf.fill([2, 3], 6) # 2x3 全為 6 的常量 Tensor

5.創建3x3隨機的隨機數組

tf.random.normal([3,3])

6.通過二維數組創建一個常量張量

a = tf.constant([[1, 2], [3, 4]]) # 形狀為 (2, 2) 的二維常量 a

7.取出張量中的numpy數組

a.numpy()

8.從1.0-10.0等間距取出5個數形成一個常量張量

tf.linspace(1.0, 10.0, 5)

9.從1開始間隔2取1個數字,到大等于10為止

tf.range(start=1, limit=10, delta=2)

運算

10.將兩個張量相加

a + a

11.將兩個張量做矩陣乘法

tf.matmul(a, a)

12.兩個張量做點乘

tf.multiply(a, a)

13.將一個張量轉置

tf.linalg.matrix_transpose(c)

14.將一個12x1張量變形成3行的張量

b = tf.linspace(1.0, 10.0, 12) tf.reshape(b,[3,4])# 方法二 tf.reshape(b,[3,-1])

二、自動微分

這一部分將會實現? 在? 處的導數

變量

15.新建一個1x1變量,值為1

x = tf.Variable([1.0]) x

16.新建一個GradientTape追蹤梯度,把要微分的公式寫在里面

with tf.GradientTape() as tape: # 追蹤梯度y = x * x

17.求y對于x的導數

grad = tape.gradient(y, x) # 計算梯度 grad

三、線性回歸案例

這一部分將生成添加隨機噪聲的沿100個的數據點,再對這些數據點進行擬合。

18.生成X,y數據,X為100個隨機數,y=3X+2+noise,noise為100個隨機數

X = tf.random.normal([100, 1]).numpy() noise = tf.random.normal([100, 1]).numpy()y = 3*X+2+noise

可視化這些點

plt.scatter(X, y)

19.創建需要預測的參數W,b(變量張量)

W = tf.Variable(np.random.randn()) b = tf.Variable(np.random.randn())print('W: %f, b: %f'%(W.numpy(), b.numpy()))

20.創建線性回歸預測模型

def linear_regression(x):return W * x + b

21.創建損失函數,此處采用真實值與預測值的差的平方,公式為:

def mean_square(y_pred, y_true):return tf.reduce_mean(tf.square(y_pred-y_true))

22.創建GradientTape,寫入需要微分的過程

with tf.GradientTape() as tape:pred = linear_regression(X)loss = mean_square(pred, y)

23.對loss,分別求關于W,b的偏導數

dW, db = tape.gradient(loss, [W, b])

24.用最簡單樸素的梯度下降更新W,b,learning_rate設置為0.1

W.assign_sub(0.1*dW) b.assign_sub(0.1*db) print('W: %f, b: %f'%(W.numpy(), b.numpy()))

25.以上就是單次迭代的過程,現在我們要繼續循環迭代20次,并且記錄每次的loss,W,b

for i in range(20):with tf.GradientTape() as tape:pred = linear_regression(X)loss = mean_square(pred, y)dW, db = tape.gradient(loss, [W, b])W.assign_sub(0.1*dW)b.assign_sub(0.1*db)print("step: %i, loss: %f, W: %f, b: %f" % (i+1, loss, W.numpy(), b.numpy()))

畫出最終擬合的曲線

plt.plot(X, y, 'ro', label='Original data') plt.plot(X, np.array(W * X + b), label='Fitted line') plt.legend() plt.show()

四、神經網絡案例

這部分將會在CIFAR10數據集上,訓練LeNet5模型

模型結構如下所示:

CIFAR10數據集為32x32的3通道圖像,標簽共10個種類

定義參數

26.定義第①步:卷積層的參數

輸入圖片:3×32×32

卷積核大小:5×5

卷積核種類:6

所以需要定義5×5×3×6個權重變量,和6個bias變量

conv1_w = tf.Variable(tf.random.truncated_normal([5,5,3,6], stddev=0.1)) conv1_b = tf.Variable(tf.zeros([6]))

27.定義第③步:卷積層的參數

輸入:14×14×6

卷積核大小:5×5

卷積核種類:16

所以需要定義5×5×6×16個權重變量,和16個bias變量

conv2_w = tf.Variable(tf.random.truncated_normal([5, 5, 6, 16], stddev=0.1)) conv2_b = tf.Variable(tf.zeros([16]))

28.定義第⑤步:全連接層的參數

輸入:5×5×16

輸出:120

fc1_w = tf.Variable(tf.random.truncated_normal([5*5*16, 120], stddev=0.1)) fc1_b = tf.Variable(tf.zeros([120]))

29.定義第⑥步:全連接層的參數

輸入:120

輸出:84

fc2_w = tf.Variable(tf.random.truncated_normal([120, 84], stddev=0.1)) fc2_b = tf.Variable(tf.zeros([84]))

30.定義第⑦步:全連接層的參數

輸入:84

輸出:10

fc3_w = tf.Variable(tf.random.truncated_normal([84, 10], stddev=0.1)) fc3_b = tf.Variable(tf.zeros([10]))

搭模型

def lenet5(input_img):## 31.搭建INPUT->C1的步驟conv1_1 = tf.nn.conv2d(input_img, conv1_w, strides=[1,1,1,1], padding="VALID")conv1_2 = tf.nn.relu(tf.nn.bias_add(conv1_1,conv1_b))## 32.搭建C1->S2的步驟pool1 = tf.nn.max_pool(conv1_2,ksize=[1,2,2,1],strides=[1,2,2,1],padding="VALID")## 33.搭建S2->C3的步驟conv2_1 = tf.nn.conv2d(pool1,conv2_w,strides=[1,1,1,1],padding="VALID")conv2_2 = tf.nn.relu(tf.nn.bias_add(conv2_1,conv2_b))## 34.搭建C3->S4的步驟pool2 = tf.nn.max_pool(conv2_2,ksize=[1,2,2,1],strides=[1,2,2,1],padding="VALID")## 35.將S4的輸出扁平化reshaped = tf.reshape(pool2,[-1, 16*5*5])## 35.搭建S4->C5的步驟fc1 = tf.nn.relu(tf.matmul(reshaped,fc1_w) + fc1_b)## 36.搭建C5->F6的步驟fc2 = tf.nn.relu(tf.matmul(fc1,fc2_w) + fc2_b)## 37.搭建F6->OUTPUT的步驟OUTPUT = tf.nn.softmax(tf.matmul(fc2,fc3_w) + fc3_b)return OUTPUT

38.創建一個Adam優化器,學習率0.02

optimizer = tf.optimizers.Adam(learning_rate=0.02)

驗證網絡正確性

(隨便搞點數據,驗證一下能不能跑通) 39.隨機一對x,y數據,x的形狀為(1,32,32,3),y的形狀為(10,)

test_x = tf.Variable(tf.random.truncated_normal([1,32,32,3])) test_y = [1,0,0,0,0,0,0,0,0,0]

將數據送入模型,進行反向傳播

with tf.GradientTape() as tape:## 40.將數據從入模型prediction = lenet5(test_x)print("第一次預測:", prediction)## 41.使用交叉熵作為損失函數,計算損失cross_entropy = -tf.reduce_sum(test_y * tf.math.log(prediction)) ## 42.計算梯度 trainable_variables = [conv1_w, conv1_b, conv2_w, conv2_b, fc1_w, fc1_b, fc2_w, fc2_b, fc3_w, fc3_b] # 需優化參數列表 grads = tape.gradient(cross_entropy, trainable_variables) ## 43.更新梯度 optimizer.apply_gradients(zip(grads, trainable_variables))print("反向傳播后的預測:", lenet5(test_x))

讀入數據,預處理

## load_cifar()定義略 train_X, train_Y, test_X, test_Y = load_cifar('/home/kesci/input/cifar10') classes = ('plane', 'car', 'bird', 'cat','deer', 'dog', 'frog', 'horse', 'ship', 'truck') train_X.shape, train_X.shape, test_X.shape, test_Y.shape

撈一個數據看看樣子

plt.imshow(train_X[0]) plt.show() print(classes[train_Y[0]])

44.預處理1:將train_y, test_y進行歸一化

train_X = tf.cast(train_X, dtype=tf.float32) / 255 test_X = tf.cast(test_X, dtype=tf.float32) / 255

45.預處理2:將train_y, test_y進行onehot編碼

train_Y = tf.one_hot(train_Y, depth=10) test_Y = tf.one_hot(test_Y, depth=10)

訓練網絡

因為前面實驗的時候修改過參數,所以需要重新初始化所有參數

conv1_w = tf.Variable(tf.random.truncated_normal([5,5,3,6], stddev=0.1)) conv1_b = tf.Variable(tf.zeros([6])) conv2_w = tf.Variable(tf.random.truncated_normal([5, 5, 6, 16], stddev=0.1)) conv2_b = tf.Variable(tf.zeros([16])) fc1_w = tf.Variable(tf.random.truncated_normal([5*5*16, 120], stddev=0.1)) fc1_b = tf.Variable(tf.zeros([120])) fc2_w = tf.Variable(tf.random.truncated_normal([120, 84], stddev=0.1)) fc2_b = tf.Variable(tf.zeros([84])) fc3_w = tf.Variable(tf.random.truncated_normal([84, 10], stddev=0.1)) fc3_b = tf.Variable(tf.zeros([10]))

然后再重新定義一個優化器

optimizer2 = tf.optimizers.Adam(learning_rate=0.002)

簡簡單單隨便寫一個算準確率的函數

def accuracy_fn(y_pred, y_true):preds = tf.argmax(y_pred, axis=1) # 取值最大的索引,正好對應字符標簽labels = tf.argmax(y_true, axis=1)return tf.reduce_mean(tf.cast(tf.equal(preds, labels), tf.float32))

46.把數據送入模型,開始訓練,訓練集迭代5遍,每遍分成25個batch,數據集每迭代完一遍,輸出一次訓練集上的準確率

EPOCHS = 5 # 整個數據集迭代次數for epoch in range(EPOCHS):for i in range(25): # 一整個數據集分為10個小batch訓練with tf.GradientTape() as tape:prediction = lenet5(train_X[i*2000:(i+1)*2000])cross_entropy = -tf.reduce_sum(train_Y[i*2000:(i+1)*2000] * tf.math.log(prediction))trainable_variables = [conv1_w, conv1_b, conv2_w, conv2_b, fc1_w, fc1_b, fc2_w, fc2_b, fc3_w, fc3_b] # 需優化參數列表grads = tape.gradient(cross_entropy, trainable_variables) # 計算梯度optimizer2.apply_gradients(zip(grads, trainable_variables)) # 更新梯度# 每訓練完一次,輸出一下訓練集的準確率accuracy = accuracy_fn(lenet5(train_X), train_Y)print('Epoch [{}/{}], Train loss: {:.3f}, Test accuracy: {:.3f}'.format(epoch+1, EPOCHS, cross_entropy/2000, accuracy))

使用網絡進行預測

47.在測試集上進行預測

test_prediction = lenet5(test_X) test_acc = accuracy_fn(test_prediction, test_Y) test_acc.numpy()

取一些數據查看預測結果

plt.figure(figsize=(10,10)) for i in range(25):plt.subplot(5,5,i+1)plt.imshow(test_X[i], cmap=plt.cm.binary)title=classes[np.argmax(test_Y[i])]+'=>'title+=classes[np.argmax(test_prediction[i])]plt.xlabel(title)plt.xticks([])plt.yticks([])plt.grid(False)

五、變量保存&讀取

這一部分,我們實現最簡單的保存&讀取變量值

48.新建一個Checkpoint對象,并且往里灌一個剛剛訓練完的數據

save = tf.train.Checkpoint() save.listed = [fc3_b] save.mapped = {'fc3_b': save.listed[0]}

49.利用save()的方法保存,并且記錄返回的保存路徑

save_path = save.save('/home/kesci/work/data/tf_list_example') print(save_path)

50.新建一個Checkpoint對象,從里讀出數據

restore = tf.train.Checkpoint() fc3_b2 = tf.Variable(tf.zeros([10])) print(fc3_b2.numpy()) restore.mapped = {'fc3_b': fc3_b2} restore.restore(save_path) print(fc3_b2.numpy())往期精彩回顧適合初學者入門人工智能的路線及資料下載 機器學習在線手冊 深度學習在線手冊 AI基礎下載(pdf更新到25集) 本站qq群1003271085,加入微信群請回復“加群” 獲取一折本站知識星球優惠券,請回復“知識星球” 喜歡文章,點個在看

總結

以上是生活随笔為你收集整理的50题真 • 一文入门TensorFlow2.x的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。