import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, confusion_matrix
from tensorflow.keras.utils import to_categorical
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Dropout
from tensorflow.keras.callbacks import EarlyStopping
import os
# 定义输出目录
output_dir = '二维数据特征提取实验/GADF-CNN'
os.makedirs(output_dir, exist_ok=True) # 创建目录(如果不存在)
plt.rcParams['font.family'] = 'sans-serif'
plt.rcParams['font.sans-serif'] = ['GB_HT_GBT2312']
plt.rcParams['axes.unicode_minus'] = False # 用来正常显示负号
# 设置随机种子
np.random.seed(42)
# 参数设置
n_samples = 1000 # 样本数量
n_timesteps = 100 # 每个样本的时间步数
n_classes = 2 # 类别数量
# 生成随机时间序列数据和标签
X = np.random.randn(n_samples, n_timesteps) # 生成随机时间序列数据
y = np.random.randint(0, n_classes, n_samples) # 生成随机标签
# 计算GADF特征图的函数
def gramian_angular_difference_field(signal):
# 归一化信号到[-1, 1]
signal = (signal - np.min(signal)) / (np.max(signal) - np.min(signal)) * 2 - 1
# 计算GADF
cos_sum = np.cos(np.outer(signal, signal))
sin_diff = np.sin(np.outer(signal, signal))
gadf = cos_sum * sin_diff
return gadf
# 计算GADF特征图
X_gadf = np.array([gramian_angular_difference_field(signal) for signal in X])
X_gadf = X_gadf[:, :, :, np.newaxis] # 增加一个维度以适应CNN输入
# 将标签进行one-hot编码,并将数据集划分为训练集和测试集
y_one_hot = to_categorical(y, num_classes=n_classes)
X_train, X_test, y_train, y_test = train_test_split(X_gadf, y_one_hot, test_size=0.2, random_state=42)
# 构建CNN模型
model = Sequential([
Conv2D(32, (3, 3), activation='relu', input_shape=(X_gadf.shape[1], X_gadf.shape[2], 1)), # 第一层卷积层
MaxPooling2D((2, 2)), # 最大池化层
Conv2D(64, (3, 3), activation='relu'), # 第二层卷积层
MaxPooling2D((2, 2)), # 最大池化层
Flatten(), # 展平层
Dense(128, activation='relu'), # 全连接层
Dropout(0.5), # Dropout层,防止过拟合
Dense(n_classes, activation='softmax') # 输出层,使用softmax激活函数
])
# 编译模型
model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])
model.summary() # 打印模型结构
# 设置EarlyStopping回调函数
early_stopping = EarlyStopping(monitor='val_loss', patience=5, restore_best_weights=True)
# 训练模型
history = model.fit(X_train, y_train, epochs=50, batch_size=32, validation_split=0.2, callbacks=[early_stopping])
# 评估模型
y_pred = model.predict(X_test)
y_pred_classes = np.argmax(y_pred, axis=1) # 预测的类别
y_true_classes = np.argmax(y_test, axis=1) # 真实的类别
# 计算评估指标
accuracy = accuracy_score(y_true_classes, y_pred_classes)
precision = precision_score(y_true_classes, y_pred_classes, average='weighted')
recall = recall_score(y_true_classes, y_pred_classes, average='weighted')
f1 = f1_score(y_true_classes, y_pred_classes, average='weighted')
# 打印评估结果
print(f"Accuracy: {accuracy:.4f}")
print(f"Precision: {precision:.4f}")
print(f"Recall: {recall:.4f}")
print(f"F1 Score: {f1:.4f}")
# 将统计结果写入txt文件
with open(os.path.join(output_dir, 'metrics.txt'), 'w') as f:
f.write(f"Accuracy: {accuracy}\n")
f.write(f"Precision: {precision}\n")
f.write(f"Recall: {recall}\n")
f.write(f"F1 Score: {f1}\n")
# 生成混淆矩阵
conf_matrix = confusion_matrix(y_true_classes, y_pred_classes)
plt.figure(figsize=(6, 6))
sns.heatmap(conf_matrix, annot=True, fmt='d', cmap='Blues', xticklabels=range(n_classes), yticklabels=range(n_classes))
plt.xlabel('Predicted')
plt.ylabel('True')
plt.title('GASF-CNN-混淆矩阵')
plt.savefig(os.path.join(output_dir, 'DASF-CNN-confusion_matrix.png'))
plt.show()修改上述代码,使用多模态融合的方式改进GADF,将GADF与MTF结合,增强特征表达能力,将生成的GADF和MTF图像,拼接或堆叠作为多通道输入。输出完整代码。