基于pytorch代价敏感平衡一维ICIIDS-2017数据集并用cnn训练的代码

时间: 2024-01-12 10:05:30 浏览: 22
以下是基于PyTorch代价敏感平衡一维ICIIDS-2017数据集并使用CNN训练的代码示例: ```python import torch import torch.nn as nn import torch.optim as optim from torch.utils.data import DataLoader, TensorDataset import numpy as np import pandas as pd #加载数据集 train_data = pd.read_csv('train_data.csv') test_data = pd.read_csv('test_data.csv') #将数据集转换为numpy数组 train_data = train_data.values test_data = test_data.values #将数据集按标签分为攻击和正常 train_attack = train_data[train_data[:, -1] == 1] train_normal = train_data[train_data[:, -1] == 0] test_attack = test_data[test_data[:, -1] == 1] test_normal = test_data[test_data[:, -1] == 0] #计算代价敏感权重 num_attack_train = train_attack.shape[0] num_normal_train = train_normal.shape[0] num_total_train = num_attack_train + num_normal_train weight_normal = num_total_train / (2 * num_normal_train) weight_attack = num_total_train / (2 * num_attack_train) class_weight = torch.FloatTensor([weight_normal, weight_attack]) #将数据集转换为PyTorch张量 train_data_tensor = torch.FloatTensor(train_data[:, :-1]) train_label_tensor = torch.LongTensor(train_data[:, -1]) test_data_tensor = torch.FloatTensor(test_data[:, :-1]) test_label_tensor = torch.LongTensor(test_data[:, -1]) #创建数据集和数据加载器 train_dataset = TensorDataset(train_data_tensor, train_label_tensor) test_dataset = TensorDataset(test_data_tensor, test_label_tensor) train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True) test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False) #定义CNN模型 class CNN(nn.Module): def __init__(self): super(CNN, self).__init__() self.conv1 = nn.Conv1d(in_channels=1, out_channels=32, kernel_size=3, stride=1) self.conv2 = nn.Conv1d(in_channels=32, out_channels=64, kernel_size=3, stride=1) self.pool = nn.MaxPool1d(kernel_size=2) self.fc1 = nn.Linear(64*23, 128) self.fc2 = nn.Linear(128, 2) self.dropout = nn.Dropout(p=0.5) self.relu = nn.ReLU() def forward(self, x): x = self.conv1(x) x = self.relu(x) x = self.pool(x) x = self.conv2(x) x = self.relu(x) x = self.pool(x) x = x.view(-1, 64*23) x = self.fc1(x) x = self.relu(x) x = self.dropout(x) x = self.fc2(x) return x #实例化模型、损失函数和优化器 model = CNN() criterion = nn.CrossEntropyLoss(weight=class_weight) optimizer = optim.Adam(model.parameters(), lr=0.001) #训练模型 for epoch in range(50): model.train() train_loss = 0.0 train_correct = 0 for data, label in train_loader: optimizer.zero_grad() output = model(data.unsqueeze(1)) loss = criterion(output, label) loss.backward() optimizer.step() train_loss += loss.item() _, pred = torch.max(output, 1) train_correct += (pred == label).sum().item() train_acc = train_correct / num_total_train train_loss /= len(train_loader) #在测试集上评估模型 model.eval() test_loss = 0.0 test_correct = 0 with torch.no_grad(): for data, label in test_loader: output = model(data.unsqueeze(1)) loss = criterion(output, label) test_loss += loss.item() _, pred = torch.max(output, 1) test_correct += (pred == label).sum().item() test_acc = test_correct / test_data.shape[0] test_loss /= len(test_loader) #输出训练和测试结果 print('Epoch: {}, Train Loss: {:.4f}, Train Acc: {:.4f}, Test Loss: {:.4f}, Test Acc: {:.4f}'.format(epoch+1, train_loss, train_acc, test_loss, test_acc)) ``` 在这个示例中,我们首先加载数据集并按标签分为攻击和正常。然后,我们计算代价敏感权重,将数据集转换为PyTorch张量,并创建数据集和数据加载器。接下来,我们定义了一个简单的CNN模型,并实例化了模型、损失函数和优化器。最后,我们使用训练和测试数据集训练模型,并输出训练和测试结果。

相关推荐

最新推荐

recommend-type

PyTorch版YOLOv4训练自己的数据集—基于Google Colab

Google Colaboratory是谷歌开放的一款研究工具,主要用于机器学习的开发和研究。 工具优势:Google Colab最大的好处是给广大的AI开发者提供了免费的GPU使用。你可以在上面轻松地跑例如:Keras、Tensorflow、Pytorch...
recommend-type

用Pytorch训练CNN(数据集MNIST,使用GPU的方法)

今天小编就为大家分享一篇用Pytorch训练CNN(数据集MNIST,使用GPU的方法),具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
recommend-type

基于pytorch的UNet_demo实现及训练自己的数据集.docx

基于pytorch的UNet分割网络demo实现,及训练自己的数据集。包括对相关报错的分析。收集了几个比较好的前辈的网址。
recommend-type

pytorch 语义分割-医学图像-脑肿瘤数据集的载入模块

由于最近目标是完成基于深度学习的脑肿瘤语义分割实验,所以需要用到自定义的数据载入,本文参考了一下博客:https://blog.csdn.net/tuiqdymy/article/details/84779716?utm_source=app,一开始是做的眼底图像分割,...
recommend-type

pytorch学习教程之自定义数据集

自定义数据集 在训练深度学习模型之前,样本集的制作非常重要。在pytorch中,提供了一些接口和类,方便我们定义自己的数据集合,下面完整的试验自定义样本... data/train——训练集 data/val——–验证集 在test/tra
recommend-type

zigbee-cluster-library-specification

最新的zigbee-cluster-library-specification说明文档。
recommend-type

管理建模和仿真的文件

管理Boualem Benatallah引用此版本:布阿利姆·贝纳塔拉。管理建模和仿真。约瑟夫-傅立叶大学-格勒诺布尔第一大学,1996年。法语。NNT:电话:00345357HAL ID:电话:00345357https://theses.hal.science/tel-003453572008年12月9日提交HAL是一个多学科的开放存取档案馆,用于存放和传播科学研究论文,无论它们是否被公开。论文可以来自法国或国外的教学和研究机构,也可以来自公共或私人研究中心。L’archive ouverte pluridisciplinaire
recommend-type

实现实时数据湖架构:Kafka与Hive集成

![实现实时数据湖架构:Kafka与Hive集成](https://img-blog.csdnimg.cn/img_convert/10eb2e6972b3b6086286fc64c0b3ee41.jpeg) # 1. 实时数据湖架构概述** 实时数据湖是一种现代数据管理架构,它允许企业以低延迟的方式收集、存储和处理大量数据。与传统数据仓库不同,实时数据湖不依赖于预先定义的模式,而是采用灵活的架构,可以处理各种数据类型和格式。这种架构为企业提供了以下优势: - **实时洞察:**实时数据湖允许企业访问最新的数据,从而做出更明智的决策。 - **数据民主化:**实时数据湖使各种利益相关者都可
recommend-type

spring添加xml配置文件

1. 创建一个新的Spring配置文件,例如"applicationContext.xml"。 2. 在文件头部添加XML命名空间和schema定义,如下所示: ``` <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans
recommend-type

JSBSim Reference Manual

JSBSim参考手册,其中包含JSBSim简介,JSBSim配置文件xml的编写语法,编程手册以及一些应用实例等。其中有部分内容还没有写完,估计有生之年很难看到完整版了,但是内容还是很有参考价值的。