写一个cnn模型代码用于图片情感分类 pytorch
时间: 2023-08-31 12:34:26 浏览: 140
### 回答1:
可以的,以下是一个使用 PyTorch 实现的 CNN 模型代码,用于图片情感分类:
```python
import torch
import torch.nn as nn
import torch.optim as optim
import torchvision.transforms as transforms
import torchvision.datasets as datasets
# 定义 CNN 模型
class CNN(nn.Module):
def __init__(self):
super(CNN, self).__init__()
self.conv1 = nn.Conv2d(3, 16, kernel_size=3, stride=1, padding=1)
self.bn1 = nn.BatchNorm2d(16)
self.relu1 = nn.ReLU()
self.pool1 = nn.MaxPool2d(kernel_size=2, stride=2)
self.conv2 = nn.Conv2d(16, 32, kernel_size=3, stride=1, padding=1)
self.bn2 = nn.BatchNorm2d(32)
self.relu2 = nn.ReLU()
self.pool2 = nn.MaxPool2d(kernel_size=2, stride=2)
self.fc1 = nn.Linear(32 * 8 * 8, 128)
self.relu3 = nn.ReLU()
self.fc2 = nn.Linear(128, 2)
def forward(self, x):
x = self.conv1(x)
x = self.bn1(x)
x = self.relu1(x)
x = self.pool1(x)
x = self.conv2(x)
x = self.bn2(x)
x = self.relu2(x)
x = self.pool2(x)
x = x.view(-1, 32 * 8 * 8)
x = self.fc1(x)
x = self.relu3(x)
x = self.fc2(x)
return x
# 加载数据集
transform = transforms.Compose([
transforms.Resize((32, 32)),
transforms.ToTensor(),
transforms.Normalize(mean=[.5, .5, .5], std=[.5, .5, .5])
])
train_dataset = datasets.ImageFolder(root='./train', transform=transform)
train_loader = torch.utils.data.DataLoader(train_dataset, batch_size=64, shuffle=True)
test_dataset = datasets.ImageFolder(root='./test', transform=transform)
test_loader = torch.utils.data.DataLoader(test_dataset, batch_size=64, shuffle=True)
# 定义损失函数和优化器
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters(), lr=.001)
# 训练模型
model = CNN()
for epoch in range(10):
running_loss = .
for i, data in enumerate(train_loader, ):
inputs, labels = data
optimizer.zero_grad()
outputs = model(inputs)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
running_loss += loss.item()
if i % 100 == 99:
print('[%d, %5d] loss: %.3f' % (epoch + 1, i + 1, running_loss / 100))
running_loss = .
# 测试模型
correct =
total =
with torch.no_grad():
for data in test_loader:
images, labels = data
outputs = model(images)
_, predicted = torch.max(outputs.data, 1)
total += labels.size()
correct += (predicted == labels).sum().item()
print('Accuracy: %d %%' % (100 * correct / total))
```
这个模型可以用于对图片进行情感分类,你可以将训练集和测试集的图片放在 `./train` 和 `./test` 目录下,然后运行这个代码即可。
### 回答2:
import torch
import torch.nn as nn
import torch.optim as optim
import torchvision.datasets as datasets
import torchvision.transforms as transforms
# 定义CNN模型
class CNN(nn.Module):
def __init__(self):
super(CNN, self).__init__()
self.conv1 = nn.Conv2d(in_channels=3, out_channels=16, kernel_size=3, stride=1, padding=1)
self.relu1 = nn.ReLU()
self.pool1 = nn.MaxPool2d(kernel_size=2)
self.conv2 = nn.Conv2d(in_channels=16, out_channels=32, kernel_size=3, stride=1, padding=1)
self.relu2 = nn.ReLU()
self.pool2 = nn.MaxPool2d(kernel_size=2)
self.fc1 = nn.Linear(32 * 8 * 8, 128)
self.relu3 = nn.ReLU()
self.fc2 = nn.Linear(128, 2) # 假设只有2种情感,正面和负面
def forward(self, x):
x = self.conv1(x)
x = self.relu1(x)
x = self.pool1(x)
x = self.conv2(x)
x = self.relu2(x)
x = self.pool2(x)
x = x.view(x.size(0), -1) # 扁平化
x = self.fc1(x)
x = self.relu3(x)
x = self.fc2(x)
return x
# 数据预处理
transform = transforms.Compose([
transforms.Resize(32),
transforms.ToTensor()
])
# 加载训练集和测试集
train_dataset = datasets.ImageFolder(root='train_path', transform=transform)
test_dataset = datasets.ImageFolder(root='test_path', transform=transform)
# 创建数据加载器
train_loader = torch.utils.data.DataLoader(train_dataset, batch_size=64, shuffle=True)
test_loader = torch.utils.data.DataLoader(test_dataset, batch_size=64, shuffle=True)
# 创建模型对象和损失函数
model = CNN()
criterion = nn.CrossEntropyLoss()
# 定义优化器
optimizer = optim.Adam(model.parameters(), lr=0.001)
# 训练模型
total_epochs = 10
for epoch in range(total_epochs):
for i, (images, labels) in enumerate(train_loader):
outputs = model(images)
loss = criterion(outputs, labels)
optimizer.zero_grad()
loss.backward()
optimizer.step()
if (i+1) % 10 == 0:
print('Epoch [{}/{}], Step [{}/{}], Loss: {:.4f}'.format(epoch+1, total_epochs, i+1, len(train_loader), loss.item()))
# 测试模型
model.eval()
with torch.no_grad():
correct = 0
total = 0
for images, labels in test_loader:
outputs = model(images)
_, predicted = torch.max(outputs.data, 1)
total += labels.size(0)
correct += (predicted == labels).sum().item()
print('Test Accuracy: {:.2f} %'.format(100 * correct / total))
### 回答3:
import torch
import torch.nn as nn
import torch.optim as optim
from torchvision import models
from torch.utils.data import DataLoader
from torchvision.datasets import ImageFolder
from torchvision.transforms import transforms
# 定义CNN模型
class CNNModel(nn.Module):
def __init__(self, num_classes):
super(CNNModel, self).__init__()
self.resnet = models.resnet18(pretrained=True)
self.resnet.fc = nn.Linear(512, num_classes)
def forward(self, x):
return self.resnet(x)
# 数据预处理
transform = transforms.Compose([
transforms.RandomResizedCrop(224),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
])
# 加载数据集
train_dataset = ImageFolder('./train', transform=transform)
test_dataset = ImageFolder('./test', transform=transform)
# 加载数据集至DataLoader
train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)
test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)
# 实例化模型和损失函数
model = CNNModel(num_classes=2) # 假设有2个情感类别
criterion = nn.CrossEntropyLoss()
# 迁移学习 - 冻结ResNet的所有参数
for param in model.resnet.parameters():
param.requires_grad = False
# 将分类层的参数设置为可训练
for param in model.resnet.fc.parameters():
param.requires_grad = True
# GPU计算
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model = model.to(device)
# 优化器
optimizer = optim.SGD(model.parameters(), lr=0.001, momentum=0.9)
# 训练模型
epochs = 10
for epoch in range(epochs):
running_loss = 0.0
for i, data in enumerate(train_loader):
inputs, labels = data
inputs = inputs.to(device)
labels = labels.to(device)
optimizer.zero_grad()
outputs = model(inputs)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
running_loss += loss.item()
if i % 10 == 9:
print('[%d, %5d] loss: %.3f' % (epoch + 1, i + 1, running_loss / 10))
running_loss = 0.0
print('Training finished!')
# 在测试集上评估模型
correct = 0
total = 0
with torch.no_grad():
for data in test_loader:
images, labels = data
images = images.to(device)
labels = labels.to(device)
outputs = model(images)
_, predicted = torch.max(outputs.data, 1)
total += labels.size(0)
correct += (predicted == labels).sum().item()
accuracy = 100 * correct / total
print('Accuracy on test set: {:.2f}%'.format(accuracy))
阅读全文