【写给自己】成功使用ResNet识别RML2018.a数据集

这篇具有很好参考价值的文章主要介绍了【写给自己】成功使用ResNet识别RML2018.a数据集。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

        源码来自[https://blog.csdn.net/qq_34467412/article/details/90738232],作者也是对论文作者ResNet框架的复现,而我是在chatGPT帮助下把博主TensorFlow的代码改成了pytorch代码。
        由于硬件限制,并没有使用完整的数据集,仅对前10种调制模型进行识别,全信噪比情况下测试集识别率可达72%;仅考虑0:30dB情况下测试集识别率可达94%。

训练过程

【写给自己】成功使用ResNet识别RML2018.a数据集,人工智能

测试集上的混淆矩阵

【写给自己】成功使用ResNet识别RML2018.a数据集,人工智能

不同信噪比下的识别率

【写给自己】成功使用ResNet识别RML2018.a数据集,人工智能

信噪比为0db时候的混淆矩阵

【写给自己】成功使用ResNet识别RML2018.a数据集,人工智能文章来源地址https://www.toymoban.com/news/detail-536586.html

网络部分

class ResidualStack(nn.Module):
    def __init__(self, input_channels, output_channels, kernel_size, seq, pool_size):
        super(ResidualStack, self).__init__()
        self.conv1 = nn.Conv2d(input_channels, output_channels, kernel_size=1, stride=1, padding='same') # (kernel_size-1)//2保证输入输出形状一样
        # Residual Unit 1
        self.conv2 = nn.Conv2d(output_channels, 32, kernel_size=kernel_size, stride=1, padding='same')
        self.conv3 = nn.Conv2d(32, output_channels, kernel_size=kernel_size, stride=1, padding='same')
        # Residual Unit 2
        self.conv4 = nn.Conv2d(output_channels, 32, kernel_size=kernel_size, stride=1, padding='same')
        self.conv5 = nn.Conv2d(32, output_channels, kernel_size=kernel_size, stride=1, padding='same')
        self.maxpool = nn.MaxPool2d(kernel_size=pool_size, stride=pool_size)
        self.seq = seq

    def forward(self, x):
        # Residual Unit 1
        x = self.conv1(x)
        shortcut = x
        x = self.conv2(x)
        x = F.relu(x)
        x = self.conv3(x)
        x = x + shortcut
        x = F.relu(x)
        # Residual Unit 2
        shortcut = x
        x = self.conv4(x)
        x = F.relu(x)
        x = self.conv5(x)
        x = x + shortcut
        x = F.relu(x)
        x = self.maxpool(x)
        return x

class MyResNet(nn.Module):          # 1,1024,2
    def __init__(self, num_classes):
        super(MyResNet, self).__init__()
        self.num_classes = num_classes
        # self.bn = nn.BatchNorm2d(1)
        self.seq1 = ResidualStack(1, 32, kernel_size=(3, 2), seq="ReStk0", pool_size=(2, 2))
        self.seq2 = ResidualStack(32, 32, kernel_size=(3, 1), seq="ReStk1", pool_size=(2, 1))
        self.seq3 = ResidualStack(32, 32, kernel_size=(3, 1), seq="ReStk2", pool_size=(2, 1))
        self.seq4 = ResidualStack(32, 32, kernel_size=(3, 1), seq="ReStk3", pool_size=(2, 1))
        self.seq5 = ResidualStack(32, 32, kernel_size=(3, 1), seq="ReStk4", pool_size=(2, 1))
        self.seq6 = ResidualStack(32, 32, kernel_size=(3, 1), seq="ReStk5", pool_size=(2, 1))
        self.fc1 = nn.Linear(512, 128)           # 64 rml, 192 mnist, 512 rml2018
        self.fc2 = nn.Linear(128, num_classes)
        self.dropout = nn.AlphaDropout(0.2)

    def forward(self, x):
        # x = self.bn(x)
        x = self.seq1(x)
        x = self.seq2(x)
        x = self.seq3(x)
        x = self.seq4(x)
        x = self.seq5(x)
        x = self.seq6(x)
        x = torch.flatten(x,start_dim=1)
        x = self.fc1(x)
        x = F.selu(x)
        x = self.dropout(x)
        x = self.fc2(x)
        return x

 混淆矩阵代码

def plot_confusion_matrix(dataloader, model, classes):
    # pre-progression
    num_classes = len(classes)
    matrix = torch.zeros(size=(num_classes,num_classes))
    for x, y in dataloader:
        y_pred = model(x)
        for i in range(y.size(0)):
            matrix[y_pred[i].argmax()][y[i].argmax()] += 1
    for i in range(0, num_classes):
        matrix[i, :] = matrix[i, :] / torch.sum(matrix[i, :])
    # configuration of plot
    plt.figure(figsize=(10, 10))
    plt.imshow(matrix, interpolation='nearest', cmap=plt.cm.Blues)
    # interpolation插值影响图像显示效果
    tick_marks = np.arange(num_classes)
    plt.xticks(tick_marks, classes, rotation=45)
    plt.yticks(tick_marks, classes)
    plt.tight_layout()
    plt.title('Confusion Matrix')
    plt.colorbar()
    plt.xlabel('Predicted label')
    plt.ylabel('True label')
    plt.show()

    return matrix

 信噪比准确率,信噪比混淆矩阵代码

def plot_snr_curves(x, y, snr, model, classes):

    if not x[0].is_cuda:
        model.cpu()

    num_classes = len(classes)
    snr = snr.reshape((len(snr)))
    snrs, counts = np.unique(snr, return_counts=True)
    num_snrs = len(snrs)
    acc = np.zeros(num_snrs)
    matrix = torch.zeros(size=(num_snrs, num_classes, num_classes))
    for i in range(num_snrs):
        x_snr = x[snr==snrs[i]]
        y_snr = y[snr==snrs[i]]

        temp_dataset = Data.TensorDataset(x_snr, y_snr)
        temp_dataloader = DataLoader(dataset=temp_dataset, batch_size=256)

        for temp_x, temp_y in temp_dataloader:
            y_pred = model(temp_x)
            acc[i] += (y_pred.argmax(1) == temp_y.argmax(1)).sum()

            for k in range(temp_y.size(0)):
                matrix[i][y_pred[k].argmax()][temp_y[k].argmax()] += 1

    acc = acc / counts

    plt.plot(snrs, acc)
    plt.xlabel('SNR')
    plt.ylabel('Acc')
    plt.show()

    plt.figure(figsize=(10, 10))
    plt.imshow(matrix[0][:][:], interpolation='nearest', cmap=plt.cm.Blues)
    # interpolation插值影响图像显示效果
    tick_marks = np.arange(num_classes)
    plt.xticks(tick_marks, classes, rotation=45)
    plt.yticks(tick_marks, classes)
    plt.tight_layout()
    plt.title('Confusion Matrix SNR 0dB')
    plt.colorbar()
    plt.xlabel('Predicted label')
    plt.ylabel('True label')
    plt.show()
    return matrix

重新配置信号的label

def select(y, classes, classes_included=True):
    temp = y.sum(axis=0)
    one_zero = (temp >= 1)                              # 哪些地方是label的
    index = [i for i, x in enumerate(one_zero) if x]    # 得到label的位置
    new_classes = []
    new_num_classes = one_zero.sum()
    for i in range(new_num_classes):
        new_classes.append(classes[index[i]])

    new_y = np.zeros((y.shape[0], new_num_classes))
    y_index = y.argmax(1)                               # y=1的位置
    for i in range(y_index.shape[0]):
        new_y[i][y_index[i]] = 1

    if classes_included:
        return new_y, new_classes
    else:
        return new_y

训练和测试代码

def train(model, train_dataloader, itr, optimizer, loss_func):
    start_time = time.time()
    train_loss = 0
    train_accuracy = 0
    model.train()
    for x, y in train_dataloader:

        optimizer.zero_grad()       # 梯度清零
        y_pred = model(x)           # 计算预测标签
        loss = loss_func(y_pred, y.argmax(dim=1))  # 计算损失, argmax() for one-hot
        loss.backward()             # 利用反向传播计算gradients
        optimizer.step()            # 利用gradients更新参数值
        train_accuracy += (y_pred.argmax(1) == y.argmax(1)).sum()

        train_loss += loss.item()
    ep_loss = train_loss / len(train_dataloader.dataset)
    ep_train_acc = train_accuracy / len(train_dataloader.dataset)
    end_time = time.time()
    print("Epoch:", itr + 1,
          "\nTraining Loss: ", round(ep_loss,5),
          "Training Accuracy: ", round(ep_train_acc.item(), 5))
    print("Training time consuming: {}".format(end_time-start_time))
    return ep_loss, ep_train_acc

def test(model,test_dataloader):
    # test
    test_accuracy = 0
    model.eval()
    for x, y in test_dataloader:
        y_pred = model(x)
        test_accuracy += (y_pred.argmax(1) == y.argmax(1)).sum()

    ep_test_acc = test_accuracy / len(test_dataloader.dataset)
    print("Test Accuracy: ", round(ep_test_acc.item(),5))

    return ep_test_acc

主程序

if __name__ == "__main__":
    # Running Time
    time = datetime.datetime.now()
    month = time.month
    day = time.day

    # Configuration

    device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')

    # File path
    path = 'data/SNR_greater_0_10data/'
    x_train, x_test, y_train, y_test = np.load(path + 'X_train.npy'), np.load(path + 'X_test.npy'), np.load(path + 'Y_train.npy'), np.load(path + 'Y_test.npy')
    y_train, classes = select(y_train, classes)
    y_test = select(y_test, classes, False)
    x_train, x_test, y_train, y_test = torch.from_numpy(x_train), torch.from_numpy(x_test), torch.from_numpy(y_train), torch.from_numpy(y_test)
    x_train, x_test, y_train, y_test = x_train.to(device), x_test.to(device), y_train.to(device), y_test.to(device)

    num_classes = len(classes)
    train_mean, train_std = torch.mean(x_train), torch.std(x_train)
    test_mean, test_std = torch.mean(x_test), torch.std(x_test)

    train_transformer = transforms.Compose([
        transforms.Normalize(mean=train_mean, std=train_std),
    ])
    test_transformer = transforms.Compose([
        transforms.Normalize(mean=test_mean, std=test_std),
    ])

    x_train = train_transformer(x_train)
    x_test = test_transformer(x_test)
    x_train = resize(x_train, (x_train.shape[0], 1, 1024, 2))
    x_test = resize(x_test, (x_test.shape[0], 1, 1024, 2))
    print("Shape of x_train : {}".format(x_train.shape))

    train_dataset = Data.TensorDataset(x_train, y_train)
    train_dataloader = DataLoader(dataset=train_dataset,batch_size=256, shuffle=True)
    test_dataset = Data.TensorDataset(x_test, y_test)
    test_dataloader = DataLoader(dataset=test_dataset, batch_size=256, shuffle=True)

    # Model
    model = MyResNet(num_classes).to(device)
    loss_function = nn.CrossEntropyLoss()
    optimizer = torch.optim.Adam(model.parameters(), lr=0.005)
    lr_scheduler = torch.optim.lr_scheduler.StepLR(optimizer, step_size=50, gamma=0.1)  # step decay

    itrs = 100
    train_loss = []
    train_acc = []
    test_acc = []
    best_accuracy = 0

    print("start training")
    for itr in range(itrs):
        epoch_loss, epoch_train_acc = train(model, train_dataloader, itr, optimizer, loss_function)
        epoch_test_acc = test(model, test_dataloader)
        train_loss.append(epoch_loss)
        train_acc.append(epoch_train_acc)
        test_acc.append(epoch_test_acc)

        # Save best model on test data
        if epoch_test_acc > best_accuracy:
            best_accuracy = epoch_test_acc
            torch.save(model, path + "ResNet_Identification_best_{}month_{}day.pth".format(month,day))
            print("-----The best accuracy now is {}-----".format(best_accuracy))
            print("-----The best model until now has been saved-----")
        lr_scheduler.step()

    confusion_matrix = plot_confusion_matrix(test_dataloader, model, classes)
    # Accuracy and Loss
    train_acc = [tensor.item() for tensor in train_acc]
    test_acc = [tensor.item() for tensor in test_acc]
    fig, ax1 = plt.subplots()
    ax2 = ax1.twinx()
    x = range(itrs)
    ax1.plot(x, train_loss, label='train_loss')
    ax2.plot(x, train_acc, label='train_acc')
    ax2.plot(x, test_acc, label='test_acc')

    ax1.set_xlabel('Iteration')
    ax1.set_ylabel('Loss')
    ax2.set_ylabel('Accuracy')
    plt.legend()
    plt.show()

到了这里,关于【写给自己】成功使用ResNet识别RML2018.a数据集的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • U盘无法识别,在别人电脑能使用,自己无法使用

    1 供电不足 请将U盘换口,如果是台式机,请插机箱后面 2 无驱动 请检查是否无驱动,特别是老电脑,在设备管理里查看是否打问号,如果出现这种情况,请卸载设备,并重新插拔 3 其他设备 这种情况多出现于U盘在别人电脑能使用,自己无法使用。如果在设别管理器里发现这

    2024年02月11日
    浏览(17)
  • YOLOv5训练自己的数据集实现视频的识别

    写在前面 我本来是使用这个模型进行手写签名的定位,但是因为比赛的主办方原因,数据不允许公开,所以我使用动物世界的一段开头视屏来制作我的数据集。这整个模型跑通的过程中,我参考了很多不错的博客,写这篇博客的原因是记录一下我的所见所感。我的模型是在

    2024年02月02日
    浏览(41)
  • 基于Stanford Cars的ResNet和GoogLeNet图像识别

    这是一个使用斯坦福汽车数据集进行汽车分类的深度学习项目。我将使用迁移学习在ImageNet上预训练的深度网络,并对数据集进行微调,为了减少训练时间我把数据集。 数据来源:https://ai.stanford.edu/~jkrause/cars/car_dataset.html 斯坦福汽车数据集包含 195 类汽车的 16,185 张图像。数

    2024年02月11日
    浏览(17)
  • 【ResNet18】on IEMOCAP—语音情感识别(预处理篇)

    在开始模型训练前,一定要对数据处理熟悉!   一、预处理: 1、IEMOCAP语音数据部分 按照人(1F,1M,2F,2M,3F,3M,4F,4M,5F,5M): ang有语音数量:[147, 82, 67, 70, 92, 148, 205, 122, 78, 92] exc有语音数量:[63, 80, 96, 114, 48, 103, 154, 84, 82, 217] hap有语音数量:[69, 66, 70, 47, 80, 55, 31, 34, 77, 66] neu有语

    2024年02月08日
    浏览(16)
  • 手写数学公式识别领域最新论文CAN代码梳理,以及用自己的数据集训练

    Counting-Aware Network(CAN)-手写数学公式识别网络是好未来与白翔团队一起发布的一篇2022年的被ECCV收录的论文,该论文旨在缓解目前大部分基于注意力机制的手写数学公式识别算法在处理较长或者空间结构较复杂的数学公式时,容易出现的注意力不准确的情况。该论文通过将符号

    2024年02月07日
    浏览(14)
  • 计算机视觉的应用8-基于ResNet50对童年数码宝贝的识别与分类

    大家好,我是微学AI,今天给大家介绍一下计算机视觉的应用8-基于ResNet50对童年数码宝贝的识别与分类,想必做完90后的大家都看过数码宝贝吧,里面有好多类型的数码宝贝,今天就给大家简单实现一下,他们的分类任务。 引言 ResNet50模型简介 ResNet50模型原理 ResNet50模型的应

    2024年04月28日
    浏览(17)
  • 使用OpenCV工具包成功实现人脸检测与人脸识别,包括传统视觉和深度学习方法(附完整代码,吐血整理......)

    要实现人脸识别功能,首先要进行人脸检测,判断出图片中人脸的位置,才能进行下一步的操作。 参考链接: 1、OpenCV人脸检测 2、【OpenCV-Python】32.OpenCV的人脸检测和识别——人脸检测 3、【youcans 的图像处理学习课】23. 人脸检测:Haar 级联检测器 4、OpenCV实战5:LBP级联分类器

    2024年02月12日
    浏览(16)
  • 使用OpenCV工具包成功实现人脸检测与人脸识别,包括传统视觉和深度学习方法(附完整代码,模型下载......)

    要实现人脸识别功能,首先要进行人脸检测,判断出图片中人脸的位置,才能进行下一步的操作。 参考链接: 1、OpenCV人脸检测 2、【OpenCV-Python】32.OpenCV的人脸检测和识别——人脸检测 3、【youcans 的图像处理学习课】23. 人脸检测:Haar 级联检测器 4、OpenCV实战5:LBP级联分类器

    2024年02月08日
    浏览(20)
  • win下YOLOv7训练自己的数据集(交通标志TT100K识别)

    预测结果: 数据集的准备包括数据集适配YOLO格式的重新分配以及相应配置文件的书写,此处可查看博主的TT100K2yolo的重新分配博文,该文章包括数据集划分,配置文件书写,以及最终的数据集层级目录组织,可以直接提供给下一步进行训练。 需要注意的是数据集的yaml文件有

    2024年02月06日
    浏览(21)
  • 视频与AI,与进程交互(二) pytorch 极简训练自己的数据集并识别

    检测出已经分割出的图像的分类 pytorch 非常简单就可以做到训练和加载 如上图所示,用来训练的文件放在了train中,验证的文件放在val中,train.txt 和 val.txt 分别放文件名称和分类类别,然后我们在代码中写名字就行 里面我就为了做一个例子,放了两种文件,1 是 卡宴保时捷

    2024年02月10日
    浏览(19)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包