特征可视化
对于卷积神经网络,你可以可视化卷积层的滤波器(filter)以及它们在输入信号上的响应。这可以帮助你理解网络是如何学习特征的。
# 获取卷积层的输出
layer_outputs = [layer.output for layer in model.layers if isinstance(layer, Conv1D)]
activation_model = Model(inputs=model.input, outputs=layer_outputs)
activations = activation_model.predict(sample_data)
# 可视化卷积层的输出
layer_names = [layer.name for layer in model.layers if isinstance(layer, Conv1D)]
for layer_name, activation in zip(layer_names, activations):
plt.figure(figsize=(8, 4))
for i in range(activation.shape[-1]):
plt.plot(activation[0, :, i], label=f'Filter {i + 1}')
plt.title(f'Activation of {layer_name}')
plt.legend()
plt.show()
样本预测可视化
随机选择一些测试集样本,将模型的预测结果与真实标签进行对比。
import random
# 随机选择一些测试样本
sample_indices = random.sample(range(len(X_test)), 5)
for index in sample_indices:
# 获取单个测试样本
sample_data = X_test[index].reshape(1, -1, 1)
true_label = label_encoder.inverse_transform([y_true_classes[index]])[0]
# 进行预测
predicted_probs = model.predict(sample_data)
predicted_label = label_encoder.classes_[np.argmax(predicted_probs)]
# 可视化
plt.figure(figsize=(8, 4))
plt.plot(sample_data[0], label='Signal')
plt.title(f'True Label: {true_label}, Predicted Label: {predicted_label}')
plt.legend()
plt.show()
分类报告
使用sklearn
库中的classification_report
可以生成每个类别的精确度、召回率和 F1 分数等指标。
from sklearn.metrics import classification_report
# ...(前面的代码)
# 生成分类报告
report = classification_report(y_true_classes, y_pred_classes, target_names=label_encoder.classes_)
print(report)
混淆矩阵热图
import seaborn as sns
import matplotlib.pyplot as plt
# ...(前面的代码)
# 计算混淆矩阵
confusion_mtx = confusion_matrix(y_true_classes, y_pred_classes)
# 可视化混淆矩阵
plt.figure(figsize=(10, 8))
sns.heatmap(confusion_mtx, annot=True, fmt='d', cmap='Blues', xticklabels=label_encoder.classes_, yticklabels=label_encoder.classes_)
plt.xlabel('Predicted Label')
plt.ylabel('True Label')
plt.title('Confusion Matrix')
plt.show()