根据题目,猜想应该是跟图像相关对抗网络
查看 train.py,根据经验直到应该是梯度攻击
import torch
import torch.nn as nn
import torch.optim as optim
import torchvision.transforms as transforms
import numpy as np
from PIL import Image
import torch.nn.functional as F
class tanji_model(nn.Module):
def __init__(self):
super(tanji_model, self).__init__()
self.classifier = nn.Sequential(
nn.Linear(31 * 31, 512),
nn.ReLU(),
nn.Linear(512, 128),
nn.ReLU(),
nn.Linear(128, 1),
)
def forward(self, x):
x = torch.flatten(x, 1)
y = self.classifier(x)
return torch.sigmoid(y)
# 加载与训练模型文件model.pth
tanji = tanji_model().cpu()
tanji.load_state_dict(torch.load('model.pth'))
tanji.eval()
print(tanji)
# 创建一个跟flag一样的空白图片
flag_size = (31, 31)
img = torch.zeros((1, 1, * flag_size), requires_grad = True)
# 设置优化器
optimizer = optim.Adam([img], lr=0.001)
for i in range(10000):
# 把梯度置零
optimizer.zero_grad()
output = tanji(img)
# 计算损失 _ 最小化负对数似然损失
loss = -torch.log(F.sigmoid(output))
# 反向传播
loss.backward()
# 更新参数
optimizer.step()
with torch.no_grad():
img.clamp_(0, 1)
if i % 100 == 0:
print(f'Iteration {i}, Loss: {loss.item()}')
# 保存图片
optimized_image = transforms.ToPILImage()(img.squeeze(0))
# optimized_image = transforms.ToPILImage()(img[0].cpu()).save('flag.png')
optimized_image.show()
optimized_image.save('flag.png')