- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
大家,早安
下面是我对 pytorch siamese 网络的实现。我使用 32 批量大小、MSE 损失和 SGD 以 0.9 动量作为优化器。
class SiameseCNN(nn.Module):
def __init__(self):
super(SiameseCNN, self).__init__() # 1, 40, 50
self.convnet = nn.Sequential(nn.Conv2d(1, 8, 7), nn.ReLU(), # 8, 34, 44
nn.Conv2d(8, 16, 5), nn.ReLU(), # 16, 30, 40
nn.MaxPool2d(2, 2), # 16, 15, 20
nn.Conv2d(16, 32, 3, padding=1), nn.ReLU(), # 32, 15, 20
nn.Conv2d(32, 64, 3, padding=1), nn.ReLU()) # 64, 15, 20
self.linear1 = nn.Sequential(nn.Linear(64 * 15 * 20, 100), nn.ReLU())
self.linear2 = nn.Sequential(nn.Linear(100, 2), nn.ReLU())
def forward(self, data):
res = []
for j in range(2):
x = self.convnet(data[:, j, :, :])
x = x.view(-1, 64 * 15 * 20)
res.append(self.linear1(x))
fres = abs(res[1] - res[0])
return self.linear2(fres)
每个批次包含交替对,即
[pos, pos], [pos, neg], [pos, pos]
等等...然而,网络不收敛,问题似乎是
fres
在网络中每一对都是一样的(不管是正对还是负对),
self.linear2(fres)
的输出总是约等于
[0.0531, 0.0770]
.这与我所期望的相反,即
[0.0531, 0.0770]
的第一个值随着网络的学习,正对将接近 1,而负对的第二个值将接近 1。这两个值也需要相加为 1。
[pos, pos]
您将以深度方式堆叠这两个图像,例如
numpy.stack([pos, pos], -1)
.
nn.Conv2d(1, 8, 7)
尺寸也更改为
nn.Conv2d(2, 8, 7)
在这个设置中。这工作得很好。
def forward(self, data):
res = []
for j in range(2):
x = self.convnet(data[:, j, :, :])
x = x.view(-1, 64 * 15 * 20)
res.append(x)
fres = self.linear2(self.linear1(abs(res[1] - res[0]))))
return fres
torch.nn.PairwiseDistance
convnet
的输出之间.进行了某种改进;网络在前几个时期开始收敛,然后每次都达到相同的平台:def forward(self, data):
res = []
for j in range(2):
x = self.convnet(data[:, j, :, :])
res.append(x)
pdist = nn.PairwiseDistance(p=2)
diff = pdist(res[1], res[0])
diff = diff.view(-1, 64 * 15 * 10)
fres = self.linear2(self.linear1(diff))
return fres
另一件可能要注意的事情是,在我的研究范围内,为每个对象训练了一个 Siamese 网络。因此,第一类与包含相关对象的图像相关联,第二类与包含其他对象的图像相关联。不知道这是否可能是问题的原因。然而,在传统 CNN 和 2 channel CNN 方法的背景下,这不是问题。
model = SiameseCNN().cuda()
ls_fn = torch.nn.BCELoss()
optim = torch.optim.SGD(model.parameters(), lr=1e-6, momentum=0.9)
epochs = np.arange(100)
eloss = []
for epoch in epochs:
model.train()
train_loss = []
for x_batch, y_batch in dp.train_set:
x_var, y_var = Variable(x_batch.cuda()), Variable(y_batch.cuda())
y_pred = model(x_var)
loss = ls_fn(y_pred, y_var)
train_loss.append(abs(loss.item()))
optim.zero_grad()
loss.backward()
optim.step()
eloss.append(np.mean(train_loss))
print(epoch, np.mean(train_loss))
备注
dp
在
dp.train_set
是一个具有属性的类
train_set, valid_set, test_set
,其中每个集合的创建方式如下:
DataLoader(TensorDataset(torch.Tensor(x), torch.Tensor(y)), batch_size=bs)
根据请求,这是预测概率与真实标签的示例,您可以看到模型似乎没有在学习:
Predicted: 0.5030623078346252 Label: 1.0
Predicted: 0.5030624270439148 Label: 0.0
Predicted: 0.5030624270439148 Label: 1.0
Predicted: 0.5030625462532043 Label: 0.0
Predicted: 0.5030625462532043 Label: 1.0
Predicted: 0.5030626654624939 Label: 0.0
Predicted: 0.5030626058578491 Label: 1.0
Predicted: 0.5030627250671387 Label: 0.0
Predicted: 0.5030626654624939 Label: 1.0
Predicted: 0.5030627846717834 Label: 0.0
Predicted: 0.5030627250671387 Label: 1.0
Predicted: 0.5030627846717834 Label: 0.0
Predicted: 0.5030627250671387 Label: 1.0
Predicted: 0.5030628442764282 Label: 0.0
Predicted: 0.5030627846717834 Label: 1.0
Predicted: 0.5030628442764282 Label: 0.0
最佳答案
我认为你的方法是正确的,你做得很好。对我来说有点奇怪的是最后一层有 RELU 激活。通常对于连体网络,当两个输入图像属于同一类时,您希望输出高概率,否则输出低概率。因此,您可以使用单个神经元输出和 sigmoid 激活函数来实现这一点。
因此,我将重新实现您的网络如下:
class SiameseCNN(nn.Module):
def __init__(self):
super(SiameseCNN, self).__init__() # 1, 40, 50
self.convnet = nn.Sequential(nn.Conv2d(1, 8, 7), nn.ReLU(), # 8, 34, 44
nn.Conv2d(8, 16, 5), nn.ReLU(), # 16, 30, 40
nn.MaxPool2d(2, 2), # 16, 15, 20
nn.Conv2d(16, 32, 3, padding=1), nn.ReLU(), # 32, 15, 20
nn.Conv2d(32, 64, 3, padding=1), nn.ReLU()) # 64, 15, 20
self.linear1 = nn.Sequential(nn.Linear(64 * 15 * 20, 100), nn.ReLU())
self.linear2 = nn.Sequential(nn.Linear(100, 1), nn.Sigmoid())
def forward(self, data):
for j in range(2):
x = self.convnet(data[:, j, :, :])
x = x.view(-1, 64 * 15 * 20)
res.append(self.linear1(x))
fres = res[0].sub(res[1]).pow(2)
return self.linear2(fres)
然后为了与训练保持一致,您应该使用二元交叉熵:
criterion_fn = torch.nn.BCELoss()
当两个输入图像属于同一类时,请记住将标签设置为 1。
linear1
之后使用一点 dropout,大约有 30% 的概率丢弃一个神经元。层。
关于python - Pytorch Siamese 网络不收敛,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61793268/
已关闭。此问题不符合Stack Overflow guidelines 。目前不接受答案。 这个问题似乎与 help center 中定义的范围内的编程无关。 . 已关闭 3 年前。 此帖子于去年编辑
据我所知,在使用 GPU 训练和验证模型时,GPU 内存主要用于加载数据,向前和向后。据我所知,我认为 GPU 内存使用应该相同 1) 训练前,2) 训练后,3) 验证前,4) 验证后。但在我的例子中
我正在尝试在 PyTorch 中将两个复数矩阵相乘,看起来 the torch.matmul functions is not added yet to PyTorch library for com
我正在尝试定义二分类问题的损失函数。但是,目标标签不是硬标签0,1,而是0~1之间的一个 float 。 Pytorch 中的 torch.nn.CrossEntropy 不支持软标签,所以我想自己写
我正在尝试让 PyTorch 与 DataLoader 一起工作,据说这是处理小批量的最简单方法,在某些情况下这是获得最佳性能所必需的。 DataLoader 需要一个数据集作为输入。 大多数关于 D
Pytorch Dataloader 的迭代顺序是否保证相同(在温和条件下)? 例如: dataloader = DataLoader(my_dataset, batch_size=4,
PyTorch 的负对数似然损失,nn.NLLLoss定义为: 因此,如果以单批处理的标准重量计算损失,则损失的公式始终为: -1 * (prediction of model for correct
在PyTorch中,new_ones()与ones()有什么区别。例如, x2.new_ones(3,2, dtype=torch.double) 与 torch.ones(3,2, dtype=to
假设我有一个矩阵 src带形状(5, 3)和一个 bool 矩阵 adj带形状(5, 5)如下, src = tensor([[ 0, 1, 2], [ 3, 4,
我想知道如果不在第 4 行中使用“for”循环,下面的代码是否有更有效的替代方案? import torch n, d = 37700, 7842 k = 4 sample = torch.cat([
我有三个简单的问题。 如果我的自定义损失函数不可微会发生什么? pytorch 会通过错误还是做其他事情? 如果我在我的自定义函数中声明了一个损失变量来表示模型的最终损失,我应该放 requires_
我想知道 PyTorch Parameter 和 Tensor 的区别? 现有answer适用于使用变量的旧 PyTorch? 最佳答案 这就是 Parameter 的全部想法。类(附加)在单个图像中
给定以下张量(这是网络的结果 [注意 grad_fn]): tensor([121., 241., 125., 1., 108., 238., 125., 121., 13., 117., 12
什么是__constants__在 pytorch class Linear(Module):定义于 https://pytorch.org/docs/stable/_modules/torch/nn
我在哪里可以找到pytorch函数conv2d的源代码? 它应该在 torch.nn.functional 中,但我只找到了 _add_docstr 行, 如果我搜索conv2d。我在这里看了: ht
如 documentation 中所述在 PyTorch 中,Conv2d 层使用默认膨胀为 1。这是否意味着如果我想创建一个简单的 conv2d 层,我必须编写 nn.conv2d(in_chann
我阅读了 Pytorch 的源代码,发现它没有实现 convolution_backward 很奇怪。函数,唯一的 convolution_backward_overrideable 函数是直接引发错
我对编码真的很陌生,现在我正在尝试将我的标签变成一种热门编码。我已经完成将 np.array 传输到张量,如下所示 tensor([4., 4., 4., 4., 4., 4., 4., 4., 4.
我正在尝试实现 text classification model使用CNN。据我所知,对于文本数据,我们应该使用一维卷积。我在 pytorch 中看到了一个使用 Conv2d 的示例,但我想知道如何
我有一个多标签分类问题,我正试图用 Pytorch 中的 CNN 解决这个问题。我有 80,000 个训练示例和 7900 个类;每个示例可以同时属于多个类,每个示例的平均类数为 130。 问题是我的
我是一名优秀的程序员,十分优秀!