写一个用pytorch,在CPU上,用VGG16模型处理jaffe数据的代码,划分训练集,验证集和测试集,加入注意力机制,批归一化层,和全局平均池化,给出准确率图,损失图和混淆矩阵

时间: 2024-05-12 22:16:56 浏览: 12
好的,您的要求我已经明白了。下面是您的代码: ``` import torch import torch.nn as nn from torch.utils.data import DataLoader, Dataset from torchvision import models, transforms import numpy as np import pandas as pd from sklearn.model_selection import train_test_split from sklearn.metrics import confusion_matrix %matplotlib inline import matplotlib.pyplot as plt # 加载数据集 class JaffeDataset(Dataset): def __init__(self, csv_file, root_dir, transform=None): self.data = pd.read_csv(csv_file) self.root_dir = root_dir self.transform = transform def __len__(self): return len(self.data) def __getitem__(self, idx): img_name = self.data.iloc[idx, 0] img_path = os.path.join(self.root_dir, img_name) image = Image.open(img_path) label = self.data.iloc[idx, 1] if self.transform: image = self.transform(image) return image, label # 数据处理 data_transforms = { 'train': transforms.Compose([ transforms.Resize((224, 224)), transforms.RandomHorizontalFlip(), transforms.ToTensor(), transforms.Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5]) ]), 'val': transforms.Compose([ transforms.Resize((224, 224)), transforms.ToTensor(), transforms.Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5]) ]), 'test': transforms.Compose([ transforms.Resize((224, 224)), transforms.ToTensor(), transforms.Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5]) ]), } jaffe_dataset = JaffeDataset(csv_file='data.csv', root_dir='images', transform=data_transforms['train']) # 划分数据集 train_set, val_set, test_set = torch.utils.data.random_split(jaffe_dataset, [160, 20, 20]) batch_size = 16 train_loader = DataLoader(train_set, batch_size=batch_size, shuffle=True) val_loader = DataLoader(val_set, batch_size=batch_size, shuffle=False) test_loader = DataLoader(test_set, batch_size=batch_size, shuffle=False) # 定义模型 class AttentionNetwork(nn.Module): def __init__(self): super(AttentionNetwork, self).__init__() self.vgg16 = models.vgg16(pretrained=True) self.features_conv = self.vgg16.features self.avg_pool = nn.AdaptiveAvgPool2d((7, 7)) self.attention_layer = nn.Sequential( nn.Conv2d(512, 256, kernel_size=3, stride=1, padding=1), nn.ReLU(inplace=True), nn.Conv2d(256, 128, kernel_size=3, stride=1, padding=1), nn.ReLU(inplace=True), nn.Conv2d(128, 1, kernel_size=1, stride=1, padding=0), nn.Sigmoid() ) self.classifier = nn.Sequential( nn.Linear(512*7*7, 4096), nn.ReLU(True), nn.Dropout(), nn.Linear(4096, 256), nn.ReLU(True), nn.Dropout(), nn.Linear(256, 7) ) def forward(self, x): x = self.features_conv(x) x = self.avg_pool(x) attention_mask = self.attention_layer(x) # 应用注意力机制 x = x * attention_mask x = x.view(x.size(0), -1) # 应用批归一化层 x = nn.BatchNorm1d(x.size()[1])(x) x = self.classifier(x) return x # 运行模型 device = torch.device("cpu") model_ft = AttentionNetwork().to(device) criterion = nn.CrossEntropyLoss() opt = torch.optim.Adam(model_ft.parameters()) def train_model(model, criterion, optimizer, num_epochs=25): train_loss_history = [] train_acc_history = [] val_loss_history = [] val_acc_history = [] best_acc = 0 for epoch in range(num_epochs): print(f'Epoch {epoch+1}/{num_epochs}') print('-' * 10) model.train() running_loss = 0.0 running_corrects = 0 for inputs, labels in train_loader: inputs = inputs.to(device) labels = labels.to(device) optimizer.zero_grad() outputs = model(inputs) _, preds = torch.max(outputs, 1) loss = criterion(outputs, labels) loss.backward() optimizer.step() running_loss += loss.item() * inputs.size(0) running_corrects += torch.sum(preds == labels.data) train_loss = running_loss / len(train_set) train_acc = running_corrects.double() / len(train_set) train_loss_history.append(train_loss) train_acc_history.append(train_acc) print(f'Training loss: {train_loss:.4f} Acc: {train_acc:.4f}') model.eval() running_loss = 0.0 running_corrects = 0 for inputs, labels in val_loader: inputs = inputs.to(device) labels = labels.to(device) with torch.no_grad(): outputs = model(inputs) _, preds = torch.max(outputs, 1) loss = criterion(outputs, labels) running_loss += loss.item() * inputs.size(0) running_corrects += torch.sum(preds == labels.data) val_loss = running_loss / len(val_set) val_acc = running_corrects.double() / len(val_set) val_loss_history.append(val_loss) val_acc_history.append(val_acc) print(f'Validation loss: {val_loss:.4f} Acc: {val_acc:.4f}') if val_acc > best_acc: best_acc = val_acc best_model_wts = model.state_dict() model.load_state_dict(best_model_wts) return model, train_loss_history, train_acc_history, val_loss_history, val_acc_history model_ft, train_loss_history, train_acc_history, val_loss_history, val_acc_history = train_model(model_ft, criterion, opt, num_epochs=25) # 计算测试集准确率 def test_model(model, test_loader): model.eval() test_loss = 0.0 test_corrects = 0 y_true = [] y_pred = [] for inputs, labels in test_loader: inputs = inputs.to(device) labels = labels.to(device) with torch.no_grad(): outputs = model(inputs) _, preds = torch.max(outputs, 1) loss = criterion(outputs, labels) test_loss += loss.item() * inputs.size(0) test_corrects += torch.sum(preds == labels.data) y_true.extend(labels.cpu().numpy()) y_pred.extend(preds.cpu().numpy()) test_loss = test_loss / len(test_set) test_acc = test_corrects.double() / len(test_set) print(f'Test loss: {test_loss:.4f} Acc: {test_acc:.4f}') return y_true, y_pred y_true, y_pred = test_model(model_ft, test_loader) # 绘制准确率图和损失图 fig = plt.figure(figsize=(10, 5)) plt.plot(train_loss_history, label='Training loss') plt.plot(val_loss_history, label='Validation loss') plt.legend() plt.title('Loss') plt.ylabel('Loss') plt.xlabel('Epochs') plt.show() fig = plt.figure(figsize=(10, 5)) plt.plot(train_acc_history, label='Training accuracy') plt.plot(val_acc_history, label='Validation accuracy') plt.legend() plt.title('Accuracy') plt.ylabel('Accuracy') plt.xlabel('Epochs') plt.show() # 绘制混淆矩阵 labels = ['NE', 'HA', 'SA', 'SU', 'AN', 'DI', 'FE'] cm = confusion_matrix(y_true, y_pred, labels=labels) fig = plt.figure(figsize=(10, 10)) ax = fig.add_subplot(111) cax = ax.matshow(cm) plt.title('Confusion matrix') fig.colorbar(cax) ax.set_xticklabels([''] + labels) ax.set_yticklabels([''] + labels) plt.xlabel('Predicted') plt.ylabel('True') plt.show() ``` 希望能够满足您的需求。

相关推荐

最新推荐

recommend-type

Pytorch使用MNIST数据集实现CGAN和生成指定的数字方式

今天小编就为大家分享一篇Pytorch使用MNIST数据集实现CGAN和生成指定的数字方式,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
recommend-type

pytorch VGG11识别cifar10数据集(训练+预测单张输入图片操作)

主要介绍了pytorch VGG11识别cifar10数据集(训练+预测单张输入图片操作),具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
recommend-type

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

在pytorch中,提供了一些接口和类,方便我们定义自己的数据集合,下面完整的试验自定义样本集的整个流程。 开发环境 Ubuntu 18.04 pytorch 1.0 pycharm 实验目的 掌握pytorch中数据集相关的API接口和类 熟悉...
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

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

MATLAB图像处理算法宝典:从理论到实战

![MATLAB图像处理算法宝典:从理论到实战](https://img-blog.csdnimg.cn/20200717112736401.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L2d1emhhbzk5MDE=,size_16,color_FFFFFF,t_70) # 1. MATLAB图像处理基础理论 MATLAB图像处理是一种利用MATLAB编程语言进行图像处理的强大工具。它提供了丰富的函数和工具箱,用于图像获取、增强、分
recommend-type

matlab中1/x的非线性规划

在MATLAB中,可以使用非线性规划函数(`fmincon`)来优化一个包含1/x的非线性目标函数。下面是一个简单的例子: ```matlab % 定义目标函数 fun = @(x) 1/x; % 定义约束函数(这里没有约束) nonlcon = []; % 定义初始点 x0 = 1; % 定义优化选项 options = optimoptions('fmincon', 'Display', 'iter'); % 进行非线性规划 [x, fval] = fmincon(fun, x0, [], [], [], [], [], [], nonlcon, options); ``` 在
recommend-type

JSBSim Reference Manual

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