1. 程式人生 > 其它 >Tensorboard進行視覺化:書寫字型原始碼實現

Tensorboard進行視覺化:書寫字型原始碼實現

技術標籤:TensorFlowtensorflow

TensorBoard是一套用於檢查和理解TensorFlow執行和圖形的Web應用程式,這也是Google的TensorFlow比Facebook的Pytorch最大的優勢之一。

# Import the deep learning library
import tensorflow as tf
tf.compat.v1.disable_eager_execution()
# Define our compuational graph
W1 = tf.constant(5.0, name="x")
W2 = tf.
constant(3.0, name="y") W3 = tf.cos(W1, name="cos") W4 = tf.sin(W2, name="sin") W5 = tf.multiply(W3, W4, name="mult") W6 = tf.divide(W1, W2, name="div") W7 = tf.add(W5, W6, name="add") # Open the session with tf.compat.v1.Session() as sess:
cos = sess.run(W3) sin = sess.run(W4) mult = sess.run(W5) div = sess.run(W6) add = sess.run(W7) # Before running TensorBoard, make sure you have generated summary data in a log directory by creating a summary writer writer = tf.compat.v1.summary.FileWriter("./ComputationGraph"
, sess.graph) # Once you have event files, run TensorBoard and provide the log directory # Command: tensorboard --logdir="path/to/logs"

在這裡插入圖片描述

終端執行:備註:tensorboard --logdir="path/to/logs
到指定路徑下執行:
tensorboard --logdir logs/ComputationGraph

根據提示開啟連結:

Serving TensorBoard on localhost; to expose to the network, use a proxy or pass --bind_all
TensorBoard 2.0.2 at http://localhost:6006/ (Press CTRL+C to quit)


書寫字型原始碼實現:

import tensorflow as tf
import numpy as np
import math
from tensorflow import keras
from tensorflow.keras import datasets,layers,optimizers,Sequential
from tensorflow.keras.callbacks import TensorBoard
import datetime
import matplotlib.pyplot as plt
plt.rcParams['axes.unicode_minus']=True


#匯入資料
(x_train,y_train),(x_test,y_test)=tf.keras.datasets.mnist.load_data()
print(x_train.shape,x_test.shape)

#預處理---正規化
def normalize(x,y):
    x=tf.cast(x,tf.float32)
    x/=255
    return x,y

#新增一層維度,方便後續扁平化
x_train=tf.expand_dims(x_train,axis=-1)
x_test=tf.expand_dims(x_test,axis=-1)

train_dataset=tf.data.Dataset.from_tensor_slices((x_train,y_train))
test_dataset=tf.data.Dataset.from_tensor_slices((x_test,y_test))
train_dataset=train_dataset.map(normalize)
test_dataset=test_dataset.map(normalize)


#畫圖
plt.figure(figsize=(10,15))
i=0
for (x_test,y_test) in test_dataset.take(25):
    x_test=x_test.numpy().reshape((28,28))
    plt.subplot(5,5,i+1)
    plt.grid(False)
    plt.xticks([])
    plt.imshow(x_test,cmap=plt.cm.binary)
    plt.xlabel([y_test.numpy()],fontsize=10)
    i+=1
plt.show()


#開始定義模型
model=tf.keras.Sequential([
    tf.keras.layers.Flatten(input_shape=(28,28,1)),
    tf.keras.layers.Dense(128,activation=tf.nn.relu),
    tf.keras.layers.Dense(64,activation=tf.nn.relu),
    tf.keras.layers.Dense(10,activation=tf.nn.softmax)
])

model.summary()

# 模型編譯
model.compile(optimizer='adam',loss='sparse_categorical_crossentropy',metrics=['accuracy'])

#開始訓練
batch_size=32
train_dataset=train_dataset.repeat().shuffle(60000).batch(batch_size)
test_dataset=test_dataset.batch(batch_size)
#為tensorboard視覺化儲存資料
tensorboard_callback=tf.keras.callbacks.TensorBoard(histogram_freq=1)
model.fit(train_dataset,epochs=5,steps_per_epoch=math.ceil(60000/batch_size),callbacks=[tensorboard_callback])

#模型評估
test_loss,test_accuracy=model.evaluate(test_dataset,steps=math.ceil(10000/32))
print('Accuracy on test_dataset',test_accuracy)

# 模型預測
predictions = model.predict(test_dataset)


# 檢視預測結果
def plot_test(i, predictions_array, true_labels, images):
    predic, label, img = predictions_array[i], true_labels[i], images[i]
    plt.grid(False)
    plt.xticks([])
    plt.imshow(img[..., 0], cmap=plt.cm.binary)
    predic_label = np.argmax(predic)
    if (predic_label == label):
        color = 'green'
    else:
        color = 'red'
    plt.xlabel("預測標籤為:{},概率:{:2.0f}% (真實標籤:{})".format(predic_label, 100 * np.max(predic), label), color=color)


def plot_value(i, predictions_array, true_label):
    predic, label = predictions_array[i], true_label[i]
    plt.grid(False)
    plt.xticks([])
    thisplot = plt.bar(range(10), predic, color='#777777')
    plt.ylim([0, 1])
    predic_label = np.argmax(predic)
    thisplot[predic_label].set_color('blue')
    thisplot[label].set_color('green')


rows, cols = 5, 3
num_images = rows * cols
for test_images, test_labels in test_dataset.take(1):
    test_images = test_images.numpy()
    test_labels = test_labels.numpy()

plt.figure(figsize=(2 * 2 * cols, 2 * rows))
for i in range(num_images):
    plt.subplot(rows, 2 * cols, 2 * i + 1)
    plot_test(i, predictions, test_labels, test_images)
    plt.subplot(rows, 2 * cols, 2 * i + 2)
    plot_value(i, predictions, test_labels)