50题真 • 一文入门TensorFlow2.x
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 的常量 Tensor5.創建3x3隨機的隨機數組
tf.random.normal([3,3])6.通過二維數組創建一個常量張量
a = tf.constant([[1, 2], [3, 4]]) # 形狀為 (2, 2) 的二維常量 a7.取出張量中的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 + a11.將兩個張量做矩陣乘法
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]) x16.新建一個GradientTape追蹤梯度,把要微分的公式寫在里面
with tf.GradientTape() as tape: # 追蹤梯度y = x * x17.求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 + b21.創建損失函數,此處采用真實值與預測值的差的平方,公式為:
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 OUTPUT38.創建一個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) / 25545.預處理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的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 头条+腾讯 双杀面经(NLP实习)
- 下一篇: 数据可视化实战,画个新冠肺炎地图