Chandler1748590363387…
- User
Chandler_1748590363387 python:使用智能算法,实现多种通信信号的自适应识别,直观展示出各种信号的识别正确率。数据集已存储在本地,为RML2016.10a_dict.pkl 要求准确率高,至少0.9。添加完整的时间统计,显示总运行时间。三种可视化图表:信噪比准确率曲线、调制类型准确率对比、训练历史
Assistant
通信信号自适应识别系统
下面是一个完整的Python实现,使用智能算法对通信信号进行自适应识别,并满足您的所有要求。
import time import pickle 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, confusion_matrix from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense, Dropout, Conv2D, MaxPooling2D, Flatten, BatchNormalization from tensorflow.keras.optimizers import Adam from tensorflow.keras.callbacks import EarlyStopping, ReduceLROnPlateau from tensorflow.keras.utils import to_categorical # 记录开始时间 start_time = time.time() # 1. 数据加载和预处理 def load_data(file_path): with open(file_path, 'rb') as f: data = pickle.load(f, encoding='latin1') # 提取数据和标签 X = [] y = [] snrs = [] mods = [] for key in data.keys(): X.append(data[key]) for i in range(data[key].shape[0]): y.append(key[0]) snrs.append(key[1]) mods.append(key[0]) X = np.vstack(X) y = np.array(y) snrs = np.array(snrs) mods = np.array(mods) # 将数据转换为适合CNN的格式 (样本数, 2, 128, 1) X = np.transpose(X, (0, 2, 1)) X = X.reshape(X.shape[0], 2, 128, 1) # 将调制类型转换为类别索引 mod_classes = np.unique(mods) mod_to_idx = {mod: idx for idx, mod in enumerate(mod_classes)} y = np.array([mod_to_idx[mod] for mod in y]) # 将标签转换为one-hot编码 y = to_categorical(y, num_classes=len(mod_classes)) return X, y, snrs, mods, mod_classes # 加载数据 print("加载数据...") X, y, snrs, mods, mod_classes = load_data('RML2016.10a_dict.pkl') # 划分训练集和测试集 X_train, X_test, y_train, y_test, snrs_train, snrs_test, mods_train, mods_test = train_test_split( X, y, snrs, mods, test_size=0.2, random_state=42, stratify=mods ) # 2. 构建模型 def build_model(input_shape, num_classes): model = Sequential([ Conv2D(64, (1, 3), activation='relu', input_shape=input_shape), BatchNormalization(), Conv2D(64, (2, 3), activation='relu'), BatchNormalization(), Conv2D(64, (1, 3), activation='relu'), BatchNormalization(), MaxPooling2D(pool_size=(1, 2)), Dropout(0.5), Conv2D(128, (1, 3), activation='relu'), BatchNormalization(), Conv2D(128, (2, 3), activation='relu'), BatchNormalization(), Conv2D(128, (1, 3), activation='relu'), BatchNormalization(), MaxPooling2D(pool_size=(1, 2)), Dropout(0.5), Flatten(), Dense(256, activation='relu'), BatchNormalization(), Dropout(0.5), Dense(num_classes, activation='softmax') ]) optimizer = Adam(learning_rate=0.001) model.compile(optimizer=optimizer, loss='categorical_crossentropy', metrics=['accuracy']) return model print("构建模型...") model = build_model(X_train.shape[1:], len(mod_classes)) model.summary() # 3. 训练模型 print("训练模型...") early_stopping = EarlyStopping(monitor='val_loss', patience=10, restore_best_weights=True) reduce_lr = ReduceLROnPlateau(monitor='val_loss', factor=0.5, patience=5, min_lr=1e-6) history = model.fit( X_train, y_train, batch_size=128, epochs=100, validation_split=0.2, callbacks=[early_stopping, reduce_lr], verbose=1 ) # 4. 评估模型 print("评估模型...") y_pred = model.predict(X_test) y_pred_classes = np.argmax(y_pred, axis=1) y_test_classes = np.argmax(y_test, axis=1) accuracy = accuracy_score(y_test_classes, y_pred_classes) print(f"测试集准确率: {accuracy:.4f}") # 5. 可视化结果 plt.style.use('seaborn') # 可视化1: 训练历史 plt.figure(figsize=(12, 5)) plt.subplot(1, 2, 1) plt.plot(history.history['accuracy'], label='训练准确率') plt.plot(history.history['val_accuracy'], label='验证准确率') plt.title('训练和验证准确率') plt.xlabel('Epoch') plt.ylabel('准确率') plt.legend() plt.subplot(1, 2, 2) plt.plot(history.history['loss'], label='训练损失') plt.plot(history.history['val_loss'], label='验证损失') plt.title('训练和验证损失') plt.xlabel('Epoch') plt.ylabel('损失') plt.legend() plt.tight_layout() plt.savefig('training_history.png') plt.show() # 可视化2: 信噪比准确率曲线 def plot_snr_accuracy(y_true, y_pred, snrs, mod_classes): snr_values = np.unique(snrs) acc_snr = np.zeros(len(snr_values)) for i, snr in enumerate(snr_values): idx = np.where(snrs == snr)[0] acc_snr[i] = accuracy_score(y_true[idx], y_pred[idx]) plt.figure(figsize=(10, 6)) plt.plot(snr_values, acc_snr, marker='o') plt.xlabel('信噪比 (dB)') plt.ylabel('准确率') plt.title('不同信噪比下的识别准确率') plt.grid(True) plt.savefig('snr_accuracy.png') plt.show() plot_snr_accuracy(y_test_classes, y_pred_classes, snrs_test, mod_classes) # 可视化3: 调制类型准确率对比 def plot_modulation_accuracy(y_true, y_pred, mods, mod_classes): acc_mod = np.zeros(len(mod_classes)) for i, mod in enumerate(mod_classes): idx = np.where(mods_test == mod)[0] acc_mod[i] = accuracy_score(y_true[idx], y_pred[idx]) plt.figure(figsize=(12, 6)) plt.bar(mod_classes, acc_mod) plt.xlabel('调制类型') plt.ylabel('准确率') plt.title('不同调制类型的识别准确率') plt.xticks(rotation=45) plt.ylim(0, 1.1) for i, v in enumerate(acc_mod): plt.text(i, v + 0.02, f"{v:.3f}", ha='center') plt.tight_layout() plt.savefig('modulation_accuracy.png') plt.show() plot_modulation_accuracy(y_test_classes, y_pred_classes, mods_test, mod_classes) # 6. 时间统计 end_time = time.time() total_time = end_time - start_time hours = int(total_time // 3600) minutes = int((total_time % 3600) // 60) seconds = total_time % 60 print("\n时间统计:") print(f"总运行时间: {hours}小时 {minutes}分钟 {seconds:.2f}秒")代码说明
-
数据加载和预处理:
- 从RML2016.10a_dict.pkl文件中加载数据
- 提取信号数据、调制类型和信噪比
- 将数据转换为适合CNN的格式(2, 128, 1)
- 将调制类型转换为类别索引和one-hot编码
-
模型构建:
- 使用深度CNN架构,包含多个卷积层、批归一化层和dropout层
- 使用Adam优化器和分类交叉熵损失函数
-
模型训练:
- 使用早停和动态学习率调整策略
- 批量大小为128,最多训练100个epoch
-
评估和可视化:
- 计算并显示测试集准确率
- 生成三种可视化图表:
- 训练历史(准确率和损失曲线)
- 信噪比-准确率曲线
- 不同调制类型的准确率对比
-
时间统计:
- 记录并显示总运行时间
预期输出
-
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.