使用tensorflow进行模型训练并使用TensorBoard进行可视化展示

1.使用tensorflow加载数据,并进行数据的预处理

import tensorflow as tf
#使用keras加载数据集,每个图像都表示为28*28的数字,而不是尺寸784的一维数组
fashion_mnist = tf.keras.datasets.fashion_mnist.load_data()
(x_train_full, y_train_full), (x_test, y_test) = fashion_mnist
x_train,y_train = x_train_full[:-5000],y_train_full[:-5000]
x_valid ,y_valid = x_train_full[-5000:],y_train_full[-5000:]
print(x_train.shape)
print(x_train.dtype)

# 2. 数据预处理
x_train = x_train/ 255.0  # 归一化到 [0,1]
x_valid = x_valid/255.0
x_test = x_test/ 255.0

#类别名称
class_names =["T-shirt/top", "Trouser", "Pullover", "Dress", "Coat",
               "Sandal", "Shirt", "Sneaker", "Bag", "Ankle boot"]

 2.构建模型

# 构建模型(使用 Keras 的 Input 层)
tf.random.set_seed(42)
model = tf.keras.Sequential([
    tf.keras.layers.Input(shape=(28,28)),  # 相当于 placeholder
    tf.keras.layers.Flatten(),
    tf.keras.layers.Dense(300, activation='relu'),
    tf.keras.layers.Dense(100, activation='relu'),
    tf.keras.layers.Dense(10, activation='softmax')
])

print(model.summary)

  3.编译模型

# 编译模型
model.compile(optimizer=tf.keras.optimizers.SGD(),
              loss='sparse_categorical_crossentropy',
              metrics=['accuracy'])

  4.训练模型并添加TensorBoard回调

# 训练模型
''' history对象包含训练参数,经历的轮次列表,最重要的是包含在训练集和验证集上每轮结束时测得损失和额外指标的字典 
使用此字典创建pandas DataFrame并调用plot方法,可绘制学习曲线
'''
from pathlib import Path
from time import strftime

def get_run_logdir(root_logdir="my_logs"):
return Path(root_logdir) / strftime("run_%Y_%m_%d_%H_%M_%S")
#根据当前日期和时间生成日志子目录的路径
run_logdir = get_run_logdir()

tensorboard_cb = tf.keras.callbacks.TensorBoard(run_logdir, profile_batch=(100, 200)) history = model.fit(x_train,y_train, epochs=30,validation_data=(x_valid,y_valid),callbacks=[tensorboard_cb])
#绘制学习曲线
import  matplotlib.pyplot as plt
import pandas as pd

pd.DataFrame(history.history).plot(
figsize=(8,5),xlim=[0,29],ylim=[0,1],grid=True,xlabel="Epoch",
style=["r--","r--.","b-","b-*"]
)
plt.show()

  5.评估模型

#评估模型
test_loss, test_acc = model.evaluate(x_test, y_test)
print(f"\n测试集准确率: {test_acc:.4f}")

  6.启动TensorBoard服务

  1.    查看项目目录下是否成功生成了日志文件
  2.    在终端启动命令: tensorboard --logdir my_logs/ 
  3.   点击服务器启动链接,在浏览器中查看信息

image

 7. QA

启动tersonboard服务报如下错误:

import pkg_resources
ModuleNotFoundError: No module named 'pkg_resources'

原因

核心原因就是虚拟环境里没有安装 setuptools 这个库,而它是 pkg_resources 模块的提供者。

这个问题的根源在于,较新版本的 Python(3.12+)在创建虚拟环境后,不再默认安装 setuptools。同时,setuptools 从 82.0.0 版本开始,也把 pkg_resources 模块彻底移除了。所以你不仅要安装它,还得安装一个低于 82.0.0 的版本。

方案:降级安装 setuptools

执行安装命令:在当前的 (.venv) 环境下,直接运行以下命令:

python -m pip install "setuptools<82.0.0" --force-reinstall

 

posted @ 2026-03-08 18:32  sunshine_coast  阅读(3)  评论(0)    收藏  举报