文章目录
- Github
- 官网
- 文档
- 简介
- 动态显示训练过程中的数据和模型的决策边界
- 安装
- 源码
Github
- https://github.com/matplotlib/matplotlib
官网
- https://matplotlib.org/stable/
文档
- https://matplotlib.org/stable/api/index.html
简介
matplotlib 是 Python 中最常用的绘图库之一,用于创建各种类型的静态、动态和交互式可视化。
动态显示训练过程中的数据和模型的决策边界
安装
pip install tensorflow==2.13.1
pip install matplotlib==3.7.5
pip install numpy==1.24.3
源码
import numpy as np
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap# 生成数据
np.random.seed(0)
num_samples_per_class = 500
negative_samples = np.random.multivariate_normal(mean=[0, 3],cov=[[1, 0.5], [0.5, 1]],size=num_samples_per_class
)
positive_samples = np.random.multivariate_normal(mean=[3, 0],cov=[[1, 0.5], [0.5, 1]],size=num_samples_per_class
)inputs = np.vstack((negative_samples, positive_samples)).astype(np.float32)
targets = np.vstack((np.zeros((num_samples_per_class, 1)), np.ones((num_samples_per_class, 1)))).astype(np.float32)# 将数据分为训练集和测试集
train_size = int(0.8 * len(inputs))
X_train, X_test = inputs[:train_size], inputs[train_size:]
y_train, y_test = targets[:train_size], targets[train_size:]# 构建二分类模型
model = Sequential([# 输入层:输入形状为 (2,)# 第一个隐藏层:包含 4 个节点,激活函数使用 ReLUDense(4, activation='relu', input_shape=(2,)),# 输出层:包含 1 个节点,激活函数使用 Sigmoid(因为是二分类问题)Dense(1, activation='sigmoid')
])# 编译模型
# 指定优化器为 Adam,损失函数为二分类交叉熵,评估指标为准确率
model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])# 准备绘图
fig, ax = plt.subplots()
cmap_light = ListedColormap(['#FFAAAA', '#AAAAFF'])
cmap_bold = ListedColormap(['#FF0000', '#0000FF'])# 动态绘制函数
def plot_decision_boundary(epoch, logs):ax.clear()x_min, x_max = X_train[:, 0].min() - 1, X_train[:, 0].max() + 1y_min, y_max = X_train[:, 1].min() - 1, X_train[:, 1].max() + 1xx, yy = np.meshgrid(np.arange(x_min, x_max, 0.1),np.arange(y_min, y_max, 0.1))grid = np.c_[xx.ravel(), yy.ravel()]probs = model.predict(grid).reshape(xx.shape)ax.contourf(xx, yy, probs, alpha=0.8, cmap=cmap_light)ax.scatter(X_train[:, 0], X_train[:, 1], c=y_train[:, 0], edgecolor='k', cmap=cmap_bold)ax.set_title(f'Epoch {epoch+1}')plt.draw()plt.pause(0.01)# 自定义回调函数
class PlotCallback(tf.keras.callbacks.Callback):def on_epoch_end(self, epoch, logs=None):plot_decision_boundary(epoch, logs)# 训练模型并动态显示
plot_callback = PlotCallback()
model.fit(X_train, y_train, epochs=50, batch_size=16, callbacks=[plot_callback])# 评估模型
loss, accuracy = model.evaluate(X_test, y_test)
print(f"Test Loss: {loss}")
print(f"Test Accuracy: {accuracy}")plt.show()