大三寒假學習進度(4)
阿新 • • 發佈:2021-01-20
tensorflow學習
-
鳶尾花分類
步驟
1 · 準備資料,包括資料集讀入、資料集亂序,把訓練集和測試集中的資料配成輸入特徵和標籤對,生成 train 和 test 即永不相見的訓練集和測試集;
2 · 搭建網路,定義神經網路中的所有可訓練引數;
3 · 優化這些可訓練的引數,利用巢狀迴圈在 with 結構中求得損失函式 loss對每個可訓練引數的偏導數,更改這些可訓練引數,為了檢視效果,程式中可以加入每遍歷一次資料集顯示當前準確率,還 可以畫出準確率 acc 和損失函式 loss的變化曲線圖。
程式碼實現
from sklearn import datasets import tensorflow as tf import numpy as np from matplotlib import pyplot as plt #讀入資料並進行資料分割處理 x_data =datasets.load_iris().data y_data =datasets.load_iris().target np.random.seed(116) np.random.shuffle(x_data) np.random.seed(116) np.random.shuffle(y_data) tf.random.set_seed(116) x_train = x_data[:-30] y_train = y_data[:-30] x_test = x_data[-30:] y_test = y_data[-30:] x_train = tf.cast(x_train,tf.float32) x_test = tf.cast(x_test,tf.float32) train_db = tf.data.Dataset.from_tensor_slices((x_train, y_train)).batch(32) test_db = tf.data.Dataset.from_tensor_slices((x_test, y_test)).batch(32) # 設定引數 w1 = tf.Variable(tf.random.truncated_normal([4,3],stddev =0.1,seed=1)) b1 = tf.Variable(tf.random.truncated_normal([3],stddev=0.1,seed=1)) lr =0.1#學習率 train_loss_results=[] test_acc=[] epoch = 500#迴圈次數 loss_all = 0 # 訓練部分 for epoch in range(epoch): for step,(x_train,y_train) in enumerate(train_db): with tf.GradientTape() as tape: y = tf.matmul(x_train, w1) + b1 y = tf.nn.softmax(y) y_ = tf.one_hot(y_train, depth=3) loss = tf.reduce_mean(tf.square(y_ - y)) loss_all += loss.numpy() grads = tape.gradient(loss,[w1,b1]) # 更新引數 w1.assign_sub(lr * grads[0]) b1.assign_sub(lr * grads[1]) print("Epoch {}, loss: {}".format(epoch, loss_all/4)) train_loss_results.append(loss_all/4) loss_all=0 total_correct, total_number = 0,0 for x_test , y_test in test_db: y = tf.matmul(x_test,w1)+b1 y =tf.nn.softmax(y) pred = tf.argmax(y,axis=1) pred = tf.cast(pred,dtype=y_test.dtype) correct = tf.cast(tf.equal(pred, y_test), dtype=tf.int32) correct = tf.reduce_sum(correct) # 將每個 batch 的 correct 數加起來 total_correct += int(correct) # 將所有 batch 中的 correct 數加起來 total_number += x_test.shape[0] acc = total_correct / total_number test_acc.append(acc) print("test_acc:", acc) print("--------------------------------") # 畫圖 plt.title('Loss Function Curve') # 圖片標題 plt.xlabel('Epoch') # x 軸名稱 plt.ylabel('Loss') # y 軸名稱 plt.plot(train_loss_results, label="$Loss$") # plt.legend() plt.show() plt.title('Acc Curve') # 圖片標題 plt.xlabel('Epoch') # x 軸名稱 plt.ylabel('Acc') # y 軸名稱 plt.plot(test_acc, label="$Accuracy$") # 逐點畫出 test_acc 值並連線 plt.legend() plt.show()
結果