python 对比学习及 mnist cnn 分类 - cuda
python 对比学习及 mnist cnn 分类
对比学习
对比学习是一种无监督学习方法,旨在通过对比样本之间的相似性和差异性来学习数据的有效表示。其核心思想是通过构建正样本对和负样本对来训练模型,使得相似样本在嵌入空间中更接近,而不相似样本更远。
正负样本对
正样本对:由相似的样本组成,通常通过数据增强(如旋转、裁剪)生成同一图像的不同版本,或选择同一类别的样本。负样本对:由不相似的样本组成,通常通过随机选择不同类别的样本,或在一个批次中使用其他样本。
孪生网络
孪生网络(Siamese Network)是一种共享权重的双分支网络,用于对比学习任务。它的特点包括:
共享权重:两个分支共享相同的网络结构和权重,确保特征提取的一致性。处理不同输入:每个分支接收不同的输入样本,输出特征表示用于相似性比较。应用场景:广泛用于人脸验证、图像检索、对比学习等任务。
损失函数
在对比学习中,常用的损失函数是 InfoNCE(Information Noise-Contrastive Estimation)损失。其目标是:
最大化正样本对的相似度:通过计算正样本对的相似性,提升模型对相似样本的识别能力。最小化负样本对的相似度:通过计算负样本对的相似性,增强模型对不相似样本的区分能力。
InfoNCE 损失的公式为:
L
InfoNCE
=
−
log
exp
(
sim
(
q
,
k
0
)
/
τ
)
∑
i
=
0
N
exp
(
sim
(
q
,
k
i
)
/
τ
)
\mathcal{L}_{\text{InfoNCE}} = -\log \frac{\exp(\text{sim}(q, k_0) / \tau)}{\sum_{i=0}^{N} \exp(\text{sim}(q, k_i) / \tau)}
LInfoNCE=−log∑i=0Nexp(sim(q,ki)/τ)exp(sim(q,k0)/τ)
mnist cnn 对比学习进行分类案例
在 MNIST 数据集上使用对比学习进行分类的流程包括:
数据准备:加载 MNIST 数据集并进行数据增强。
构建样本对:生成正样本对和负样本对。
模型设计:使用共享权重的 CNN 作为特征提取器。
损失函数:使用对比损失(如 InfoNCE)来优化模型。
训练模型:通过对比学习训练模型,学习有效的特征表示。
分类任务:在嵌入表示上训练分类器进行最终分类。
评估模型:在测试集上评估模型性能,并可视化嵌入空间。
mnist cnn 对比学习分类代码
import torch
import torch.nn as nn
import torch.optim as optim
from torchvision import datasets, transforms
from torch.utils.data import DataLoader, Dataset
import numpy as np
import random
# 数据准备
transform = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.1307,), (0.3081,))
])
train_dataset = datasets.MNIST(root='./data', train=True, download=True, transform=transform)
test_dataset = datasets.MNIST(root='./data', train=False, download=True, transform=transform)
# 构建样本对
class SiameseMNIST(Dataset):
def __init__(self, mnist_dataset):
self.mnist_dataset = mnist_dataset
def __getitem__(self, index):
img1, label1 = self.mnist_dataset[index]
should_get_same_class = random.randint(0, 1)
if should_get_same_class:
while True:
index2 = random.randint(0, len(self.mnist_dataset) - 1)
img2, label2 = self.mnist_dataset[index2]
if label1 == label2:
break
else:
while True:
index2 = random.randint(0, len(self.mnist_dataset) - 1)
img2, label2 = self.mnist_dataset[index2]
if label1 != label2:
break
return img1, img2, torch.tensor([int(label1 == label2)], dtype=torch.float32)
def __len__(self):
return len(self.mnist_dataset)
train_loader = DataLoader(SiameseMNIST(train_dataset), batch_size=64, shuffle=True)
test_loader = DataLoader(SiameseMNIST(test_dataset), batch_size=64, shuffle=False)
# 模型设计
class SiameseNetwork(nn.Module):
def __init__(self):
super(SiameseNetwork, self).__init__()
self.cnn = nn.Sequential(
nn.Conv2d(1, 64, kernel_size=5),
nn.ReLU(inplace=True),
nn.MaxPool2d(2, 2),
nn.Conv2d(64, 128, kernel_size=5),
nn.ReLU(inplace=True),
nn.MaxPool2d(2, 2)
)
self.fc = nn.Sequential(
nn.Linear(128 * 4 * 4, 256), 拼多多帮助力入口
nn.ReLU(inplace=True),
nn.Linear(256, 128)
)
def forward_one(self, x):
x = self.cnn(x)
x = x.view(x.size()[0], -1)
x = self.fc(x)
return x
def forward(self, x1, x2):
output1 = self.forward_one(x1)
output2 = self.forward_one(x2)
return output1, output2
# 损失函数
class ContrastiveLoss(nn.Module):
def __init__(self, margin=1.0):
super(ContrastiveLoss, self).__init__()
self.margin = margin
def forward(self, output1, output2, label):
euclidean_distance = nn.functional.pairwise_distance(output1, output2)
loss_contrastive = torch.mean((1 - label) * torch.pow(euclidean_distance, 2) +
(label) * torch.pow(torch.clamp(self.margin - euclidean_distance, min=0.0), 2))
return loss_contrastive
# 训练模型
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model = SiameseNetwork().to(device)
criterion = ContrastiveLoss()
optimizer = optim.Adam(model.parameters(), lr=0.001)
def train(model, train_loader, criterion, optimizer, num_epochs=10):
model.train()
for epoch in range(num_epochs):
for batch_idx, (img1, img2, label) in enumerate(train_loader):
img1, img2, label = img1.to(device), img2.to(device), label.to(device)
optimizer.zero_grad()
output1, output2 = model(img1, img2)
loss = criterion(output1, output2, label)
loss.backward()
optimizer.step()
print(f'Epoch {epoch+1}, Loss: {loss.item()}')
train(model, train_loader, criterion, optimizer)
# 分类任务
class Classifier(nn.Module):
def __init__(self, feature_extractor):
super(Classifier, self).__init__()
self.feature_extractor = feature_extractor
self.fc = nn.Linear(128, 10)
def forward(self, x):
with torch.no_grad():
x = self.feature_extractor.forward_one(x)
x = self.fc(x)
return x
classifier = Classifier(model).to(device)
criterion_cls = nn.CrossEntropyLoss()
optimizer_cls = optim.Adam(classifier.fc.parameters(), lr=0.001)
def train_classifier(classifier, train_loader, criterion, optimizer, num_epochs=10):
classifier.train()
for epoch in range(num_epochs):
for batch_idx, (img1, _, label) in enumerate(train_loader):
img1, label = img1.to(device), label.to(device).squeeze().long()
optimizer.zero_grad()
output = classifier(img1)
loss = criterion(output, label)
loss.backward()
optimizer.step()
print(f'Epoch {epoch+1}, Classifier Loss: {loss.item()}')
train_classifier(classifier, train_loader, criterion_cls, optimizer_cls)
# 评估模型
def evaluate(classifier, test_loader):
classifier.eval()
correct = 0
total = 0
with torch.no_grad():
for img1, _, label in test_loader:
img1, label = img1.to(device), label.to(device).squeeze().long()
outputs = classifier(img1)
_, predicted = torch.max(outputs.data, 1)
total += label.size(0)
correct += (predicted == label).sum().item()
print(f'Accuracy: {100 * correct / total}%')
evaluate(classifier, test_loader)
代码实现了一个简单的对比学习流程,使用共享权重的 CNN 作为特征提取器,并在嵌入表示上训练分类器进行最终分类。在运行代码前安装必要的库,如 torch 和 torchvision。
对比学习可以有效地在 MNIST 数据集上进行分类任务,展示了其在无监督特征学习中的强大能力。
python 对比学习及 mnist cnn 分类
参考链接